w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Safely move svn folders and files
Just copy the folder and its child folders recursively with your OS command. Then go look at it to see if everything moved and is still connected correctly to SVN. It should be but paranoia doesn't mean SVN isn't out to get you. Add a file and check it in. Delete it and see if all that works. Then go delete the old folder and children. Of course, this only works if there isn't a nested ct folder inside /oo/P/ct

Categories : Shell

Batch: Create a list of folders and then copy multiple files/folders into all of them
Try this: @echo off &setlocal cd /d "RootFolder=X:folder omy data" for /d %%a in (*) do xcopy "_TEMPLATE" "%%~fa" /sihrky For xcopy options see xcopy /?, to test the command without writing add option /l.

Categories : List

How to stop threads of following type in Java used for watching folders for files using WatchService for folders by using jToggleButton
There is a Thread.stop() method, but is has been deprecated, because it's unsafe. Instead of using the deprecated method(s), you can modify some variable to indicate that the target thread should stop running.

Categories : Java

Synchronize List vs synchronize object inside list
... or if some other thread has a reference to some of the objects inside the list can modify it? Yes, they can modify the objects as they can acquire lock on your MyObject instances.

Categories : Java

Batch file creating folders in all folders of current directory
Total rewrite of answer. This will make a "Outlook Archive" folder in only the DataMy Documents subfolders of wherever the batch file resides. for /f "delims=" %%i in ('dir /ad/s/b') do if EXIST "%%iDataMy Documents" MKDIR "%%iDataMy DocumentsOutlook Archive" pause Credit to here

Categories : Windows

JQuery File Upload and Carrierwave to Detect Folders and Sub Folders
I don't think this is possible. See here: http://www.codeproject.com/Questions/573788/HoeplustoplusGetplustheplusOriginalplusfilepluspat It appears that you can't know the context of the uploaded file on the source operating system. Therefore you can't create it's original parent folder structure on your system.

Categories : Jquery

MATLAB: Opening and Editing Files nested in folders in folders
Check out subdir! On the file exchange, its an awesome function that can return all folders and all files in expansive subfolders, and you can filter file names by extension and whatnot. http://www.mathworks.com/matlabcentral/fileexchange/15859-subdir-a-recursive-file-search

Categories : Matlab

Qt - Tricky search algorithm - duplicates or "mirrored" duplicates in a list
1. Normalize links i.e. replace (a, b) to (b, a) when b < a. Each link should be represented as (a, b), a < b. 2. Create a QSet< QPair<Node*, Node *> > variable and put all links into it. Each link object can be maked using qMakePair(node1, node2). Since QSet is an qnique container, all duplicates will be removed automatically.

Categories : Qt

Creating data frame without duplicates in one column but could have duplicates in others
Not clear what you want since a data.frame has to be rectangular. Maybe you want this: tapply(s, n, list) #$A #[1] "aa" "dd" # #$B #[1] "bb" "aa" "cc" # #$C #[1] "cc"

Categories : R

Delete all folders except 2 lastest folders in Windows
for /f "skip=2 delims=" %G in ('dir /B /ad-h /o-d') DO echo going to delete %G For /f to process lines of "output" from single-quoted DIR... Delims= is better. tokens=* will work here, but suppresses leading spaces. /b to suppress header output from dir /o-d for REVERSE-date order. You want to KEEP the two skipped dirs, which occur FIRS in a reverse-date sort. ...good echo safety measure.

Categories : Windows

How to find duplicates in a std::vector and return a std::list of them sorted alphabetically without duplicates in that resulting list
Edit In response to comment: Remove duplicates function name is misleading, it is actually trying to return a list of words that are repeating in the sequence, but that result list only has one copy of each duplicate – user2624236 10 hours ago I hinted std::sort + std::adjacent_find(... std::equal_to<>). Here's the realization of that: template <typename C, typename T = typename C::value_type> std::list<T> adjacent_search(C input) { std::sort(begin(input), end(input)); static const auto eq = std::equal_to<T>{}; static const auto neq= std::not2(eq); std::list<T> dupes; auto end_streak = begin(input); auto dupe_at = std::adjacent_find(end_streak, end(input), eq); for(auto end_streak=begin(input); (dupe_at = st

Categories : C++

Is there any way to safely run SELECT INTO?
Unless you really don't know the fields and data types in advance, I'd recommend first creating the table, then adding the data with an Insert statement. In your link, David Moutray suggests the same thing, here's his example code verbatim: CREATE TABLE #TempTableY (ParticipantID INT NOT NULL); INSERT #TempTableY (ParticipantID) SELECT ParticipantID FROM TableX;

