_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d4801
train
When you use the colon in function AI:UnitCreated(unit), it creates a hidden self parameter that receives the AI instance. It actually behaves like this: function AI.UnitCreated(self, unit) So when calling that function from C, you need to pass both parameters: the ai instance and the unit parameter. Since you passed only one parameter, self was set to it and unit was set to nil.
unknown
d4802
train
You will need to compare the current mouse state and the last update's mouse state. In your class you'll have MouseState mouseStateCurrent, mouseStatePrevious; declared and so it'll be something like: mouseStateCurrent = Mouse.GetState(); if (mouseStateCurrent.LeftButton == ButtonState.Pressed && mouseStatePrevious.LeftButton == ButtonState.Released) { currentSelection++; } mouseStatePrevious = mouseStateCurrent; So it will detect that previous time you pressed it, then you release it - only then it is considered as a click and it will add to currentSelection.
unknown
d4803
train
As far as I know, libpcap put a timestamp on each packet. No, libpcap gets a timestamp for the packet from the OS packet capture mechanism that it uses - which, on Linux is... ...PF_PACKET sockets. The Linux kernel time stamps incoming packets. PF_PACKET sockets have multiple ways of reading from them: * *regular socket receives, for which you can either get a time stamp with an explicit ioctl (so you can avoid fetching it to userland, but you can't avoid the kernel time stamping the packet in the first place; libpcap, when using regular socket receives, always asks for the time stamp); *memory-mapped access, which always supplies the time stamp. Libpcap uses memory-mapped access whenever it's available; if you care about capture performance, you probably want to do so as well. It's not easy to use, however.
unknown
d4804
train
Their is no difficulty with that. First if we talk about your left UIImageView, Set following constraints, * *Leading constraint *Fixed Height *Fixed Width *Centre Vertically After that the UIImageView on left, set following constraints, * *Trailing space from superview *Fixed Height *Fixed Width *Centre Vertically Now for both Labels, put them in a UIView and give that UIView following constraints, * *Leading space from left image view. *trailing space from right image view. *top space from superview *bottom space from superview Now for upper UILabel, Set following constraints, * *Leading space *Trailing space *top space Now for lower UILabel, Set following constraints, * *Leading space *Trailing space *top space from upper UILabel *bottom space After all this, i think that this will work for you. A: You can use the constraints in the image below. It will work for all screen size and for any height of row.
unknown
d4805
train
I have these two functions for you, to shift in a byte-array: static public void ShiftLeft(this byte[] data, int count, bool rol) { if ((count <0) || (count > 8)) throw new ArgumentException("Count must between 0 and 8."); byte mask = (byte)(0xFF << (8 - count)); int bits = rol ? data[0] & mask : 0; for (int i = data.Length - 1; i >= 0; i--) { int b = data[i] & mask; data[i] = (byte)((data[i] << count) | (bits >> (8 - count))); bits = b; } } static public void ShiftRight(this byte[] data, int count, bool rol) { if ((count <0) || (count > 8)) throw new ArgumentException("Count must between 0 and 8."); byte mask = (byte)(0xFF >> (7 - count)); int bits = rol ? data[data.Length - 1] & mask : 0; for (int i = 0; i < data.Length; i++) { int b = data[i] & mask; data[i] = (byte)((data[i] >> count) | (bits << (8 - count))); bits = b; } } For your code example, call them like this: byte[] data = ...; ShiftLeft(data, 2, false); Assuming you want to copy 2 bytes into 1 ushort, you can use this code (make sure it is even in length!): byte[] data = ...; short[] sdata = new short[data.Length / 2]; Buffer.BlockCopy(data, 0, sdata, 0, dataLen); If you want to copy 1 byte into 1 ushort, then this would be the answer: byte[] data = ...; short[] sdata = Array.ConvertAll(data, b => (short)b); A: I take your question to mean you want to do this conversion: combine aaaaaaaa and bbbbbbbb into bbbbbbbbaaaaaaaa and then apply a right-shift by 6, yielding 000000bbbbbbbbaa. Then this will be your code: using System; public class Test { public static void Main() { byte[] src = new byte[2] { 192, 85 }; ushort[] tgt = new ushort[1]; for ( int i = 0 ; i < src.Length ; i+=2 ) { tgt[i] = (ushort)( ( src[i+1]<<8 | src[i] )>>6 ); } System.Console.WriteLine( tgt[0].ToString() ); } } If what you want to do is combine to aaaabbbbbbbbaa, then this will require |-ing a src[i]<<10 in a second step, as there is no circular shift operator in C#. A: my final code :D public override short[] GetShortDataAlignedRight() { short[] ReturnArray = new short[_channels[0].Data.Length / 2]; if (_channels[0].Bpp == 8) { Buffer.BlockCopy(_channels[0].Data, 0, ReturnArray, 0, _channels[0].Data.Length); } else { short tempData; int offsetHigh = 8 - (16 - _channels[0].Bpp); int offsetLow = (16 - _channels[0].Bpp); for (int i = 0, j = 0; i < _channels[0].Data.Length; i += 2, j++) { tempData = (short)(_channels[0].Data[i] >> offsetLow); tempData |= (short)(_channels[0].Data[i + 1] << offsetHigh); ReturnArray[j] = tempData; } } return ReturnArray; }
unknown
d4806
train
Thanks for your replies!!! Using FormulaLocal works great!!! What I did was to "translate" the functions names and done! Cells(LastRow + 1, 3).Formula = "=IFERROR(VLOOKUP(" & "B" & laststr & " , Datos!A2:E52, 3), """")" A: Please refer to the answer by Monster for the correct solution to the problem. I have to leave this answer here until it is "unaccepted", and then I will be able to delete it. To enter locale-dependent formulas, you need to use FormulaLocal: Cells(LastRow + 1, 3).FormulaLocal = "=SI.ERROR(BUSCARV(B" & laststr & " , Datos!A2:E52, 3), """")"
unknown
d4807
train
Make sure your execute() method just being invoked. If you're using @Scheduled, make sure that you have the @EnableScheduling annotation, for example: @SpringBootApplication @EnableScheduling // Make sure this is present public class ScheduledTaskApplication { private static final Logger log = LogManager.getLogger(); public static void main(String[] args) { log.info("Scheduler is testing"); SpringApplication.run(ScheduledTaskApplication.class, args); } @Scheduled(cron="*/2 * * * * *") public void execute() { //following not getting printed log.info("Scheduler ...."); } } Additionally, make sure that you configured the logging.config property in application.properties: logging.config=classpath:log4j2.properties If you don't do this, it seems that the logging behaves weird, since the message in main() will be written to the proper logger, but afterwards it changes it to the rootLogger, causing all other messages within that class (not only the messages within test() to be written to the console).
unknown
d4808
train
@Unimportant's comment solved the issue. Both pure virtual and non-pure virtual functions must all have a body. Changed my win_home.h to: #include "win_home.h" HomeGUI::HomeGUI() { //build interface/gui this->buildInterface(); //retrieve printers //create printer Buttons //register Handlers //this->registerHandlers(); } HomeGUI::~HomeGUI() { } void HomeGUI::buildInterface() { //combo boxes /* Gtk::HBox combo_rowbox = Gtk::HBox(false, 10); Gtk::ComboBox combobox_department = Gtk::ComboBox(false); Gtk::ComboBox combobox_building = Gtk::ComboBox(false); combo_rowbox.pack_start(child, false, false, padding=0) add(combo_rowbox); */ return; } void HomeGUI::registerHandlers() { }
unknown
d4809
train
UPDATED Please replace this with your code <div id="container"> <iframe width="560" height="315" src="https://www.youtube.com/embed/NhxVR2Szu3k" frameborder="0" allowfullscreen></iframe> </div> and css #container { border: 1px solid red; text-align:center; width: 80%; margin-left:auto; margin-right:auto; } as you are not using correct code for video..go in video link..then share and then embed code and take that code and it will work..hope this help. Updated : now your video is responsive..change width according to your need. A: I didn't clearly understand what you're trying to achieve but try this example: <html> <head> </head> <body> <div style="text-align:center"> <button onclick="playPause()">Play/Pause </button> <br> <video id="video" width="420"> <source src="video.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> </div> <script> var myVideo = document.getElementById("video "); function playPause() { if (myVideo.paused) myVideo.play(); else myVideo.pause(); } </script> </body> </html>
unknown
d4810
train
Your graphs are isomorphic (have the same structure) but are different Python objects. You can test isomorphism with nx.is_ismorphic import networkx as nx G1 = nx.Graph() G1.add_edge(1, 2) G1.edges() # [(1, 2)] G1.degree(1) # 1 G2 = nx.Graph() G2.add_edges_from([(1, 2), (1, 2)]) G2.edges() # [(1, 2)] G2.degree(1) # 1 print G1==G2 # False print repr(G1),repr(G2) print nx.is_isomorphic(G1,G2) #OUTPUT # False #<networkx.classes.graph.Graph object at 0x7fda3174c050> <networkx.classes.graph.Graph object at 0x7fda3463e890> #True
unknown
d4811
train
You could take advantage of the cy.spy command: cy.intercept('/my-route', cy.spy().as('myRequest')); // later in the test cy.get('@myRequest').should('not.have.been.called'); // not yet intercepted // something triggers the API call cy.get('@myRequest').should('have.been.calledOnce'); // now is intercepted See: https://docs.cypress.io/api/commands/spy Credits to: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the-network-call-has-not-been-made A: Intercept has a routeHandler section which can be a function cy.intercept(routeMatcher, routeHandler?) routeHandler (string | object | Function | StaticResponse) The function receives the request, and inside that another function can receive the response, see Intercepting a response cy.intercept('/integrations', (req) => { // req.continue() with a callback will send the request to the destination server req.continue((res) => { // 'res' represents the real destination response // you can manipulate 'res' before it's sent to the browser }) }) so either on the receipt of req or the inner function on receipt of res, set an external flag and test it at one or more places in the test, // top of the test let interceptFlag = false; cy.intercept('/my-route', (req) => { interceptFlag = true; req.continue((res) => { // or here interceptFlag = true; }) }) // later in the test cy.wrap(interceptFlag).should('eq', false); // not yet intercepted // something triggers the API call cy.wrap(interceptFlag).should('eq', true); // now is intercepted This is very generalized, if you post some details can be more specific.
unknown
d4812
train
In SQL Server 2008 onwards you can cast to time datatype: SELECT CAST(dbo.tbReceiptLine.Time as time) See The ultimate guide to the datetime datatypes
unknown
d4813
train
First of all, add that method that would return person's age to your Person model class: public function getAgeAttribute() { return (int) ((time() - strtotime($this->born_at) / 3600 / 24 / 365); } In your controller you'll need to pass a model object to the view: public someControllerAction() { // get person from the database or create a new model $person = ...; return view('some.view')->with(['person' => $person]); } And then, in the Blade template you can display age by doing: {{ $person->age }} I'm just not sure why you mention resource controllers. Usually they do not have a related view that they use to render HTML, but instead they return plain data, that is later serialized (e.g. to JSON) and used as controller response.
unknown
d4814
train
Here is my solution with ScheduledThreadPoolExecutor. To cancel existing tasks, issue future.cancel() on Future object returned from scheduleAtFixedRate(). Then call scheduleAtFixedRate() again with initial delay set to 0. class HiTask implements Runnable { @Override public void run() { System.out.println("Say Hi!"); } } // periodically execute task in every 100 ms, without initial delay time ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); long initialDelay = 0; long period = 100; ScheduledFuture<?> future1 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS); // to trigger task execution immediately boolean success = future.cancel(true); // mayInterruptIfRunning = true: interrupt thread even task has already started ScheduledFuture<?> future2 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS); A: Options you have with ScheduledExecutorService: * *submit() the same task again in the moment you need the data to be refreshed. If will be immediately executed (and only once). Possible drawback: If this happens very close to a scheduled execution, you have two scans with very little time in between. *cancel() the Tasks in the moment you need the data to be refreshed, submit() it once for immediate execution and and schedule() for repeated execution. Be aware that any exceptions that occur in the task that are unhandled cancel future executions. How to solve that is answered in How to reschedule a task using a ScheduledExecutorService?. ExecutorService is not persistent (i.e. does not survive device reboot). I don't know if that's a problem for you. If it is there are libraries specialized on background task execution on Android: * *smart-scheduler-android *android-priority-jobqueue *android-job You would have to apply the same workarounds mentioned above.
unknown
d4815
train
When you split by density, the Android plugin will always generate an "additional" APK for devices whose screen densities are not supported (at least yet). As per their documentation: Because each APK that's based on screen density includes a tag with specific restrictions about which screen types the APK supports, even if you publish several APKs, some new devices will not match your multiple APK filters. As such, Gradle always generates an additional universal APK that contains assets for all screen densities and does not include a tag. You should publish this universal APK along with your per-density APKs to provide a fallback for devices that do not match the APKs with a tag. In your case, because you're also splitting by ABI, you get two "additional" APKs instead of just one.
unknown
d4816
train
I frankly don't have experience with Tera Term in particular, but I've programmed Atmel MCUs before and there seem to be issues with your general C code, rather than the MCU functions. The C compiler errors can be often hard to read, but I can see you're mixing up the structure definition, declaration and initialization, as well as struggle with pointers. Consider the following plain C code and let's go over the differences with yours. #include <stdio.h> #include <stdint.h> int main(void) { struct date_struct { uint8_t month; uint8_t date; uint8_t year; }; // Define a structure named date_struct typedef struct date_struct date_struct_type; // make 'struct date_struct' into a new type date_struct_type date; // Declare a variable of the new type date.month = 0x03; // Initialize the fields of the variable date.date = 0x24; date.year = 0x21; date_struct_type * date_ptr; // Create a new pointer to the struct date_ptr = &date; // Assign the address of the variable to the pointer // Use the pointer to adress the structure's values printf("Month: %d\nDate: %d\nYear: %d\n", date_ptr->month, date_ptr->date, date_ptr->year); // ... or pass the pointer into any hypothetical function // func(date_ptr); // ... or pass a reference to the structure, but never a reference to the pointer // unless you know that you need it! // func(&date); return 0; } In your code, you first define an anonymous local structure and immediately typedef it to create a new type. That means, from that point on, you work with the structure as if it was just a variable type. In my code, I split up the structure definition and the typedef into two individual statements. That code is identical to writing typedef struct date_struct { uint8_t Month; uint8_t Date; uint8_t Year; } date_struct_type; // Define and typedef a structure at the same time ... or we can even leave the structure's name out and leave it anonymous - like you did in your code - we don't need it named at all since we already have a new type made out of it that we can use. typedef struct // <-- leave out the name { uint8_t Month; uint8_t Date; uint8_t Year; } date_struct_type; // Define and typedef a structure at the same time However, a structure definition is a "template" that tells the compiler how to allocate and access the structure in memory. The definition itself doesn't store any values and as such, we can't assign to it. We first need to declare a variable of that type*. date_struct_type date; * C is a very wild language, and you can do and use all sorts of shorthands, such as this. However, I strongly recommend against doing this when you're just starting out (and also in the future), as it's really not needed and is harder to read, maintain and debug. With the variable in place, we can finally assign our values to the individual elements of the structure. When accessing members of a structure we use the member reference operator - .. date.month = 0x03; date.date = 0x24; date.year = 0x21; Now we're moving to pointers and the two magical operators - * and & in C, that often cause a lot of headaches. In your code, you've successfully declared a pointer with this: uint8_t *Date;. Here, the * is not an operator, it signifies the variable holds a pointer - in other words, the uint8_t *Date; says "There is a variable named Date and it will hold an address of a uint8_t variable somewhere in the memory". However, that is not what we intend - we want to point to our new structure, not the uint8_t. Pointers all have the same size (in your case 32 bits on the smt32 platform), so it works, but that's what's setting off the "incompatible pointer type" warnings of your compiler. Instead, we should declare a pointer of the same type as the variable we intend to "point at" using this pointer. We'll once again split up the declaration and assignment statements for clarity - we're doing two things, writing them as one statement is just a shorthand. date_struct_type * date_ptr; The assignment is where the & operator comes into play. The & operator takes any variable and returns an address to it - which is exactly the thing we want to store inside our pointer. date_ptr = &date; Now whenever we want to pass a pointer to our new structure, either we use the one we just created - date_ptr, or directly pass a reference to the structure - &date. Both are viable, but be sure to not mistakenly write this: &date_prt. This gives you a pointer to a pointer, which is not something you usually want. A few more things. When accessing member of a structure through a pointer to that structure, we have to use a structure dereference operator - ->. That's why the printf statement contains -> operators instead of just .. I'm sure with this you can tweak your code to have it work. There shouldn't be any more issues in your function calls and the infinite while loop, just pay attention which pointers are you passing into the HAL_RTC_SetDate and HAL_RTC_GetDate functions. Do ask in the comments if there's still anything unclear or not working!
unknown
d4817
train
Try this: @Override public void onBindViewHolder(ViewHolder holder, int position) { if(position ==0){ holder.colorButton.setBackgroundResource(R.drawable.colorpicker2); } else { GradientDrawable gd = context.getResources().getDrawable(R.drawable.bbshape); gd.setColor(Color.parseColor(colors[position])); holder.colorButton.setBackGroundDrawable(gd); } }
unknown
d4818
train
Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools. The most general solution is to use a HTML parser. A good one in C is HTMLparser from libxml.
unknown
d4819
train
This appears to be a language feature that was introduced in Fortran 90. A first hint is the mention of this syntax on the Wikipedia article on Fortran 95, where it is referred to as "array-valued constants (constructors)". Chapter 4 of the Programmer's Guide to Fortran 90, 3nd [sic!] Edition has a little more information about (/ … /) in Chapter 4.1.4. (Due to the copyright statement I may not reproduce the relevant text passage here, but it's freely accessible through the above hyperlink.)
unknown
d4820
train
if you want to use mobile properties with openlayers as panning or zooming with hand you have to use openlayers.mobile.js. you can use openlayers.light.js with mobile devices but not mobile functions. i think your structure should be : myProject /js openlayers.light.js /img /theme and i have tried openlayers.light.js in http://jsfiddle.net/aragon/ZecJj/ and there is no problem with it. My code: var map = new OpenLayers.Map({ div: "map", minResolution: "auto", maxResolution: "auto", }); var osm = new OpenLayers.Layer.OSM(); var toMercator = OpenLayers.Projection.transforms['EPSG:4326']['EPSG:3857']; var center = toMercator({x:-0.05,y:51.5}); map.addLayers([osm]); map.setCenter(new OpenLayers.LonLat(center.x,center.y), 13); and try to read Deploying (Shipping OpenLayers in your Application). OpenLayers comes with pre-configured examples out of the box: simply download a release of OpenLayers, and you get a full set of easy to use examples. However, these examples are designed to be used for development. When you’re ready to deploy your application, you want a highly optimized OpenLayers distribution, to limit bandwidth and loading time. you can change src file with this link and can see it still works. <script type="text/javascript" src="http://openlayers.org/dev/OpenLayers.light.debug.js"></script> to <script type="text/javascript" src="https://view.softwareborsen.dk/Softwareborsen/Vis%20Stedet/trunk/lib/OpenLayers/2.12/OpenLayers.light.js?content-type=text%2Fplain"></script> i hope it helps you...
unknown
d4821
train
Found what I needed: QProcess CommandPrompt; QStringList Arguments; Arguments << "/K" << "echo" << "hello"; CommandPrompt.startDetached("cmd",Arguments);
unknown
d4822
train
Take a look at this question. I debugged your code and I experienced that exact behavior. The accepted answer explains quite well what's happening and also provides a solution. I tried with boost, I changed cin >> uInput; to string inputString; // so you know what inputString is getline(cin, inputString); uInput = boost::lexical_cast<int>(line); and it's working fine now.
unknown
d4823
train
The user interface changed overnight. Now you have to use Deploy button: A: you are right! As per the new deployment "save" button is integrated within each module. So you don't need to globally save all changes at once instead you can save only the particular setting. Likewise you can directly deploy scripts from the function code.
unknown
d4824
train
There is a known bug happening on some devices for the image captures described here: https://code.google.com/p/android/issues/detail?id=1480 Not sure if your problem is the same, but you should try the code explained in this answer from another question: https://stackoverflow.com/a/1932268/2206688 A: McAfee Antivirus may be the culprit in this case. In which case, uninstalling it should solve the issue.
unknown
d4825
train
ajax.open("POST",'http://www.xxxx.php',false); ^^^^^^ You are making a synchronous request, so the request is being made and the response received before you assign your event handler. Don't do that. Remove false (or change it to true).
unknown
d4826
train
You can use must clause.That will perform and operation "query": { "bool": { "must": [ { "query_string": { "default_field": "thread_name", "query": "apple" } }, { "query_string": { "default_field": "site_name", "query": "test_site" } } ] } }
unknown
d4827
train
This is primarily a syntax error, the correct syntax should be: $query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'"; Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times. The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements. The correct way if(count($user_id_pc)) { $stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE postcode_ss = ?"); mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'"); mysqli_stmt_execute($stmt); } Note that the for loop has been replaced by a simple if A: You have to check the query variable, instead of: $query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'" have you tried this: $query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '" . $user_id_pc[$i] . "' "; And another thing, try something different like this: while ($row = mysqli_fetch_array($job_data)) { $job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info"); } Then try to print the values. A: Sorry but I like foreach(), so your working code is: <?php // To store the result $job_results = []; foreach($user_id_pc as $id ){ // selecting matching rows $query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'"; $job_data = mysqli_query($dbc, $query2); // checking if query fetch any result if(mysqli_num_rows($job_data)){ // fetching the result while ($row = mysqli_fetch_array($job_data)){ // storing resulting row $job_results[] = $row; } } } // to print the result var_dump($job_results);
unknown
d4828
train
It can by hosted on azure, but domain will be www.example.net/wordpresssite or wordpresssite.example.net A: Here are the detailed steps for you to configure your custom domain, you could refer to it. I assume that your domain is example.co.uk and the domain of your back-end hosted on Azure is wordpresssite.azurewebsites.net by default. Firstly, you need to log in to your domain registrar and add a CNAME record as follows: |---------FQDN EXAMPLE--------|--CNAME HOST---|------------CNAME VALUE----------| | wordpresssite.example.co.uk | wordpresssite | wordpresssite.azurewebsites.net | Then, you need to log in to the Azure Portal, select your web app, click Custom domains > Add hostname to enable the custom domain name for your app. After you finish the configuration steps,it would take some period for the changes to propagate, depending on your DNS provider. And you could verify the DNS status by using digwebinterface.com. For more details, you could follow web-sites-custom-domain-name.
unknown
d4829
train
Unfortunately, this is not supported in TFS currently. The workarounds are just like you mentioned above, to disable and enable those steps or use draft release. This is a user voice about your request you could vote: https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19165690-select-steps-when-create-release
unknown
d4830
train
Yes it is, as the Stream.findAny() documentation states: This is a short-circuiting terminal operation. It's a common misconception that objects in stream are "pushed" towards consuming operation. It's actually the other way around - the consuming operation pulls each element. For sequential streams only as many predicates will be called as are needed to find matching value. Parallel streams may execute more predicates, but will also stop execution as soon as an element is found. public class StreamFilterLazyTest { static int stI = 0; static class T { public T() { super(); this.i = ++stI; } int i; int getI() { System.err.println("getI: "+i); return i; } } public static void main(String[] args) { T[] arr = {new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T()}; Optional<T> found = Arrays.stream(arr).filter(t -> t.getI() == 3).findAny(); System.out.println("Found: "+found.get().getI()); } } will print: getI: 1 getI: 2 getI: 3 Found: 3 A: The javadoc for findAny() states: "This is a short-circuiting terminal operation." "The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations ..." This means that findAny() on a sequential stream will only "pull" enough elements to find the first one. On a parallel stream, it could pull more than enough, depending on the implementation. The package javadoc also states: "Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed." This means that the filter() predicates only occur when the findAny() terminal pulls them. In short: Q: Is filter + findAny still a short-circuit operation? A: Yes. A: Well it does not matter if sequential or parallel streams are used, they are still going to traverse as many elements as are required to find the first that matches. It might be different if you use findFirst and you have a Stream made of an ordered collection. findFirst in this case has to preserver the order. In this case, due to parallelism, the second, then third elements might be processed before the first, but still only the first will be returned. A: Stream#findAny is a short-circuiting terminal operation. it will visit Predicates to matching & short-circuited one by one since Stream#filter return a new stream each time. Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed. As @Holger mentioned in comment that it can makes filters be short-circuited as below: if(predicate1.test(value) && predicate2.test(value)){ .... } Test Iterator<Predicate<Integer>> predicates = Stream.<Predicate<Integer>>of( it -> false, it -> { throw new AssertionError("Can't be short-circuited!"); } ).iterator(); Predicate<Integer> expectsToBeShortCircuited = it -> predicates.next().test(it); Stream.of(1).filter(expectsToBeShortCircuited).filter(expectsToBeShortCircuited) // | // | // here is short-circuited since the stream is empty now .findAny(); A: You can use peek to verify this == Sequential == Alpha1 Alpha2 Beta1 Beta2 Gamma1 Gamma2 Dolphin1 Fargo1 Fargo2 Found: Fargo Applications: 9 == Parallel == Arnold1 Jim1 Loke1 Alpha1 Mustard1 Lenny1 Mustard2 Mark1 Alpha2 Mark2 Beta1 Beta2 Gamma1 Fargo1 Gamma2 Dolphin1 Fargo2 Found: Fargo Applications: 17 YMMV depending on number of cores etc. Produced by below package test.test; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; public class Snippet { static AtomicInteger predicateApplications; public static void main(String arr[]) { System.out.println("== Sequential == \n"); sequential(); System.out.println(" == Parallel == \n"); parallel(); } private static void sequential() { Stream<String> stream = Stream.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke"); execute(stream); } private static void parallel() { Stream<String> parallelStream = Stream .of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke") .parallel(); execute(parallelStream); } private static void execute(Stream<String> stream) { predicateApplications = new AtomicInteger(0); Optional<String> findAny = stream.peek(s -> print(s + "1")).filter(s -> s.contains("a")) .peek(s -> print(s + "2")).filter(s -> s.startsWith("F")).findAny(); String found = findAny.orElse("NONE"); System.out.println("\nFound: " + found); System.out.println("Applications: " + predicateApplications.get()); } private static void print(String s) { System.out.print(s + " "); predicateApplications.incrementAndGet(); } }
unknown
d4831
train
For what it's worth, you could use the Function constructor. It's slightly safer than eval because it doesn't access the local scope. But it can still access global variables. var script = buffer.toString('utf8'); // assuming the file is in UTF-8 var returnObject = new Function('return ' + script); var myObject = returnObject(); A: Depending on the complexity of the code you're dealing with, this approach may or may not suit your needs: You can create a temporary file, say "test-module.js", which includes the object from "test.js" but with a module export prependend, for example: module.exports = { get: function() { return 'hello' }, somevar: 'xxx', put: function() { return 'world' } } Then, from your main file, you can retrieve the file content already available as a Javascript object: var funcs = {} var buff = require('./test-module'); funcs['test'] = [buff.get, buff.put]; Would this solution work for you?
unknown
d4832
train
Hows' this ? import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class Server { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000)); byte[] message = new byte[512]; DatagramPacket packet = new DatagramPacket(message, message.length); socket.receive(packet); System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength())); } } import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class Client { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.connect(new InetSocketAddress(5000)); byte[] message = "Oh Hai!".getBytes(); DatagramPacket packet = new DatagramPacket(message, message.length); socket.send(packet); } } A: @none The DatagramSocket classes sure need a polish up, DatagramChannel is slightly better for clients, but confusing for server programming. For example: import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class Client { public static void main(String[] args) throws IOException { DatagramChannel channel = DatagramChannel.open(); ByteBuffer buffer = ByteBuffer.wrap("Oh Hai!".getBytes()); channel.send(buffer, new InetSocketAddress("localhost", 5000)); } } Bring on JSR-203 I say
unknown
d4833
train
There are several overloaded versions of showInputDialog, with different parameters. Only the javadoc of the last version documents correctly that the return value is null when the user pressed cancel. public int getBirthYear() { boolean prompt = true; while (prompt) { String enteredAge = showInputDialog(null,"Enter age:"); if (enteredAge == null) { // Cancel pressed age = -1; prompt = false; } else { try { age = Integer.parseInt(enteredAge); age = year - age; prompt = false; showMessageDialog(null, age); } catch (NumberFormatException e) { showMessageDialog(null, "Enter a valid number"); } } } return age; } It might be you want to restructure the program a bit; make age a local variable or whatever. Use int for real integer values. Integer is the Object wrapper class for an int. A: The most easiest answer to your question is, just put promp = false outside of your try and catch clause and it should work: public Integer getBirthYear() { boolean prompt = true; while(prompt) { String enteredAge = showInputDialog(null,"Enter age:"); try { age = Integer.parseInt(enteredAge); if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) { System.out.println("MADE IT INTO IF"); } age = year - age; showMessageDialog(null,age); } catch (NumberFormatException e) { e.printStackTrace(); } prompt = false; } return age; } A: The problem was in the scope. The entered age wasnt making it into the catch block. I resolved that issue. public Integer getBirthYear() { boolean prompt = true; do { try { age = year - Integer.parseInt(showInputDialog(null,"Enter age:")); prompt = false; showMessageDialog(null, age); } catch (NumberFormatException e) { String ageEntered = showInputDialog(null,"Enter age:"); e.printStackTrace(); if(ageEntered == null) { //close the file if Cancel is chosen prompt = false; } } } while(prompt); return age; }
unknown
d4834
train
There are many situations where classes are only needed at runtime, not compile time. One of the most typical is JDBC drivers; code is written/compiled against the JDBC API, but at runtime a driver class must be available on the classpath. There are any number of other examples, especially when you get into various frameworks that have a standard API and differing implementations that can be "injected" at runtime. A: A very common example is classes that implement some API, such as the Servlet API. Each container (Tomcat, Jetty, WebSphere) supplies classes that the Web application usually knows nothing about, since it just uses the interfaces. More broadly, this pattern is used in the Service Provider Interface to enable plugins that implement an interface to be added at runtime.
unknown
d4835
train
I tried your example like this and it worked fine using all 8 CPUs on my laptop GOMAXPROCS=8 go run rpctest.go So at a guess you messed up setting the GOMAXPROCS environment variable somehow. Did you set it on a separate line and forget to export it? export GOMAXPROCS=8 Normally I set this in program using the runtime module runtime.GOMAXPROCS(runtime.NumCPU())
unknown
d4836
train
I found the answer after an intensive search in the library. In following output 24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533 The first element (24) is the id of the marker. The next 4 elements are the pixel coordinates of the 4 corners. With Markers[0][0].x and Markers[0][0].y you get the x- and y-coordinate of the top left corner.
unknown
d4837
train
Use the attribute System.ComponentModel.DataAnnotations.Schema.Table [Table("MyTable")] public class MyEntity { public Id int {get; set;} public Name string {get; set;} public Description string {get; set;} } If you don't actually want to run the migrations, I suggest create them anyway and comment out the relevant code before you run them. That way you will be well set up for the occassion when you do actually want to run them. A: You can define the entity maps by overriding the method called OnModelCreating in your DbContext: Then you can add some maps similar to: modelBuilder.Entity<Order>(m => { m.ToTable("MyTable", "dbo"); }) Info: https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables EDIT: I don't like adding annotation directly to my entity as I prefer to centralize it in one place. Easier to manage. After all I guess it's a question of preferences :)
unknown
d4838
train
Just for reference, I solved the problem by moving {% load ... %} from the base template to the concrete template. See also this post https://stackoverflow.com/a/10427321/3198502 A: To avoid loading the module in each template using {% load MODULE_NAME %}, you can add it as a 'builtin' in settings.py: TEMPLATES = [ { 'OPTIONS': { ... , 'builtins': [ ... 'APP_NAME.templatetags.MODULE_NAME', ] }, }, ] A: First off remove the semicolon after your replace. Do you have a file called __init__.py (this is suppose to have 2 underscores before and after init, hard to format in editor.) under the templatetags directory? Here is a good page with lots of info if you haven't looked yet. http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ A: I was nearly going nuts with this problem and none of the above answers helped. If you have several apps, make sure that the file names containing your custom tags/filters are unique, prefereablyapp_name_filters.py. Otherwise Django will only load the custom filters from the app it finds matching first!
unknown
d4839
train
You have params, instead of user. Change this: params: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end end to this: user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end end A: The signature of the post (and the other HTTP request methods) has change between Rails 4 and Rails 5. So send a user param in Rails 4 use this: post user_path, { user: { name: 'foo' } } Whereas in Rails 5 use this: post user_path, params: { user: { name: 'foo' } } Hartl's Rails Tutorial was updated to Rails 5 recently. But I guess you are still running Rails 4. That means: remove nesting of the params or update your app to Rails 5.
unknown
d4840
train
Based on the rules of the eslint-plugin-vue v6.2.2 (for Vue 2.x), You can read about it here: https://github.com/vuejs/eslint-plugin-vue/blob/v6.2.2/docs/rules/README.md, this is the order: { "vue/order-in-components": ["error", { "order": [ "el", "name", "parent", "functional", ["delimiters", "comments"], ["components", "directives", "filters"], "extends", "mixins", "inheritAttrs", "model", ["props", "propsData"], "fetch", "asyncData", "data", "computed", "watch", "LIFECYCLE_HOOKS", "methods", "head", ["template", "render"], "renderError" ] }] } Here you can read the Vue style guide and the rules priority information https://v2.vuejs.org/v2/style-guide/
unknown
d4841
train
You can speed up the responsiveness of a DGV by using VirutalMode http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx A: If you have a huge amount of rows, like 10 000 and more, to avoid performance leak - do the following before data binding: dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders dataGridView1.RowHeadersVisible = false; // set it to false if not needed after data binding you may enable it.
unknown
d4842
train
Found the error.it's because I doing testing using my custom string group user name. so it will be running well. but on real class, error is because username group format not valid. error 2202 is : error number description for Terminal Server . So the problem is closed.
unknown
d4843
train
You are inserting and finding incorrectly. Your elements are of type Node*. You have an "address of" operator (&) before Your elements. Which means You are trying to add a Node**, which is the incorrect type. So the compiler is saying: prog.cpp:67:24: error: no matching function for call to ‘std::unordered_set<Node*>::insert(Node**)’ The correct way is to add an element of the correct type, which is Node*, by removing the address of operator (&); Unless You wanted the address of a pointer, then You need the container to store Node**
unknown
d4844
train
How about the Google diff-match-patch code? https://github.com/elliotlaster/Ruby-Diff-Match-Patch I've used it in the past and been happy with the results. Taken from the documentation linked above: # Diff-ing dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false) => [[-1, "Apple"], [1, "Banana"], [0, "s are a"], [1, "lso"], [0, " fruit."]] You would just need to iterate through the non-matches and find the character position in the appropriate string. pos_ary = s.enum_for(:scan, /search_string/).map { regexp.last_match.begin(0) }
unknown
d4845
train
What I do in this cases is to make two associations. Since cake allow to customize relations, you can have two relations to the same model with different names. public $belongsTo = array( 'ResponsibleEmployee' => array( 'className' => 'HrEmployee', 'foreignKey' => 'responsible_person', 'fields' => 'HrEmployee.employeename', ), 'AttendingEmployee' => array( 'className' => 'HrEmployee', 'foreignKey' => 'person_attending', 'fields' => 'HrEmployee.employeename', ) ); Change the names to adjust your needs. Now, if your model is set as containable and you retrieve the Project model with those models in it, you'll get something like array('Project' => array(/*data project*/), 'ResponsibleEmployee' => array(/*name*/), 'AttendingEmployee' => array(/*name*/) ) (or another variation of that array depending on how the query was made).
unknown
d4846
train
You have to create an culture in which sharing is rewarded. * *Post to central WIKI instead of email links. *Reward contributors and encourage bottom up organic collaboration *"Force" collaboration top down. By "force" you mean reward and encourage. You must do all of this. And more. * *You must teach collaboration *You must assure that all managers value and reward collaboration *You must measure collaboration. Even then, you'll probably have to do even more. A: Good answer by S.Lott. I'd add: You need to make sure people can easily find things when they need them. That's partly cultural - do people think to look at the wiki, and do they know where to look. It's also about the wiki's structure & quality: * *Is it easy to navigate & search? *Is it kept up to date? *How does it mesh with other documentation (eg javadoc)? A: From my experience, forced = hated. So you have to make people want to use it, ie make it useful. A central Wiki sounds like the best solution, but it's hard to say. You might want to look into MediaWiki, Traq, or Sharepoint Services (not to be confused with Office Sharepoint). Your organization may find it encouraging if you post a list of the top contributors, editors, or visitors to the site. But that depends on how your org perceives competition. A: I wouldn't suggest a central wiki for collaboration (aside from internal specific stuff). But for sharing information found online you should encourage people to use one of the many existing systems for this. Google Reader has a really nice sharing and commenting mechanism. Delicious would also be a good fit for what you want. There's no reason to try to create a walled garden inside your organization for content that is being created outside of it. The system you create will not be as good as the ones that already exist and that will kill adoption.
unknown
d4847
train
If the arc is the only element drawn in the axes, then you can actually use xarc() to generate it, and then rotate the whole axes: clf xarc(0, 1, 3, 1, 0, 310*64) isoview gca().rotation_angles(2) = 70; But, its likely not the case. Then the arc must be generated as a polyline object, and then rotate() can be used to rotate it: clf alpha = 0:1:310; [a, b, xc, yc] = (3, 1, 2, 2); x = xc + a*cosd(alpha); y = yc + b*sind(alpha); r = 20; // rotation angle in ° xyR = rotate([x;y], r/180*%pi, [xc ; yc])'; plot(xyR(:,1), xyR(:,2))
unknown
d4848
train
When using /resetsettings, you could: * *Check whether default settings file exists. Get modified date if it does. *Run devenv.exe /resetsettings <filepath> The modified date on the default settings file will be changed to match the file specified. *Check modified date has changed, or file now exists. *Close devenv.exe I've given this a go; the settings file after step 3 isn't identical to the one specified in /resetsettings, although it's clearly different from the previous default one. I don't know the criteria for which tags are kept. Related, not a PowerShell solution: A team settings file can be specified by going to Tools > Options > Environment > Import and Export Settings. More info on Enviornment Options. Note from link: "When applied, these team settings would not override any category not specified in the .vssettings file"
unknown
d4849
train
As you can see in the user_register_submit submit handler, $form_state['submit'] is hardcoded. That means that user_register_submit will define the destination, unless you override it. You can do that by adding your own submit handler (pseudo code). function mymodule_form_alter(&$form, &$form_state, $form_id) { if ($form_id == "user_register") { //Look at the code in user_register_submit for all the ifs and switches to only // add this extra handler when a normal user signs up. $form['#submit'][] = "_mymodule_user_register_submit"; } } function _mymodule_user_register_submit($form, &$form_state) { $form_state['redirect'] = $_GET['q']; //Adds the current url as redirect. } Then, using the weights in the system table, make sure your modulestarts after the user module. Otherwise they are called alphabetically, user module coming after mymodule; resetting the redirect again. And never, ever, use drupal_goto() in submit handlers, because they will stop all processing and redirect the user, causing many modules to fail and often even causing broken and inconsistent databases.
unknown
d4850
train
I solved the problem , the problem was uwsgi itself. My setting file was ok. install uwsgi by conda conda install -c conda-forge libiconv conda install -c conda-forge uwsgi then start uwsgi /home/ubuntu/anaconda3/envs/py37/bin/uwsgi --ini uwsgi.ini
unknown
d4851
train
Try using ExecuteNonQuery() instead.
unknown
d4852
train
model.sortBy("time").reverse().sortBy("place") Will sort the array model one time. Ember.computed.sort('model',sortOptions) Will recompute its value every time model or its properties change. So what you should use depends on what you need. I don't think there's a significant difference in performance of the sort itself.
unknown
d4853
train
A,B:B").Select Range("B1").Activate ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlLineStacked ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False End Sub A: With ActiveSheet.Shapes.AddChart .ChartType = xlLineStacked .SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") End With ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & *YourFileNameHere* &".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False Replace the YourFileNameHere with the name you'd like to save the file with. Or if you want to simply save the active workbook with the change ActiveWorkbook.SaveAs Filename:=ThisWorkbook.FullName, _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False If you want to loop through all possible workbook or file inside of "D:\WayneCSV" just tell me what you mean by make it work for all my files? weather that means open excel sheets, or workbook, or all files with extension of *.xlsx inside of "D:\WayneCSV" Edit: Dim StrFile As String StrFile = Dir("D:\WayneCSV\*.CSV") ' Looks up each file with CSV extension Do While Len(StrFile) > 0 ' While the file name is greater then nothing Workbooks.Open Filename:= "D:\WayneCSV\" & StrFile ' Open current workbook ActiveSheet.Shapes.AddChart.Select ' Add a chart ActiveChart.ChartType = xlLineStacked ' Add a chart type ActiveChart.SetSourceData Source:=Range("$A1:$B1", Range("$A1:$B1").End(xlDown)) ' Set the source range to be the used cells in A:B on the open worksheet With ActiveChart.Parent .Height = .Height*1.5 'Increase Height by 50% .Width = .Width*1.5 'Increase Width by 50% End With 'Note the setting of the source will only work while there are no skipped blank if you 'have empty rows in the source data please tell me and i can provide you with another ' way to get the information ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & StrFile & ".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ' Save file as excel xlsx with current files name ActiveWorkbook.Close ' Close when finished before opening next file this can be removed if you'd like to keep all open for review at the end of loop. StrFile = Dir ' Next File in Dir Loop Let me know if it works as I can't test without your folders and data. But it should work. A: where it is written Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx" that's your filename you could replace it with ThisWorkbook.FullName it should work So it should give you something like this. Filename:=ThisWorkbook.FullName, Also I don't understand that part ChDir "D:\WayneCSV" Why put the path then the full name I'm more an access programmer than an excel one so I could be wrong. A: Check out this SO link I think what you want to do is replace :="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx" with ActiveWorkbook.FullName in ActiveWorkbook.SaveAs line A: Your macro, from what I can tell, is adding a chart based off of some data and saving the sheet. That is a very specialized Macro, but you would need to change the directory as others listed to a directory on your local drive but you also need to find out where the data you are creating a chart for is being stored. Sub Macro1() ' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+m ' '<<< This is the naming convention and hotkey if you goto Tools > Macros in Excel 2003 or Developer > Macros in 2010 'Range("A:A,B:B").Select '<<< This is where you are selecting all data in columns A and B and is not needed so I commented it out 'Range("B1").Activate '<<< This code is 'activating' a cell, but not sure why, so I commented it out as it should not be needed ActiveSheet.Shapes.AddChart.Select '<<< You are adding a chart here ActiveChart.ChartType = xlLineStacked '<<<Defining a chart type ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") '<<< Setting it's source data from a worksheet called 'cwapp5_MemCPU-Date-Mem' with header information from Column B and Data from Column A ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False '<<< You are saving a copy of your workbook End Sub To make this work for other workbooks you need to rename all of the ranges to where your data is, rename the tabs to what you have your tabs named, and rename the WorkBook to what you want it saved as and where.
unknown
d4854
train
You actually asking for an opinion on game design. The way I look at it, nothing is impossible so go ahead and try your coding. Also it would be wise to look around at similar projects scattered around the net. You may be able to pick up a lot of tips without re inventing the wheel. Here is a good place to start. scrolling mini map
unknown
d4855
train
Use : if(txt.getText().trim().length()==0) //Do something Your code will not work because a blank string("") is not a null String. I simply check if the trimmed length() of TextField is 0. A sample function: public boolean isEmpty(JTextField jtf) { try{ jtf.getText(); }catch(NullPointerException e){return true;} if(jtf.getText().trim().length() == 0) return true; return false; } A: Check explicitly for null and then compare with "". public static void Vacio(JTextField txt){ String str = null; try { str = txt.getText(); } catch (NullPointerException npe) { System.out.println("The document is null!"); return; } if(str.trim().equals("")==true){/*Message*/} } A: I cannot imagine how adding Lambda expressions can improve what you're trying to do (?). Anyway, to check for an empty String I'd probably use: field.getText().trim().isEmpty() You don't need to check for null but you do need to catch NullPointerException in the event that the underlying document in the JTextField is null. For the other part of your quesiton, if you really want to check multiple JTextFields in one method you could pass them as a variable length argument list: public static void vacio(JTextField... fields) { for(JTextField field : fields) { try { if( field.getText().trim().isEmpty() ) { // do something } } catch(NullPointerException ex) { // handle exception (maybe log it?) } } } and call it like: vacio(field1, field2, field3); But, generally speaking, keeping functions brief and only doing one thing is usually better than trying to make a function do too much. One final aside, your method is named Vacio but java naming conventions suggest you should compose method names using mixed case letters, beginning with a lower case letter and starting each subsequent word with an upper case letter.
unknown
d4856
train
It looks like the problem is with google play services version of your users. You can try: private boolean checkGooglePlayServices() { final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (status != ConnectionResult.SUCCESS) { Log.e(TAG, GooglePlayServicesUtil.getErrorString(status)); // ask user to update google play services. Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1); dialog.show(); return false; } else { Log.i(TAG, GooglePlayServicesUtil.getErrorString(status)); // google play services is updated. //your code goes here... return true; } } To verify google play services is available. A: You need to lower the firebase version you have, they have some problems with the new versions on some devices.
unknown
d4857
train
This is a known issue in the Visual C++ 2012 implementation of std::thread. See the following bug on Microsoft Connect: std::thread constructor doesn't handle movable object The response to that bug states: We attempted to fix this during VC11's development, but it exploded horribly and we had to revert the change. As it turns out, std::thread can't be powered by bind(), because thread needs to move its arguments, and bind() is forbidden from doing so (since bound functors should be repeatedly invokable, without their bound arguments being moved-from). So we'll need to reimplement std::thread's ctor to avoid using bind().
unknown
d4858
train
http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. As for my understanding of the specification, you get shared object references if the object instances to be shared go throught the same ObjectOutputStream. So when you serialize the class containing the arr array, each object written gets an ID, and for each reference that passes through the stream, only that ID is written. The deserialized graph in that case remain homogeneous with the original graph. I am sorry but I cannot help with krio library own serialization mechanism, I would be very happy to learn from someone who used it as well. EDIT about kryo: Some documentation I found: * *By default, each appearance of an object in the graph after the first is stored as an integer ordinal. This allows multiple references to the same object and cyclic graphs to be serialized. This has a small amount of overhead and can be disabled to save space if it is not needed: kryo.setReferences(false); *This (github) is the contract of the reference resolver; two implementation are given: ArrayList-based for small objects graphs, Map-based for larger ones *This is implementation of the default object array (de)serializer *Classes need to be registered for (de)serialization; each registered class can be coupled with a serializer (among which, the default Java serialization mechanism)
unknown
d4859
train
I think you should use date_add() function provided in Hive. Look here
unknown
d4860
train
When a wide-char string is seen as a 1-char string, that's a symptom that you're providing a wide-char string where a multi-byte string is expected. Indeed we see the error here: (LPCSTR)valueName.c_str() (where valueName is a std::wstring). LPCSTR is const char *, whereas wstring::c_str() returns const wchar_t *. So L"ServiceType" is seen as "S\0e\0r\0v\0i\0c\0e\0T\0y\0p\0e\0", which becomes simply "S" There are 2 solutions possible: * *Use std::string instead of std::wstring (and remove the L from strings like L"ServiceType"). This solution is not recommended, since the Win32 API internally is Unicode. *Change project settings from Multi-byte to Unicode Character Set and remove the casting to LPCSTR (if you do need to cast, use LPTSTR instead, which always matches project character set settings). See Working with Strings - Win32 API for more details.
unknown
d4861
train
You should be able to specify the colors: scatterplot(wt ~ mpg, data = mtcars, col=c("green3", "red", "black")) (These are the default colors; see ?scatterplot.)
unknown
d4862
train
You start processes twice, * *First one running with output inFile, *Second one running with output inFile & error errFile Was it your original intension? try { p = builder.redirectOutput(inFile).**start()**; **// Line Number : 194 ** p = builder.redirectError(errFile).**start()**; } catch (IOException e) { logger.error(this.getClass().getName() + ": " + e.getMessage(), e); } And destroy only the last one created. if (p != null) { p.destroy(); } Fix this, and this should fix your error. P.S. Start it only once: try { builder = builder.redirectOutput(inFile); p = builder.redirectError(errFile).start(); }
unknown
d4863
train
This has now been resolved, re-imaged laptop > re-installed VS2019 with all required extensions I believe it may have been a corrupt install of VS but this is yet to be confirmed by Microsoft
unknown
d4864
train
just add null and the value to decode to in your decode string. select decode('&partitions', 'true', 'CreateTablesPartitions', null, 'itsnull', 'CreateTables') scr from dual; so if its null, then the result will be itsnull A: You can just include null as a recognised value in your decode: col scr new_value script set term off set verify off select decode('&partitions', null, 'CreateTables', 'CreateTablesPartitions') as scr from dual; set term on @@&script &partitions ... which will run CreateTables if the entered partitions value is null. But, because you have termout off, you won't see the prompt for the value. You might want to use positional variables (&1 etc.) depending on how you're intending to call this, but assuming you do want to be prompted at run-time, you can either leave termout on and add noprint to the column command (col scr new_value script noprint), which will give some blank lines in the output; or set partitions earlier. You can't use define though because that won't like a null value. The cleanest approach may be to use accept with its own prompt: accept partitions prompt "Enter partitions: " col scr new_value script noprint set verify off set term off select decode('&partitions', null, 'CreateTables', 'CreateTablesPartitions') as scr from dual; set term on @@&script &partitions With simple dummy scripts to call, e.g. CreateTables.sql: prompt In CreateTables ... and CreateTablesPartitions: prompt In CreateTablesPartitions with passed value "&1" ... this gives: Enter partitions: In CreateTables ... and: Enter partitions: Test In CreateTablesPartitions with passed value "Test"
unknown
d4865
train
Since you only want to use query strings while using pagination, the following code should be enough: $this->load->library('pagination'); ... $config['page_query_string'] = TRUE; ... $this->pagination->initialize($config); echo $this->pagination->create_links(); You should check the rest of the Pagination Class documentation.
unknown
d4866
train
You'd probably have trouble with either of those if you actually including it after the input statement. The information that ProgramFOX posted is correct, but if you're asking about the difference between these three statements, there's a little more to it: total = sum(total,cost); total + cost; The second of these implies a retain total; statement and will also treat nulls as zero. You run into the null problem when you're using this type of expression: total = total + cost; A: The differnce can be seen below: If you want to calculate cumulative total , you should use sum statement. total = sum(total,cost) /* its a sum function */ total+cost /* its a sum statement,the form is variable+expression */ Here : "total" specifies the name of the accumulator variable, which contains a numeric value. 1) The variable(total in this case) is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement. 2) To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value. and "Cost" is an expression 1) The expression is evaluated and the result added to the accumulator variable. 2) SAS treats an expression that produces a missing value as zero. A sum statement is differ from a sum function in a way that a sum statement retains the value which it has calculated earlier. However, The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here: retain total 0; total=sum(total,cost);
unknown
d4867
train
did you do this? in your main() you have to call Firebase.initializeApp() void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await GetStorage.init(); await load(); runApp(InitiateApp()); } A: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); // You are missing this statement runApp(MyApp()); }
unknown
d4868
train
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) at each 250 ms the value in the p array is printed on the console. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setInterval is used as a loop here. Using the clearInterval, the loop is breaked after 5000 ms using setTimeout. const P = ['\\', '|', '/', '-']; let x = 0; const loader = setInterval(() => { process.stdout.write(`\r${P[x++]}`); x %= P.length; }, 250); setTimeout(() => { clearInterval(loader); }, 5000); A: Not really possible in browser console. In Node.js: var twirlTimer = (function() { var P = ["\\", "|", "/", "-"]; var x = 0; return setInterval(function() { process.stdout.write("\r" + P[x++]); x &= 3; }, 250); })(); A: You can do it in the browser console as well: var loading = (function() { var h = ['|', '/', '-', '\\']; var i = 0; return setInterval(() => { i = (i > 3) ? 0 : i; console.clear(); console.log(h[i]); i++; }, 300); })(); // clearInterval(loading) to stop it. A: You can try this package: https://github.com/ErAz7/Termination it supports * *promise based tranition *easing transition functions *looped transition *frame rate control *playback speed control *canvas size options *colors and some other useful features to create animations on terminal like a piece of cake!
unknown
d4869
train
It is permissible to overwrite the contents of a host buffer which you have used as an argument to an asynchronous host to device transfer, as long as you take steps to ensure that the transfer has completed. The return status alone does not tell you that the transfer is complete. You need to use an explicit synchronization command on the host after the asynchronous copy is launched to confirm this.
unknown
d4870
train
Take a look at the JQuery's round corner plugin And here is a demo A: The default for background images to to have them repeat. Try: background: transparent url(../images/roundbox-top.jpg) 0 0 no-repeat; Edited after comment to provide full solution: IE6 sets the height of empty divs to your font-size if the height specified in the css is less than the font-size. On #roundbox .top and #roundbox .bottom, put font-size:0; line-height:0; That will collapse the div to the right height. A: In addition to the change you've made for the bottom border, setting the font-size of the element with class "top" to 7px fixes it in my IE6. A: Try using the web developer toolbar in Firefox to validate the CSS and HTML. I did a quick check and there are multiple errors in each. The rendering difference, I suspect, is because IE does not handle malformed content as well as FF. In particular, even small errors in CSS files tend to snowball in IE and melt down an otherwise good layout. Not sure if IE7 and IE8 have made any improvements in this regard.
unknown
d4871
train
I assume since you reference ModelState you want to know how forms and validation works in Blazor. Have you looked at the documentation? https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.0 This explains how to use a validation process to show errors in a form. As well as built-in validations ( [Required] etc) you can also create custom validations, e.g. How to create Custom Data Annotation Validators Alternatively you can use a more powerful library such as Fluent Validation - see these articles for more help integrating this with Blazor: https://blog.stevensanderson.com/2019/09/04/blazor-fluentvalidation/ https://chrissainty.com/using-fluentvalidation-for-forms-validation-in-razor-components/ A: I used FluentValidation with Steve Sanderson's implementation https://gist.github.com/SteveSandersonMS/090145d7511c5190f62a409752c60d00#file-fluentvalidator-cs I then made a few modifications to it. First I added a new interface based on IValidator. public interface IMyValidator : IValidator { /// <summary> /// This should be the objects primary key. /// </summary> object ObjectId { get; set; } } Then I changed the FluentValidator to implement IMyValidator and added a new parameter. public class FluentValidator<TValidator> : ComponentBase where TValidator: IMyValidator,new() { /// <summary> /// This should be the objects primary key. /// </summary> [Parameter] public object ObjectId { get; set; } ... continue with the rest of Steve Sanderson's code } For my FluentValidation AbstractValidator I did the following. public class InvestigatorValidator:AbstractValidator<IAccidentInvestigator>,IMyValidator { public object ObjectId { get; set; } public InvestigatorValidator() { RuleFor(user=>user.LogonName).NotEmpty().NotNull().MaximumLength(100); RuleFor(user=>user.Email).NotEmpty().NotNull().MaximumLength(256); RuleFor(user=>user.FullName).NotEmpty().NotNull().MaximumLength(100); RuleFor(user=>user.RadioId).MaximumLength(25); RuleFor(user=>user.LogonName).MustAsync(async (userName, cancellation)=> { var exists = await GetUserNameExists(userName); return !exists; }).WithMessage("UserName must be unique."); RuleFor(user=>user.Email).MustAsync(async (email, cancellation)=> { var exists = await GetEmailExists(email); return !exists; }).WithMessage("Email must be unique."); } private async Task<bool> GetUserNameExists(string userName) { if(ObjectId is int badge) { await using var db = MyDbContext; var retVal = await db.AccidentInvestigators.AnyAsync(a=>a.Badge != badge && string.Equals(a.LogonName.ToLower(), userName.ToLower())); return retVal; } return false; } private async Task<bool> GetEmailExists(string email) { if(ObjectId is int badge) { await using var db = DbContext; var retVal = await db.AccidentInvestigators.AnyAsync(a=>a.Badge != badge && string.Equals(a.Email.ToLower(), email.ToLower())); return retVal; } return false; } } Then in my Razor Component Form I changed the FluentValidator to set the ObjectId. <EditForm Model="_investigator" OnValidSubmit="Save"> <FluentValidator TValidator="InvestigatorValidator" ObjectId="@_investigator.Badge"/> ... put the rest of your layout here </EditForm>
unknown
d4872
train
You can enumerate the file. using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); Then, ForEach the string[] and create a new instance of the IO.File object. Once you get a handle on a File, just call the Move method and pass in String.Replace("abc_", String.Empty). I said Move because there is no direct Rename method in IO.File. File.Move(oldFileName, newFileName); Be mindful of the extension. A: You should have a look at the DirectoryInfo class and GetFiles() Method. And have a look at the File class which provides the Move() Method. File.Move(oldFileName, newFileName); A: Following code will work, not tested though, public class FileNameFixer { public FileNameFixer() { StringToRemove = "_"; StringReplacement = ""; } public void FixAll(string directory) { IEnumerable<string> files = Directory.EnumerateFiles(directory); foreach (string file in files) { try { FileInfo info = new FileInfo(file); if (!info.IsReadOnly && !info.Attributes.HasFlag(FileAttributes.System)) { string destFileName = GetNewFile(file); info.MoveTo(destFileName); } } catch (Exception ex) { Debug.Write(ex.Message); } } } private string GetNewFile(string file) { string nameWithoutExtension = Path.GetFileNameWithoutExtension(file); if (nameWithoutExtension != null && nameWithoutExtension.Length > 1) { return Path.Combine(Path.GetDirectoryName(file), file.Replace(StringToRemove, StringReplacement) + Path.GetExtension(file)); } return file; } public string StringToRemove { get; set; } public string StringReplacement { get; set; } } you can use this class as, FileNameFixer fixer=new FileNameFixer(); fixer.StringReplacement = String.Empty; fixer.StringToRemove = "@@"; fixer.FixAll("C:\\temp"); A: You can use File.Move and String.Substring(index): var prefix = "abc_"; var rootDir = @"C:\Temp"; var fileNames = Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); foreach(String path in fileNames) { var dir = Path.GetDirectoryName(path); var fileName = Path.GetFileName(path); var newPath = Path.Combine(dir, fileName.Substring(prefix.Length)); File.Move(path, newPath); } Note: Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); will search also subfolders from your root directory. If this is not intended use SearchOption.TopDirectoryOnly. A: You can try with this code DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess"); FileInfo[] infos = d.GetFiles(); foreach(FileInfo f in infos) { File.Move(f.FullName, f.FullName.Replace("abc_","")); // Careful!! This will replaces the text "abc_" anywhere in the path, including directory names. } A: you can use a foreach iteration along with the File class from the System.IO namespace. All its methods are provided for you at no cost here: http://msdn.microsoft.com/en-us/library/system.io.file%28v=vs.100%29.aspx A: Total Commander has the possibility to rename multiple files (You don't need to program a tool on your own for each little task). A: string path = @"C:\NewFolder\"; string[] filesInDirectpry = Directory.GetFiles(path, "abc*"); forearch(string file in filesInDirectory) { FileInfo fileInfo = new FileInfo(file); fileInfo.MoveTo(path + "NewUniqueFileNamHere"); } A: I like the simplicity of the answer with the most up-votes, but I didn't want the file path to get modified so I changed the code slightly ... string searchString = "_abc_"; string replaceString = "_123_"; string searchDirectory = @"\\unc\path\with\slashes\"; int counter = 0; DirectoryInfo d = new DirectoryInfo(searchDirectory); FileInfo[] infos = d.GetFiles(); foreach(FileInfo f in infos) { if (f.Name.Contains(searchString)) { File.Move(searchDirectory+f.Name, searchDirectory+ f.Name.Replace(searchString, replaceString)); counter++; } } Debug.Print("Files renamed" + counter); A: This code enables user to replace a part of file name. Useful if there are many files in a directory that have same part. using System; using System.IO; // ... static void Main(string[] args) { FileRenamer(@"D:\C++ Beginner's Guide", "Module", "PDF"); Console.Write("Press any key to quit . . . "); Console.ReadKey(true); } static void FileRenamer(string source, string search, string replace) { string[] files = Directory.GetFiles(source); foreach (string filepath in files) { int fileindex = filepath.LastIndexOf('\\'); string filename = filepath.Substring(fileindex); int startIndex = filename.IndexOf(search); if (startIndex == -1) continue; int endIndex = startIndex + search.Length; string newName = filename.Substring(0, startIndex); newName += replace; newName += filename.Substring(endIndex); string fileAddress = filepath.Substring(0, fileindex); fileAddress += newName; File.Move(filepath, fileAddress); } string[] subdirectories = Directory.GetDirectories(source); foreach (string subdirectory in subdirectories) FileRenamer(subdirectory, search, replace); } A: Use this if you want all directories recursively: using System; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { foreach (String filePath in Directory.GetFiles(@"C:\folderName\", "*.*", SearchOption.AllDirectories)) { File.Move(filePath, filePath.Replace("abc_", "")); } } } } A: This command would do the trick, using renamer: $ renamer --find "abc_" *
unknown
d4873
train
It was more a nginx question. I added this to my site nginx file: location ^~ /blog/css/ { gzip_static on; expires max; add_header Cache-Control public; }
unknown
d4874
train
If using System; were recursive, then, in just the "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" assembly, this would be list of type collisions you would get: __Filters, __HResults, <>c, <>c__DisplayClass11_0, <>c__DisplayClass4_0, AsyncCausalityStatus, AsyncReplySink, BIND_OPTS, BINDPTR, CALLCONV, CausalityRelation, CausalitySynchronousWork, CausalityTraceLevel, ChannelInfo, ConfiguredTaskAwaiter, CONNECTDATA, ContractHelper, DebugView, Decoder, DESCKIND, DESCUNION, DictionaryEnumerator, Disposition, DISPPARAMS, ELEMDESC, Encoder, Entry, Enumerator, Environment, EventData, EXCEPINFO, ExplicitlySet, FILETIME, FUNCDESC, FUNCFLAGS, FUNCKIND, Getter, IDLDESC, IDLFLAG, IEnumerable, IEnumerator, IExpando, IMPLTYPEFLAGS, InternalPartitionEnumerable, InternalPartitionEnumerator, INVOKEKIND, IReflect, KeyCollection, Keywords, LIBFLAGS, MdSigCallingConvention, NameInfo, Node, NodeEnumerator, OpFlags, PARAMDESC, PARAMFLAG, ParseFailureKind, Reader, RemoteAppEntry, Segment, SerializationMask, SinkStack, State, STATSTG, SYSKIND, Tasks, TokenType, TYPEATTR, TYPEDESC, TypeEntry, TYPEFLAGS, TypeInfo, TypeKind, TYPEKIND, TYPELIBATTR, UnsafeNativeMethods, ValueCollection, VARDESC, VARFLAGS, Variant, Win32 And in the current project I have open, with 14 assemblies loaded I would have 792 type collisions (of the 14,251 types defined). That's why it's not recursive. Here's how to run this yourself: var typeCollisions = String.Join(", ", System .AppDomain .CurrentDomain .GetAssemblies() .SelectMany(a => a.GetTypes()) .GroupBy(x => x.Name) .Where(x => x.Skip(1).Any()) .Select(x => x.Key) .OrderBy(x => x));
unknown
d4875
train
You can find the default in this file: https://android.googlesource.com/platform/packages/apps/Dialer/+/master/res/values/donottranslate_config.xml?autodive=0%2F%2F As you can see, it is empty.
unknown
d4876
train
also I don't understand why doesn't my column names show up Column names won't show up unless you add a container (like a JScrollPane) to it. add(new JScrollPane(table)); should be enough. A: Just model.fireTableDataChanged();wont work you have to reload your model from database This should work: public class Arsti2 { JFrame main = new JFrame("Ārst"); JPanel tP = new JPanel(); JPanel bP = new JPanel(); JButton one = new JButton("Test"); JTable table = new JTable(); DefaultTableModel model; Vector columnNames = new Vector(); Vector data = new Vector(); Arsti2() { main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); main.setSize(840,300); try { reloadData(); model = new DefaultTableModel(data,columnNames); table.setModel(model); //model.fireTableDataChanged(); tP.add(table); bP.add(one); main.add(tP,BorderLayout.NORTH); main.add(bP,BorderLayout.SOUTH); } catch(Exception e) { e.printStackTrace(); } main.setVisible(true); one.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evnt1) { try { reloadData(); model.fireTableDataChanged(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private void reloadData() throws ClassNotFoundException, SQLException { columnNames.clear(); data.clear(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb"; Connection con = DriverManager.getConnection(Base,"",""); Statement st = con.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM Arsti"); ResultSetMetaData rsmd = res.getMetaData(); int column = rsmd.getColumnCount(); columnNames.addElement("ID"); columnNames.addElement("Vards"); columnNames.addElement("Uzvards"); columnNames.addElement("Dzimums"); columnNames.addElement("Personas kods"); columnNames.addElement("Telefona numurs"); columnNames.addElement("Nodalas ID"); columnNames.addElement("Amata ID"); while(res.next()) { Vector row = new Vector(column); for(int i=1; i<=column; i++) { row.addElement(res.getObject(i)); } data.addElement(row); } } public static void main(String[] args) { new Arsti2(); } }
unknown
d4877
train
You need to set these following variables : enableBasicAutocompletion:true enableLiveAutocompletion:false for achieving auto-completion only on pressing Cntrl - Spacebar. Check this snippet for live demo : var langTools = ace.require("ace/ext/language_tools"); var editor = ace.edit("editor"); editor.setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: false }); <html> <body> <div id="editor" style="height: 500px; width: 800px">Type in a word like "will" below and press ctrl+space to get "auto completion"</div> <div id="commandline" style="position: absolute; bottom: 10px; height: 20px; width: 800px;"></div> </body> <script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ace.js" type="text/javascript" charset="utf-8"></script> <script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ext-language_tools.js" type="text/javascript" charset="utf-8"></script> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> </html>
unknown
d4878
train
If your servlets are already compiled then JRE will serve the purpose, But they are compiled then you will JDK and other libraries( like servlet-api.jar, etc.) to compile you servlets. In short JDK is for development where you want to develop something using Java. And JRE is used when you already have compiled classes and you just want to run it. You might want to refer to this : What is the difference between JDK and JRE? A: In theory, compiling with Eclipse's incremental compiler is sufficient. Running the application server with a JRE should be fine as well. I suppose your error is somewhere else. Anyway, I'd strongly recommend installing a JDK for developing a Java application. It comes with some handy tools and many 3rd party tools (Maven, e.g.) also require a real JDK compiler and can't work with Eclipse's built in compiler. A: I had the same problem. The JDK was not the issue. After you compile your servlet you have to restart your tomcat server so it can load your class files before you try to access it through the web browser. No more 404 errors after that, servlets are running fine.
unknown
d4879
train
I'm not sure I fully understand your issue as it looks like you only have one type of command to run. So, if you really only have the google authenticator command to run, I'd do something like this : - name: Generate a timed-based code for user command: '/usr/bin/google-authenticator -t -f -d --label="{{item}}" --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/{{item}}' creates='/home/{{{ item }}/.google_authenticator' with_items: "{{ users }}" become: true A: You are probably looking for with_nested. However, it will be difficult to implement with the creates option, since only one of the commands will create that file. Also note that the loops must be distinct -- you cannot reference one list from the other.
unknown
d4880
train
You are creating the HTML at the server side; that is a possibility, but as you see, it makes it hard to combine this with ASP.NET server controls. It would be better to put the HTML on the .aspx-page. I understand that your database knows which menu-items should be visible. And that you want to add 1 additional item, where users can login. You could use (for example) a GridView with one column. <Columns> <asp:TemplateField> <ItemTemplate> <div>Your HTML here </div> <div><%# Item.SomeProperty %></div> </ItemTemplate> </asp:TemplateField> </Columns> Use the data from your database to render one 'row' per menuitem in the grid. You can customize the TemplateField so it contains the bootstrap-layout as you need it. It might also be possible to keep your current approach. I think then you should at least not create your opening and closing bootstrap-menu tags in the code-behind. You should put those tags on the .aspx-page itself, the structure would then be: <opening tag bootstrap menu> <div id="myNav" runat="server"></div> <asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled"> ... </ ..> <closing tag bootstrap menu>
unknown
d4881
train
Try adding an audiorate element in the audio branch, and a videorate element in the video branch, to see if that makes a difference, or try a different muxer, like qtmux or matroskamux.
unknown
d4882
train
Use WCF Streaming that you can use netTcpBinding or basicHttpBinding. I have used it and It is super fast and efficient - really impressive. And yes you can simulate slow transfer, you just need to write to your stream slowly (pauses in the middle).
unknown
d4883
train
Kiran, the issue is you only have two utterances in your app that contain the subsidiary entity. Additional to that, the word 'cakemagic' is not a real word and, thus, LUIS doesn't know how to handle that word. The option is to either include more utterances from which you can train LUIS with (i.e. more examples of context, where the entity can show up in the utterance, or different values the subsidiary can be), use real words LUIS would naturally recognize, or build out the phrase list to include all the words you are looking to have included.
unknown
d4884
train
With the hibernate.connection.datasource property, you're telling hibernate to look for a datasource in JNDI. Obviously you don't have one. Since you're specifying all the other required connection properties there, I'm guessing you don't really mean to do that.
unknown
d4885
train
The typical cause of an App, that uses SQLite and that copies a pre-existing database suddenly not working for API 28 is that to get around the issue of the database folder not existing (the copy would fail if the directory didn't exist) is to create an empty database and then overwrite the database. However, as by default, from API 28, the SDK uses WAL (Write-ahead logging) and that creating the empty database to be overwritten, results in the -shm and -wal files being created. It is the existence of these files that result in the database being empty after the copy. * *I believe that this is because once the copied database is opened, a mismach is detected and the SDK's methods create an empty usable database (this is conjecture and hasn't actually been shown to be). Quick Fix The quick, but not recommended fix, is to override the onConfigure method in the class that subclasses SQLiteOpenHelper to use the disableWriteAheadLogging method so that the database is opened in journal mode. * *the full code below (2nd piece of code) includes this, but the line has been commented out. Recommended Fix The recommended method, so as to gain from the benefits of WAL, is to check for the existence of the database directory and create the directory if it doesn't exist rather than create a database to be overwritten (and therefore the -shm and -wal file don't exist when the database is copied) The following is an example method where the directory is checked/created when checking to see if the database exists (obviously this would need to be tailored accordingly) :- private boolean checkDataBase() { /** * Does not open the database instead checks to see if the file exists * also creates the databases directory if it does not exists * (the real reason why the database is opened, which appears to result in issues) */ File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database if (db.exists()) return true; // If it exists then return doing nothing // Get the parent (directory in which the database file would be) File dbdir = db.getParentFile(); // If the directory does not exits then make the directory (and higher level directories) if (!dbdir.exists()) { db.getParentFile().mkdirs(); dbdir.mkdirs(); } return false; } * *Note that this relies upon the variable DB_NAME being the database name (file name of the database file) and that the final location of the database is the standard location (data/data/the_package/databases/). The above has been extracted from the following subclass of SQLiteOpenHelper :- public class DBHelper extends SQLiteOpenHelper { private static String DB_NAME = "db"; private SQLiteDatabase myDataBase; private final Context myContext; private int bytes_copied = 0; private static int buffer_size = 1024; private int blocks_copied = 0; public DBHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; // Check for and create (copy DB from assets) when constructing the DBHelper if (!checkDataBase()) { bytes_copied = 0; blocks_copied = 0; createDataBase(); } } /** * Creates an empty database on the system and rewrites it with your own database. * */ public void createDataBase() { boolean dbExist = checkDataBase(); // Double check if(dbExist){ //do nothing - database already exists } else { //By calling this method an empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. //this.getReadableDatabase(); //<<<<<<<<<< Dimsiss the above comment //By calling this method an empty database IS NOT created nor are the related -shm and -wal files //The method that creates the database is flawed and was only used to resolve the issue //of the copy failing in the absence of the databases directory. //The dbExist method, now utilised, checks for and creates the database directory, so there //is then no need to create the database just to create the databases library. As a result //the -shm and -wal files will not exist and thus result in the error associated with //Android 9+ failing with due to tables not existining after an apparently successful //copy. try { copyDataBase(); } catch (IOException e) { File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); if (db.exists()) { db.delete(); } e.printStackTrace(); throw new RuntimeException("Error copying database (see stack-trace above)"); } } } /** * Check if the database already exist to avoid re-copying the file each time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { /** * Does not open the database instead checks to see if the file exists * also creates the databases directory if it does not exists * (the real reason why the database is opened, which appears to result in issues) */ File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database Log.d("DBPATH","DB Path is " + db.getPath()); //TODO remove for Live App if (db.exists()) return true; // If it exists then return doing nothing // Get the parent (directory in which the database file would be) File dbdir = db.getParentFile(); // If the directory does not exits then make the directory (and higher level directories) if (!dbdir.exists()) { db.getParentFile().mkdirs(); dbdir.mkdirs(); } return false; } /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException { final String TAG = "COPYDATABASE"; //Open your local db as the input stream Log.d(TAG,"Initiated Copy of the database file " + DB_NAME + " from the assets folder."); //TODO remove for Live App InputStream myInput = myContext.getAssets().open(DB_NAME); // Open the Asset file String dbpath = myContext.getDatabasePath(DB_NAME).getPath(); Log.d(TAG,"Asset file " + DB_NAME + " found so attmepting to copy to " + dbpath); //TODO remove for Live App // Path to the just created empty db //String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream File outfile = new File(myContext.getDatabasePath(DB_NAME).toString()); Log.d("DBPATH","path is " + outfile.getPath()); //TODO remove for Live App //outfile.setWritable(true); // NOT NEEDED as permission already applies //OutputStream myoutputx2 = new FileOutputStream(outfile); /* Note done in checkDatabase method if (!outfile.getParentFile().exists()) { outfile.getParentFile().mkdirs(); } */ OutputStream myOutput = new FileOutputStream(outfile); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[buffer_size]; int length; while ((length = myInput.read(buffer))>0) { blocks_copied++; Log.d(TAG,"Ateempting copy of block " + String.valueOf(blocks_copied) + " which has " + String.valueOf(length) + " bytes."); //TODO remove for Live App myOutput.write(buffer, 0, length); bytes_copied += length; } Log.d(TAG, "Finished copying Database " + DB_NAME + " from the assets folder, to " + dbpath + String.valueOf(bytes_copied) + "were copied, in " + String.valueOf(blocks_copied) + " blocks of size " + String.valueOf(buffer_size) + "." ); //TODO remove for Live App //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); Log.d(TAG,"All Streams have been flushed and closed."); //TODO remove for Live App } @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); Log.d("DBCONFIGURE","Database has been configured "); //TODO remove for Live App //db.disableWriteAheadLogging(); //<<<<<<<<<< un-comment to force journal mode } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); Log.d("DBOPENED","Database has been opened."); //TODO remove for live App } } * *Note the above code is/was intended for development/experimentation and thus includes code that could be removed.
unknown
d4886
train
Thanks a lot to @Deadpool and @Stephen C, Combining your answers solved my problem. public static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXX"; public filter(@DateTimeFormat(pattern =DATE_TIME_FORMAT) LocalDate fromDate) { ... } I updated date format as well.
unknown
d4887
train
A solution that should work without any additional gems: let(:rest_client_double) { instance_double(Some::REST::Client, create_thing: response) } it 'sends get request to the RestClient' do allow(Some::REST::Client).to receive(:new).and_return(rest_client_double) MyModel.new(attrs).do_a_rest_call(some_str) expect(rest_client_duble).to have_received(:create_thing).with(some_str).once end Basically, you are creating a double for REST client. Then, you make sure that when calling Some::REST::Client.new the double will be used (instead of real REST client instance). Finally, you call a method on your model and check if double received given message.
unknown
d4888
train
Yes, we can. Have a look at the following example (especially the correlate method call): from sqlalchemy import select, func, table, Column, Integer table1 = table('table1', Column('col', Integer)) table2 = table('table2', Column('col', Integer)) subquery = select( [func.if_(table1.c.col == 1, table2.c.col, None)] ).correlate(table1) query = ( select([table1.c.col, subquery.label('subquery')]) .select_from(table1) ) if __name__ == '__main__': print(query) will result in the following query SELECT table1.col, (SELECT if(table1.col = :col_1, table2.col, NULL) AS if_1 FROM table2) AS subquery FROM table1 As you can see, if you call correlate on a select, the given Table will not be added to it's FROM-clause. You have to do this even when you specify select_from directly, as SQLAlchemy will happily add any table it finds in the columns. A: Based on the link from univerio's comment, I've done this code for my request: Declch = db.aliased(Declanchement) maxdate_sub = db.select([db.func.max(Declanchement.date)])\ .where(Declanchement.id_envoi == Declch.id_envoi) decs_sub = db.session.query(Declch.id_envoi)\ .filter(Declch.status == SMS_EN_ATTENTE)\ .filter(Declch.date < since)\ .filter(Declch.date == maxdate_sub).subquery() envs = Envoi.query.filter(Envoi.id_envoi.in_(decs_sub)).all()
unknown
d4889
train
First of all you need to ensure that the TestManagedLibrary.dll file is located in a place where Fusion could find it. Your first try should be the location of the executable you are running. One way to handle this is via the reference properties. If the reference to your TestManagedLibrary.dll is set with the copy local flag than during the build the referenced library is going to be copied from the referenced location to the output directory. You can enable the internal fusion logging to find out the details: * *Run Developer Command Prompt with administrative privileges. *Run fuslogvw *In the Assembly Binding Log Viewer hit settings and set either Log bind failures to disk or Log all binds to disk. *Start your service *Hit Refresh in the Assembly Binding Log Viewer, pick your executable and hit View Log A: The compiled DLL should have been in the same location as the executable for the CLR to search for it. In my case, the .NET compiled DLL was in the solution folder and not searchable.
unknown
d4890
train
No need to use .each. click already binds to all div occurrences. $('div').click(function(e) { .. }); See Demo Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound. A: One solution you could use is to assign a more generalized class to any div you want the click event handler bound to. For example: HTML: <body> <div id="dog" class="selected" data-selected="false">dog</div> <div id="cat" class="selected" data-selected="true">cat</div> <div id="mouse" class="selected" data-selected="false">mouse</div> <div class="dog"><img/></div> <div class="cat"><img/></div> <div class="mouse"><img/></div> </body> JS: $( ".selected" ).each(function(index) { $(this).on("click", function(){ // For the boolean value var boolKey = $(this).data('selected'); // For the mammal value var mammalKey = $(this).attr('id'); }); });
unknown
d4891
train
Fiddler might be helpful in this scenario. It will show you the post body sent to your PHP endpoint. A: In your dev tools, click Network tab, then do the request and click on it. Scroll to the Request body section. Network tab A: I recommend you axios, easier to check if success or error and cleaner: Post without any body sent; import axios from 'axios'; axios.post('http://example.com/email.php') .then(response=>response.data) .then(response=>console.log('Success:', response)) .catch(err=>console.log('Error: ',err)) With some arguments: axios.post('http://example.com/email.php', { firstName: 'Fred', lastName: 'Flintstone' }) .then(response=>response.data) .then(response=>console.log('Success:', response)) .catch(err=>console.log('Error: ',err)
unknown
d4892
train
The + operator is already defined for the type Array. It does an array merge and tacks the values of the rvalue onto the lvalue. To do a sum of values by index you can do something like this: protocol Numeric { } extension Double: Numeric {} extension Int: Numeric {} func +<T: Numeric>(left: [T], right: [T]) -> [T]? { var numElements: Int = 0 if count(left) != count(right) { return nil } else { numElements = count(left) } var result = [T]() for var i = 0; i < numElements; ++i { if let lvalue = left[i] as? Int, rvalue = right[i] as? Int { result.append(lvalue + rvalue as! T) } else if let lvalue = left[i] as? Double, rvalue = right[i] as? Double { result.append(lvalue + rvalue as! T) } } return result } But generally, I wouldn't advise overriding a predefined operator because of the high potential to cause confusion and chaos later on down the road.
unknown
d4893
train
This is a little complicated. You want a "vertical" list but have nothing to match the columns. You can use row_number() and union all: select max(t1_col1), max(t1_col2), max(t2_col1), max(t2_col2) from ((select t1.col1 as t1_col1, t1.col2 as t1_col2, null as t2_col1, null as t2_col2, row_number() over () as seqnum from table1 t1 ) union all (select null, null, t2.col1, t2.col2, row_number() over () as seqnum from table2 t2 ) ) t group by seqnum; Here is a db<>fiddle. Note that this will keep all rows in both tables, regardless of which is longer. The specific ordering of the rows in each column is not determinate. SQL tables represent unordered sets. If you want things in a particular order, you need a column that specifies the ordering. If you want to save this in a new table, put create table as table3 before the select. If you want to insert into an existing table, use insert.
unknown
d4894
train
From your code I think you are using tensorflow v<2. So, not sure if this will solve your problem but I can create adj.list and adj.mat format using v2.2.0 split is used to parse name, following this answer Adjacency matrix generation, # adjacency matrix # if operation input is node1 and output is node2, then mat[node1][node2] = 1 graph_adj_mat = [] # name to number mapping to set 1/0 from the node name tensorflow gives graph_node_name_to_num_map = {} # node number to name map will be needed later to understand matrix # as tensorflow identify node using name graph_node_num_to_name_map = {} # usage of compat module to use Session in v2.2.0 # if v < 2 use tf.Session() as sess with tf.compat.v1.Session() as sess: # initiating the matrix and necessary map for op in sess.graph.get_operations(): graph_node_num_to_name_map[len(graph_adj_mat)] = op.name graph_node_name_to_num_map[op.name] = len(graph_adj_mat) graph_adj_mat.append([0]*len(sess.graph.get_operations())) # parsing the name and setting adj. mat # edge direction input tensor to output tensor for op in sess.graph.get_operations(): dst_node_name = op.name.split(':')[0] for in_tensor in op.inputs: src_node_name = in_tensor.name.split(':')[0] graph_adj_mat[graph_node_name_to_num_map[src_node_name]][graph_node_name_to_num_map[dst_node_name]] = 1 print(graph_adj_mat) print(graph_node_num_to_name_map) Adjacency list generation (using dict), # adjacency list is dictionary of tensor name, # each input tensor name key holds output tensor name containing list graph_adj_list = {} with tf.compat.v1.Session() as sess: for op in sess.graph.get_operations(): graph_adj_list[op.name] = [] for op in sess.graph.get_operations(): dst_node_name = op.name.split(':')[0] for in_tensor in op.inputs: src_node_name = in_tensor.name.split(':')[0] graph_adj_list[src_node_name].append(dst_node_name) # graph_adj_list[in_tensor_name] contains list containing tensor names which are produced using in_tensor_name print(graph_adj_list) Output tested with modified version of given code, import tensorflow as tf print(tf.__version__) tf.compat.v1.disable_eager_execution() tf.compat.v1.reset_default_graph() a = tf.constant(1.3, name = 'const_a') b = tf.constant(3.1, name = 'const_b') c = tf.add(a,b, name = 'addition') d = tf.multiply(c,a, name = 'multiplication') e = tf.add(d,c, name = 'addition_1')
unknown
d4895
train
The first compiler would be 1.08 times the speed of the second compiler, which is 8% faster (because 1.0 + 0.08 = 1.08). A: Probably both calculations are innacurate, with modern/multi-core processors a compiler that generates more instruction may actually produce faster code.
unknown
d4896
train
The issues here are actually similar to the issues in 2d: MPI_Type_create_subarray and MPI_Gather ; there's a very lengthy answer there that covers most of the crucial points. Gathering multidimensional array sections is trickier than just doing 1d arrays, because the data you're gathering actually overlaps. Eg, the first row from rank 1 comes between the first and second rows of rank 0. So you need to (a) use mpi_gatherv, so you can specify the displacments, and (b) set the extents of the data types explicitly to facilitate the overlapping. Understanding the sending and receiving of complex data structures (in MPI, or in anything else) is all about understanding the layout of data in memory -- which is crucial for getting high performance out of your code anyway. Speaking of layout of memory, your Allocate3d won't work for the purposes here; the problem is that it allocates memory that may not be contiguous. There's no guarantee that if you allocate a 10x10x10 array this way that element [1][0][0] comes immediately after element [0][9][9]. This is a common problem in C/C++, which doesn't come with any built-in concept of multidimensional arrays. You'll need to do something like this: void Allocate_3D_R(long double***& m, int d1, int d2, int d3) { m=new long double** [d1]; for (int i=0; i<d1; ++i) { m[i]=new long double* [d2]; } m[0][0] = new long double[d1*d2*d3]; for (int i=0; i<d1; ++i) { for (int j=0; j<d2; ++j) { if (i!=0 && j!=0) m[i][j]=&(m[0][0][(i*d2+j)*d3]; for (int k=0; k<d3; ++k) { m[i][j][k]=0.0; } } } plus or minus -- that is, you'll need to allocate a contiguous d1*d2*d3 chunk of memory, and then point the array indicies to the appropriate places in that contiguous memory.
unknown
d4897
train
You can pass NULL for the lpModuleName parameter into GetModuleHandle: If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
unknown
d4898
train
As a user, you don’t want to have to sign in every time you use the app. Luckily, MSAL already caches your authorization and can log you in silently if it’s still valid.When properly authenticated we receive an access token that we can subsequently use to query other APIs that are secured by MSAL. Signing out is pretty straight forward. We go through all the available accounts that MSAL has locally cached for us and sign them out. We also clear the access token that we stored in secure storage when we signed in. public async Task<bool> SignOutAsync() { try { var accounts = await _pca.GetAccountsAsync(); // Go through all accounts and remove them. while (accounts.Any()) { await _pca.RemoveAsync(accounts.FirstOrDefault()); accounts = await _pca.GetAccountsAsync(); } // Clear our access token from secure storage. SecureStorage.Remove("AccessToken"); return true; } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return false; } }
unknown
d4899
train
https://github.com/palantir/gradle-docker you should use this project or jar_path=$(find . |grep $APP_NAME|grep jar|grep -v original|grep -v repository|grep -v templates) mv $jar_path ./app.jar
unknown
d4900
train
You can apply CSS using style tag inside the same specific component, Otherwise, you can apply CSS by targeting it with a specific class name.
unknown