void SplDoublyLinkedList::setIteratorMode (int $mode)Parameters:This function takes one parameter, $mode,which contains two orthogonal sets of modes, which are listed below:
Direction of iteration:
- SplDoublyLinkedList::IT_MODE_LIFO (stack style)
- SplDoublyLinkedList::IT_MODE_FIFO (queue style)
- SplDoublyLinkedList::IT_MODE_DELETE (items are removed by the iterator)
- SplDoublyLinkedList::IT_MODE_KEEP (items are iterated over)
Program 1:
& l t;? php
// Declare an empty SplDoublyLinkedList
$list
=
new
SplDoublyLinkedList();
// Add item to SplDoublyLinkedList
$list
-> setIteratorMode (SplDoublyLinkedList::IT_MODE_FIFO);
// Use the getIteratorMode() function
$mode
=
$list
-> getIteratorMode();
var_dump (
$mode
);
// Add item to SplDoublyLinkedList
$list
-> setIteratorMode (SplDoublyLinkedList::IT_MODE_DELETE);
// Use the getIteratorMode() function
$mode
=
$list
-> getIteratorMode();
var_dump (
$mode
);
// Add item to SplDoublyLinkedList
$list
-> setIteratorMode (SplDoublyLinkedList::IT_MODE_LIFO);
// Use the getIteratorMode() function
$mode
=
$list
-> getIteratorMode();
var_dump (
$mode
);
?>
Exit:int (0 ) int (1) int (2)Program 2:
// Declare an empty SplDoublyLinkedList
$list
=
new
SplDoublyLinkedList ( );
// Add item to SplDoublyLinkedList
$list
-> setIteratorMode (SplDoublyLinkedList::IT_MODE_FIFO
| SplDoublyLinkedList::IT_MODE_DELETE
| SplDoublyLinkedList::IT_MODE_LIFO);
$mode
=
$list
-> getIteratorMode();
var_dump (
$mode
& amp; SplDoublyLinkedList::IT_MODE_FIFO);
var_dump (
$mode
& amp; SplDoublyLinkedList::IT_MODE_LIFO);
var_dump (
$mode
& amp; SplDoublyLinkedList::IT_MODE_DELETE);
var_dump (
$mode
& amp; SplDoublyLinkedList::IT_MODE_KEEP);
?>
Exit:int (0 ) int (2) int (1) int (0)
Link: https://www.php.net/manual/en/spldoublylinkedlist.setiteratormode.php
PHP SplDoublyLinkedList setIteratorMode () function: StackOverflow Questions
How can I make a time delay in Python?
I would like to know how to put a time delay in a Python script.
Answer #1:
import time
time.sleep(5) # Delays for 5 seconds. You can also use a float value.
Here is another example where something is run approximately once a minute:
import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).
Answer #2:
You can use the sleep()
function in the time
module. It can take a float argument for sub-second resolution.
from time import sleep
sleep(0.1) # Time in seconds
Answer #3:
How can I make a time delay in Python?
In a single thread I suggest the sleep function:
>>> from time import sleep
>>> sleep(4)
This function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.
Use it for that purpose, or simply to delay a function from executing. For example:
>>> def party_time():
... print("hooray!")
...
>>> sleep(3); party_time()
hooray!
"hooray!" is printed 3 seconds after I hit Enter.
Example using sleep
with multiple threads and processes
Again, sleep
suspends your thread - it uses next to zero processing power.
To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can"t find the party_later
function for some reason):
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time
def party_later(kind="", n=""):
sleep(3)
return kind + n + " party time!: " + __name__
def main():
with ProcessPoolExecutor() as proc_executor:
with ThreadPoolExecutor() as thread_executor:
start_time = time()
proc_future1 = proc_executor.submit(party_later, kind="proc", n="1")
proc_future2 = proc_executor.submit(party_later, kind="proc", n="2")
thread_future1 = thread_executor.submit(party_later, kind="thread", n="1")
thread_future2 = thread_executor.submit(party_later, kind="thread", n="2")
for f in as_completed([
proc_future1, proc_future2, thread_future1, thread_future2,]):
print(f.result())
end_time = time()
print("total time to execute four 3-sec functions:", end_time - start_time)
if __name__ == "__main__":
main()
Example output from this script:
thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037
Multithreading
You can trigger a function to be called at a later time in a separate thread with the Timer
threading object:
>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!
>>>
The blank line illustrates that the function printed to my standard output, and I had to hit Enter to ensure I was on a prompt.
The upside of this method is that while the Timer
thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).
There isn"t a respective object in the multiprocessing library. You can create one, but it probably doesn"t exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new subprocess.
Answer #4:
Delays can be also implemented by using the following methods.
The first method:
import time
time.sleep(5) # Delay for 5 seconds.
The second method to delay would be using the implicit wait method:
driver.implicitly_wait(5)
The third method is more useful when you have to wait until a particular action is completed or until an element is found:
self.wait.until(EC.presence_of_element_located((By.ID, "UserName"))
How to delete a file or folder in Python?
How do I delete a file or folder in Python?
Answer #1:
os.remove()
removes a file.
os.rmdir()
removes an empty directory.
shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.
pathlib.Path.rmdir()
removes an empty directory.
PHP SplDoublyLinkedList setIteratorMode () function: StackOverflow Questions
Answer #2:
os.remove()
removes a file.
os.rmdir()
removes an empty directory.
shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.
pathlib.Path.rmdir()
removes an empty directory.
Answer #3:
Python syntax to delete a file
import os
os.remove("/tmp/<file_name>.txt")
Or
import os
os.unlink("/tmp/<file_name>.txt")
Or
pathlib Library for Python version >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
Unlink method used to remove the file or the symbolik link.
If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
Best practice
- First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
a. os.path.isfile("/path/to/file")
b. Use exception handling.
EXAMPLE for os.path.isfile
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
Exception Handling
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
RESPECTIVE OUTPUT
Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.
Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.
Enter file name to delete : foo.txt
Python syntax to delete a folder
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
Answer #4:
Here is a robust function that uses both os.remove
and shutil.rmtree
:
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
Is there a simple way to delete a list element by value?
I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The above case (in which it does not exist) shows the following error:
Traceback (most recent call last):
File "D:zjm_codea.py", line 6, in <module>
b = a.index(6)
ValueError: list.index(x): x not in list
So I have to do this:
a = [1, 2, 3, 4]
try:
b = a.index(6)
del a[b]
except:
pass
print(a)
But is there not a simpler way to do this?
Answer #1:
To remove an element"s first occurrence in a list, simply use list.remove
:
>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]
Mind that it does not remove all occurrences of your element. Use a list comprehension for that.
>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]
Answer #2:
Usually Python will throw an Exception if you tell it to do something it can"t so you"ll have to do either:
if c in a:
a.remove(c)
or:
try:
a.remove(c)
except ValueError:
pass
An Exception isn"t necessarily a bad thing as long as it"s one you"re expecting and handle properly.