Categories : SQL

So what can you use delayedInit for safely?
If you make the hierarchy out of traits and only the leaf type a class you will get the behavior you want: object LearnDelayedInit extends App { trait A extends DelayedInit { def delayedInit(x: => Unit) { x //call constructor code println("delayed init called") } } trait B extends A { println("Hello from B") } class C extends B { println("hello from C") } val c = new C } Only the initialization code for classes is wrapped and passed to delayedInit, traits have their initialization code run in the constructor as usual.

Categories : Scala

Safely dispose within .net finalizer
I think you might've misunderstood IDispoable - the typical pattern on an IDisposable object is loosely: void Dispose() { Dispose(true); } void Dispose(bool disposing) { if (disposing) { // Free managed resources } // always free unmanaged resources } ~Finalizer() { Dispose (false); } Because the finalizer should always handle unmanaged resources, if you wait for it to run (which will be at some point in the future when memory constraints trigger the garbage collection, or it's triggered manually), you shouldn't leak. If you want to be deterministic about when those resources are freed, then you will have to expose IDispoable down your class hierarchy.

Categories : C#

Could you safely say this code is "unsafe"
You code is badly broken. Your declaration of GetProcessIoCounters is wrong. You are passing the address of the process handle but you need to pass the process handle by value. What's more there is no need at all for unsafe code here. I suggest you stop using unsafe. Here's how you declare GetProcessIoCounters: [DllImport(@"kernel32.dll", SetLastError=true)] static extern bool GetProcessIoCounters( IntPtr hProcess, out IO_COUNTERS IoCounters ); Your declaration of IO_COUNTERS is fine. To call the function you simply do this: IO_COUNTERS IoCounters; if (!GetProcessIoCounters(Process.GetCurrentProcess().Handle, out IoCounters)) throw new Win32Exception();

Categories : C#

Safely Get Tail of Array
First of all, the warning doesn't have anything to do with the fact that you're using an unsafe method. If you restart the REPL with -feature you'll see the following: scala> arr tail <console>:9: warning: postfix operator tail should be enabled by making the implicit value language.postfixOps visible... And a pointer to the documentation for scala.language.postfixOps, which includes the following note: Postfix operators interact poorly with semicolon inference. Most programmers avoid them for this reason. This is good advice. Being able to write arr tail instead of arr.tail isn't worth the fuss. Now about the safety issue. The standard library doesn't provide a tailOption for collections, but you can get the same effect using headOption and map: scala> val arr = Arr

Categories : Scala

How can I safely add to a composer package?
As far as I'm aware, you cannot add to a Composer package as it is external and therefore out of your control. You should treat the packages as libraries only, and add all classes into your own project, ensuring that the packages you need are still set up in your .json file

Categories : PHP

Safely upload gif images
Definitely not, as one could change page code on client side and submit whatever they want to your server. This applies to the file size too. You should validate the file server-side, checking against its MIME content-type. You could do that preferably with getimagesize() function. Improving your server-side code: if (isset($_REQUEST['upload'])) { list(,, $image_type) = @getimagesize($_FILES['file']['tmp_name']); if (filesize($_FILES['file']['tmp_name']) <= 65536 && $image_type === IMAGETYPE_GIF) { move_uploaded_file($_FILES['file']['tmp_name'], sprintf('../images/logos/%s.gif', str_replace(' ', '_', $name))); } } You can improve that even more splitting checks and raising error messages to the user. I'll leave that for you.

Categories : PHP

Accessing files in iOS safely
Api's that check for the existence of files typically return a true or false. False usually means that the file is in-accessable not that it doesn't exist. So for example if the file existed on a file share but you had no read permission it would return false. It maybe the same if another thread or user had the file open already for example. Obviously on iOS some of these reasons are unlikely but something similar could be occurring.

Categories : IOS

Is it SAFELY possible to use a str(BlobKey) as datastore id?
Seems like your question is asking whether you can create some kind of "virtual ancestor group" by specifying a parent that doesn't exist. This is legitimate, it's mentioned in the docs that the parent doesn't actually need to exist. https://developers.google.com/appengine/docs/python/datastore/entities#Python_Ancestor_paths Alternatively, if your list of BlobReferences will be limited, it would probably be easier and less expensive to just store a list of them inside one entity. You an make the Key of that container entity the same as the BlobKey. Then fetching that entity by key and modifying it will let you work without eventual consistency problems. It'll also be cheaper than querying and modifying indexed entities.

Categories : Google App Engine

how to use std::map in threaded application safely?
Without looking at code, I can only say that you use a ConcurrentHashMap for your needs. You may also want to read this : What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

Categories : Misc

How can you safely tell that a TCP/IP packet was received at the other end?
The TCP connection isn't really down unless the socket closes on your side. It takes minutes for TCP to decide the connection is down and close the socket if it doesn't receive any response from the network after sending data.

Categories : C#

should I synchronize the deque or not
The deque has to keep track of how many elements it has and where those elements are. Adding an element changes that stored data, as does removing an element. Changing that data from two threads without synchronization is a data race, and produces undefined behavior. In short, you must synchronize those operations.

Categories : C++

How to synchronize QNetworkAccessManager?
Erm... what are you doing? You create a QNetWorkManager, connect the finished signal to a replyFinished slot and expect to get a result, which comes from replyFinished before you even sent the request? Sorry, but from what I see in your code, I'd say it is beyond repair. The foreach (QString delIdList, deleteIdList) must be in the replyFinished slot, when deleteIdList is somehow a result of your request. And QUrl url(requestUrl); QNetworkRequest request; request.setUrl(url); manager->get(request); must be outside the loop below your connect. But of course, your code is so wrong, that my 'hints' are just rough guess work about what you might intend to do.

Categories : C++

How to synchronize frames
finally i have done it using javascript. The first script generates top.frames[1].location = .... with parameter exec=1 initially the frame is called with different parameter exec=0 if ($_GET['exec'] == '0') return; // in the beginning of second php

Categories : Misc

How to safely convert unsigned value to signed?
Eventually, is there a way that is simpler, not relying on undefined behaviour and doing the same thing? short x = (short) value; int y = (int) value; But be sure on what integral type you are casting to. value may go out of the range of the signed type used.

Categories : C++

Safely evaluating arithmetic expressions in R?
I'd take a slightly different approach to defining the safe functions and the environment in which you evaluate arbitrary code, but it's really just some style changes. This technique is provably safe, provided all of the functions in safe_f are safe, i.e. they don't allow you to perform arbitrary code execution. I'd be pretty confident the functions in list are safe, but you'd need to inspect the individual source code to be sure. safe_f <- c( getGroupMembers("Math"), getGroupMembers("Arith"), getGroupMembers("Compare"), "<-", "{", "(" ) safe_env <- new.env(parent = emptyenv()) for (f in safe_f) { safe_env[[f]] <- get(f, "package:base") } safe_eval <- function(x) { eval(substitute(x), env = safe_env) } # Can't access variables outside of that environment a

Categories : R

Can sync.WaitGroup safely be reused?
Yes, it is safe. In fact, it is even safer than that. You can Wait from multiple goroutines concurrently, and interchange Add and Done calls as appropriate for your use case. As long as the Add happens before the Wait, you should be safe. Just out of curiosity, right now the WaitGroup is implemented with a mutex, two int32s counters, and a semaphore: type WaitGroup struct { m Mutex counter int32 waiters int32 sema *uint32 } This is also an interesting test: var wg1, wg2 sync.WaitGroup wg1.Add(1) wg1.Done() wg1.Wait() fmt.Println(wg1 == wg2) // Prints true Finally, if you do find any issues with that kind of use, please report as it would be a bug.

Categories : Go

How to work with plist file using GCD safely?
You should use a single, serial queue for both reading and writing. That way, you're ensured that they won't interfere with each other. For example, in viewDidLoad you could create your queue: self.queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); And then you can use it when saving: dispatch_async(self.queue, ^{ // save }); and when reading: dispatch_async(self.queue, ^{ // read }); This is one of the primary purposes of serial queues, to synchronize the access to some shared resource (see the discussion of serial queues).

Categories : Objective C

Am I safely deleting a linked list?
It would be more C++ if you passed head pointer by reference, not by pointer: void deleteList(Node * & head) { // (...) head = nullptr; // NULL in C++ pre-11 } Also, to keep code a little more tidy, you can move declaration of next inside the loop: while (current != 0) { Node * next = current->next; delete current; current = next; } My only worries about memory leak would concern properly freeing node's contents, but since you store a simple int, there shouldn't be any problems there. Assuming, that your list have valid pointers to nodes and that head pointer is valid too, everything else seems fine.

Categories : C++

Safely writing bytes to stream
The conversion from unsigned char to char and back is perfectly fine, and it's exactly what you should be doing. All three char types are layout compatible. You only have to be careful with any non-char integral types and convert them to uint8_t first before converting to char, etc., and similarly in the other direction.

Categories : C++

How to std::swap elements in a container safely
The fact that i is a reverse iterator makes no difference. If you want to swap the value at i with the first value of the vector, you should do what you are doing. Also note that the iterator returned by end() is after the last element in the vector and should never be dereferenced.

Categories : C++

How to safely wait for async method?
You're running into a deadlock that I describe on my blog. There is no standard solution for blocking on an async method, because there is no solution that works in every situation. The only officially recommended solution is to use async all the way. Stephen Toub has a good summary of workarounds here. One approach is to execute the async method in a background thread (via Task.Run) and then Wait on that. Disadvantages of this approach are: 1) it won't work for async methods that require a specific context (e.g., write to an ASP.NET response, or update a UI); 2) changing from a synchronized context to the unsynchronized thread pool context may introduce race conditions; and 3) it burns a thread just waiting for another thread. Another approach is to execute the async method within a ne

Categories : C#

How to safely store sensitive data?
pycrypto has many tools for this. They have many standard types of encryption included in the module. Here is a quick tutorial.

Categories : Python

Efficiently and safely assigning unique IDs
With an uint64_t (64bit), it would take you well, well over 100 years, even if you insert somewhere close to 100k entries per second. Over 100 years, you should insert somewhere around 315,360,000,000,000 records (not taking into account leap years and leap seconds, etc). This number will fit into 49 bits. How long to you anticipate that application to run? Over 100 years? This is the common thing database administrators do when they have an autoincrement field that apprpaches the 32bit limit. They change the value to the native 64bit type (or 128bit) for their DB system.

Categories : C++

How to safely keep a decrypted temporary data?
Yes, keeping the database in memory seems to be a viable solution. What makes this a bit difficult is that SQLite can easily create a database in memory (using :memory: instead of filename) but making it load already existing in-memory database is a bit of a pain: you'll have to implement your own sqlite_vfs. I've seen one implementation but it's pretty old, I'm not sure that it still works. Also, using it from Python will require extra effort. Still, keeping the whole decrypted database always in memory is not very secure, since your memory may occasionally get paged to disk. So, remember to mlock it. A simpler solution is having an ordinary database, but encrypting all the data before storing in it. This way, you'll have to keep in memory only the password and small little chunks of dec

Categories : Python

Javascript safely use user regex
This should not cause any security errors. Worse case scenario you are using an invalid regEx string. Unless I am misunderstanding the question. EDIT Worse case scenario is locking up your own browser. Thanks Anirudh for bringing this point up.

Categories : Javascript

Which elements can be safely made contenteditable?
This question has no meaningful answer. It will vary from browser version to browser version and with the rapid development of both Chrome and Firefox any answer will be out of date before the bytes have dried. Using new/experimental features in HTML (or any other standard) should only be done as an enhancement of existing or complementary solutions. One day we will be able to use contentEditable at will, but it's a ways off. Either you'll have to support the same/similar features in some other way (don't think there is a polyfill for contentEditable) or restrict what browsers your users can use (easier in a backend app such as a CMS or admin panel). But setting up a table for what elements works how with contentEditable on every browser/version combo is a herculean task. It would also

Categories : HTML

How to quit HandlerThread's looper safely
Im not Thread Guru, but this way can give you direction: ... _thread.setRunning(true); _thread.start(); .. public void stopThread(){ boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; Log.e("test", "thread stopped"); } catch (InterruptedException e) { Log.e("test", "can't stop thread, retrying..."); // we will try it again and again... } } } In your thread: while (isRunning) { //... } 1st all you implement run method in loop (while(isRunnig){}). On finish, you switch flag to false and "wait" for join.

Categories : Android

Insert value to MySQL table safely using PDO
YES, PDO Extension already removes all the injection vulnerabilities like that. Since you are binding params afters ward, you are doing it correctly too. However, just to make the query at it safest state, specify the data type of the variable while binding them. $query = $db->prepare('INSERT INTO login (username,password,name,email_add,age,country) VALUES (:username,:password,:name,:email_add,:age,:country)'); $query->bindParam(':username', $username, PDO::PARAM_STR, 20); // and so on $query -> execute(); More Details

Categories : Mysql



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.