Category Archives: Coder

The bilibilibili cache video cache batch converted to MP4 format Python code

It is recommended to use virtual machine or Android mobile phone to download the cache

After the conversion, play more free, I hope to help you

Default cache location: Android – Data – ta.danmaku.bili – Download

How to use: put the script in the same directory as the cache, input the file name after execution, and then convert instantly

Only tested Mac, win should be universal, no test

Before conversion – after conversion:

import os, shutil #Import the required more reports
work_dir = os.getcwd() #Get the working directory


def main():
    old_dir = input("Enter the name of the directory to process") # Prompt for a filename similar to : 34387218
    new_dir = old_dir+"_MP4" # Enter the name of the file to be stored
    if(os.path.exists(new_dir)): # determine if it exists, if so delete and rebuild
        print(new_dir+"already exists, already rebuilt")
        shutil.rmtree(new_dir) 
        os.mkdir(new_dir)
    else:
        print(new_dir+"Created successfully")
        os.mkdir(new_dir)

    for i in os.listdir(os.path.join(work_dir, old_dir)): # Loop through
        if(i == ".DS_Store"): # Skip the file created by Apple by default
            continue
        for o in os.listdir(os.path.join(work_dir, old_dir, i)): # Start loop inside
            if(o == ".DS_Store"): # Skip files created by Apple by default
                continue
            if(os.path.isdir(os.path.join(work_dir, old_dir, i, o))): # Enter second level loop
                for p in os.listdir(os.path.join(work_dir, old_dir, i, o)): # Start the operation loop
                    if(o == ".DS_Store"): # Skip the file created by Apple by default
                        continue
                    file_name = os.path.basename(p) # Get the name of the file
                    if file_name.endswith(".blv"): # Determine if the name format is correct
                        f_file_name = file_name.split('.') # Split the file name
                        index = int(f_file_name[0]) + 1
                        old_file = os.path.join(work_dir, old_dir, i, o, p) # Get the old file
                        shutil.move(old_file,new_dir) # move the file
                        new_file = str(i)+"_"+str(index)+".mp4" # customize the new file name
                        os.rename(os.path.join(work_dir, new_dir,file_name), os.path.join(work_dir, new_dir, new_file)) # Perform rename
                    
                        
if __name__ == "__main__":
    main()

Beyond compare is an Excel to TXT script to solve the problems of special characters unable to output, multiple sheet pages unable to compare, and files too large to exceed the system memory

Beyond compare is an Excel to TXT script to solve the problems of special characters unable to output, multiple sheet pages unable to compare, and files too large to exceed the system memory

' XLS_to_CSV.vbs
'
' Converts an Excel workbook to a comma-separated text file.  Requires Microsoft Excel.
' Usage:
'  WScript XLS_to_CSV.vbs <input file> <output file>

Option Explicit

' MsoAutomationSecurity
Const msoAutomationSecurityForceDisable = 3
' OpenTextFile iomode
Const ForReading = 1
Const ForAppending = 8
Const TristateTrue = -1 
' XlFileFormat
Const xlCSV = 6 ' Comma-separated values
Const xlUnicodeText = 42
' XlSheetVisibility
Const xlSheetVisible = -1

Dim App, AutoSec, Doc, FileSys, AppProtect
Set FileSys = CreateObject("Scripting.FileSystemObject")
If FileSys.FileExists(WScript.Arguments(1)) Then
    FileSys.DeleteFile WScript.Arguments(1)
End If
Set App = CreateObject("Excel.Application")
'Set AppProtect = CreateObject("Excel.Application")

On Error Resume Next

App.DisplayAlerts = False
AutoSec = App.AutomationSecurity
App.AutomationSecurity = msoAutomationSecurityForceDisable
Err.Clear

Dim I, J, SheetName, TgtFile, TmpFile, TmpFilenames(), Content
Set Doc = App.Workbooks.Open(WScript.Arguments(0), False, True)
If Err = 0 Then
    I = 0
    For J = 1 To Doc.Sheets.Count
        If Doc.Sheets(J).Visible = xlSheetVisible Then
            I = I + 1
        End If
    Next
    ReDim TmpFilenames(I - 1)
    Set TgtFile = FileSys.OpenTextFile(WScript.Arguments(1), ForAppending, True, TristateTrue)
    I = 0
    For J = 1 To Doc.Sheets.Count
        If Doc.Sheets(J).Visible = xlSheetVisible Then
            SheetName = Doc.Sheets(J).Name
            TgtFile.WriteLine """SHEET " & SheetName & """"
            Doc.Sheets(J).Activate
            TmpFilenames(I) = FileSys.GetSpecialFolder(2) & "\" & FileSys.GetTempName
            Doc.SaveAs TmpFilenames(I), xlUnicodeText
            Set TmpFile = FileSys.OpenTextFile(TmpFilenames(I), ForReading, False, TristateTrue)
            'Write Writing the entire file will cause all the contents of the file to be lost if the write fails, so use the line-by-line method.
            ' It also prevents the problem of insufficient memory for too large files
            while not TmpFile.AtEndOfStream
                TgtFile.WriteLine TmpFile.ReadLine
            Wend
            'TgtFile.Write TmpFile.ReadAll
            TmpFile.Close
            If I <> UBound(TmpFilenames) Then
                TgtFile.WriteLine
            End If
            Doc.Sheets(J).Name = SheetName
            I = I + 1
        End If
    Next
    TgtFile.Close
    Doc.Close False
End If

App.AutomationSecurity = AutoSec
App.Quit
Set App = Nothing

For I = 0 To UBound(TmpFilenames)
    If FileSys.FileExists(TmpFilenames(I)) Then
        FileSys.DeleteFile TmpFilenames(I)
    End If
Next

WScript.Sleep(1000)

'This step is to expose the failed window to the foreground for the user to close manually, which should be ignored by the On Error Resume Next catch above
App.Visible = true

If AppProtect.Workbooks.
' 'Protected processes can not just exit, the user may be using        
'    AppProtect.Quit
'End If
'AppProtect.Visible = true
'Set AppProtect = Nothing

‘ XLS_to_CSV.vbs” Converts an Excel workbook to a comma-separated text file. Requires Microsoft Excel.’ Usage:’ WScript XLS_to_CSV.vbs <input file> <output file>
Option Explicit
‘ MsoAutomationSecurityConst msoAutomationSecurityForceDisable = 3′ OpenTextFile iomodeConst ForReading = 1Const ForAppending = 8Const TristateTrue = -1’ XlFileFormatConst xlCSV = 6 ‘ Comma-separated valuesConst xlUnicodeText = 42′ XlSheetVisibilityConst xlSheetVisible = -1
Dim App, AutoSec, Doc, FileSys, AppProtectSet FileSys = CreateObject(“Scripting.FileSystemObject”)If FileSys.FileExists(WScript.Arguments(1)) ThenFileSys.DeleteFile WScript.Arguments(1)End IfSet App = CreateObject(“Excel.Application”)’Set AppProtect = CreateObject(“Excel.Application”)
On Error Resume Next
App.DisplayAlerts = FalseAutoSec = App.AutomationSecurityApp.AutomationSecurity = msoAutomationSecurityForceDisableErr.Clear
Dim I, J, SheetName, TgtFile, TmpFile, TmpFilenames(), ContentSet Doc = App.Workbooks.Open(WScript.Arguments(0), False, True)If Err = 0 ThenI = 0For J = 1 To Doc.Sheets.CountIf Doc.Sheets(J).Visible = xlSheetVisible ThenI = I + 1End IfNextReDim TmpFilenames(I – 1)Set TgtFile = FileSys.OpenTextFile(WScript.Arguments(1), ForAppending, True, TristateTrue)I = 0For J = 1 To Doc.Sheets.CountIf Doc.Sheets(J).Visible = xlSheetVisible ThenSheetName = Doc.Sheets(J).NameTgtFile.WriteLine “””SHEET ” & SheetName & “”””Doc.Sheets(J).ActivateTmpFilenames(I) = FileSys.GetSpecialFolder(2) & “\” & FileSys.GetTempNameDoc.SaveAs TmpFilenames(I), xlUnicodeTextSet TmpFile = FileSys.OpenTextFile(TmpFilenames(I), ForReading, False, TristateTrue)’Write If you write the whole file, a write failure will cause all the contents of the whole file to be lost, so a line-by-line approach is used.’ It can also prevent the problem of too large file with insufficient memory while not TmpFile.AtEndOfStream TgtFile.WriteLine TmpFile.ReadLine Wend ‘TgtFile.Write TmpFile.ReadAllTmpFile.CloseIf I <> UBound(TmpFilenames) ThenTgtFile.WriteLineEnd IfDoc.Sheets(J).Name = SheetNameI = I + 1End IfNextTgtFile.CloseDoc.Close FalseEnd If
App.AutomationSecurity = AutoSecApp.QuitSet App = Nothing
For I = 0 To UBound(TmpFilenames)If FileSys.FileExists(TmpFilenames(I)) ThenFileSys.DeleteFile TmpFilenames(I)End IfNext
WScript.Sleep(1000)
‘This step is designed to expose the failed window to the foreground for the user to close manually, which should be ignored by the above On Error Resume Next capture App.Visible = true
If AppProtect.Workbooks.Count = 0 Then’ ‘The protection process can’t just exit, the user may be using ‘ AppProtect.Quit’End If’AppProtect.Visible = true’Set AppProtect = Nothing

sklearn.utils.validation.check_random_state(seed)

Parameters:

————————————————————————————————————

Seed: if seed is none, random state singleton (NP. Random) is returned

If seed is int, a new random state instance is returned, which is generated by the new seed

If seed is a random state instance, it returns itself directly

Process

————————————————————————————————————

defcheck_random_state(seed):

"""Turnseedintoanp.random.RandomStateinstance
IfseedisNone,returntheRandomStatesingletonusedbynp.random.
Ifseedisanint,returnanewRandomStateinstanceseededwithseed.
IfseedisalreadyaRandomStateinstance,returnit.
OtherwiseraiseValueError.
"""
#Returns np.random.mtrand._rand if seed is None or np.random.
ifseedisNoneorseedisnp.random:
returnnp.random.mtrand._rand

#seed for numbers.Intergral or np.integer instances.
ifisinstance(seed,(numbers.Integral,np.integer)):
returnnp.random.RandomState(seed)

#Returns itself if it is np.random.RandomState.


ifisinstance(seed,np.random.RandomState):
returnseed


# Error is reported if it is not the above case.


raiseValueError('%rcannotbeusedtoseedanumpy.random.RandomState'
'instance'%seed)

Install a docker container in centos7 that can log in SSH

Recently, I’ve been working on docker, which really excited me for a few days. Let’s share the installation process

Because docker requires a higher version of Linux kernel, I installed centos7 in VBox. As for how to install CentOS 7, I don’t need to worry about it. Here is the minimal installation

First, configure the network card to ensure that the virtual machine can access the network normally, because the installation of docker requires networking. I am usually used to setting up two network cards when installing virtual machine. One uses NAT to connect and is responsible for surfing the Internet; A host only connection is used to connect the host to the virtual machine. Then enable the two network cards, the simplest way is to enter dhclient mode, the system will automatically assign IP to the network card

First of all, the command to install docker:
is used

#yum-yinstalldocker

After the installation, you can use the following command to view the available images:

#dockerimages
REPOSITORYTAGIMAGEIDCREATEDVIRTUALSIZE

At this time, no image is available and the container cannot be started, so we need to download the image. In this step, we can choose to download images of different systems. Here, we still choose the most familiar CentOS. In this step, docker will download image files online

#dockerpullcentos

Wait until the image download is completed, and then use the docker images command to see several CentOS images:

#dockerimages
REPOSITORYTAGIMAGEIDCREATEDVIRTUALSIZE

 

First, build a docker container that can be accessed through SSH

1. Start a docker container:

#dockerrun-i-tcentos/bin/bash

This creates a new docker container and enters the bash of the container

2. Install sshd:

#yum-yinstallopenssh-server

3. Start sshd. Use absolute path here. To view the path of a command, use where is or which:

#/usr/sbin/sshd-D

The following error occurs when starting sshd under centos.

Could not load host key: /etc/ssh/ssh_host_rsa_key

Could not load host key: /etc/ssh/ssh_host_dsa_key

Simply execute the following commands in sequence.

ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key #just enter

ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key #just enter

ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N “”

Press and start the sshd service again, it should be fine. 4.

4. After finishing, edit the sshd_config configuration file, find the paragraph UsePAM yes, change it to UsePAM no

#UsePAMno
UsePAMyes
to
UsePAMno
#UsePAMyes

If you don’t modify this paragraph, you will exit immediately when you log in to the container using SSH

5. Install passwd and change the password of root

#yum-yinstallpasswd
#passwroot
Changingpasswordforuserroot.
Newpassword:

6. After changing the password, execute the exit command to exit. At this time, you will return to the shell of the host machine and execute the following command to submit the container to the image:

#dockercommitcontaineridimagename

Here, containerid is the ID of the container, and imagename is the name of the image at the time of submission. It’s better to use a new name when submitting for the first time, instead of covering the original clean CentOS image

The container ID can be viewed through the docker PS – L command. After starting the container, the default host name is actually the container ID

7. Start a new container through docker run. The parameter – D means running in the background and – P means mapping the docker to the host port

#dockerrun-d-p10022:22imagename/usr/sbin/sshd-D

If there is no problem starting, you can log in to the container:

#sshroot@localhost-p10022

After logging in, we can install all kinds of software and build all kinds of environments

Settext notes of Textview (How to Use)

##Do not concatenate text displayed with settext

prodNameView.setText("" + name);  
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));

How do you suggest

Do not concatenate text displayed with setText. Do not concatenate text displayed with setText. Use resource string with placeholders.

When calling TextView#setText:

Never call Number#toString() to format numbers; locale-specific digits properly. it will not handle fraction separators and locale-specific digits properly. Consider using String#format with proper format specifications (%d or %f) instead.

Do not pass a string literal (e.g. “Hello”) to display text. Hardcoded text can not be properly translated to other languages. Consider using Android resource strings instead.

Do not build messages by concatenating text chunks. Do not build messages by concatenating text chunks. Such messages can not be properly translated.

Simply put, there are three things to keep in mind when using the setText method of a TextView.

If a number, use String#formatto modify

Special compilation, but use Android String36164; source file

Character set using+progress

##example in String36164;

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

Setting in textview by settext

hello.setText(getString(R.string.welcome_messages,"John",10));

##Refer to the problems in stackoverflow

Android official document

Mac OS: How to Copy an operating system image to an SD card

First, verify the path to your SD card. You can do this by running the following command from a terminal:

diskutil list

In this case i can verify /dev/disk2 is my SD card because the TYPE,NAME and Size values are correct.

IF you have an existing partiton on the disk you may need to unmount it,otherwise you’will get a ”Resource Busy” error message when you try to write the image .

diskutil unmount /dev/disk2s1

Now to write the image file to the disk. Note the ‘r’ added to rdisk2 which drastically improves write performance by telling dd to operate in raw disk mode:

sudo dd if=2019-09-26-raspbian-buster.img of=/dev/rdisk2 bs=1m

Depending on the size of your SDcard this may take a while. You can press CTRL+T to see the current status of dd.

Copy the image

From Terminal, enter:

sudo dd bs=1m if=path_of_your_image.img of=/dev/rdiskN conv=sync

ReplaceNwith the number that you noted before.

This can take more than 15 minutes, depending on the image file size. Check the progress by pressing Ctrl+T.

If the command reportsdd: bs: illegal numeric value, change the block sizebs=1mtobs=1M.

If the command reportsdd: /dev/rdisk2: Operation not permittedyou need to disable SIP before continuing.

If the command reports the errordd: /dev/rdisk3: Permission denied, the partition table of the SD card is being protected against being overwritten by Mac OS. Erase the SD card’s partition table using this command:

sudo diskutil partitionDisk /dev/diskN 1 MBR "Free Space" "%noformat%" 100%

That command will also set the permissions on the device to allow writing. Now issue theddcommand again.

After theddcommand finishes, eject the card:

sudo diskutil eject /dev/rdiskN

filter:progid:DXImageTransform.Microsoft.Gradient

1.Transparency
Writing

1.1 mainstream browser writing

div{background-color:rgba(255,255,255,0.8);}/*forIE10+,firefox,chrome*/

1.2 for IE 9-browser

div{filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr="#ccffffff",EndColorStr="#ccffffff");/*IE6-9*/}

 

2. grammar intensive lectures

2.1filter:progid:DXImageTransform.Microsoft.Gradient( )

filter:progid:DXImageTransform.Microsoft.Gradient(
GradientType=0,/*GradientType:Read and writeable. Integer value (Integer). Set or retrieve the direction of the color gradient. 1|0*/
StartColorStr="#ccffffff",/*Optional. String(String). Set or retrieve the start color and transparency of the color gradient. */
EndColorStr="#ccffffff" /* optional. String(String). Set or retrieve the end color and transparency of the color gradient. */
)

/*
*@StartColorStr,EndColorStr: its format is #AARRGGBB.
*AA, RR, GG, BB are hexadecimal positive integers. The range of values is 00-FF.
*RR specifies the red value, GG specifies the green value, BB specifies the blue value, and AA specifies the transparency (00 is completely transparent, FF is completely opaque). Values out of the range will be restored to the default value.
* StartColorStr, default value is #FF0000FF, opaque blue, EndColorStr, default value is #FF000000, opaque black.
*/

 

10% 20% 30% 40% 50% 60% 70% 80% 90%
33 4b 66 99 cc

 

Wpa_supplicant Debugging Failure Cause Analysis

Background

When using WPA_ When using the supplicant tool to debug Linux WiFi, we found some problems. For the record. Some problems are encountered and have been solved. Some problems are complicated and can only be used as ideas

Problems and Solutions

1. Error not running in the background 

Failed to connect to non-global ctrl_ifname: (nil) error: No such file or directory 

solution: let WPA_ Supplicant runs in the background, for example:

nohup wpa_supplicant -c wpa.conf > /tmp/wpa_supplicant.log &

2

Failed to connect to non-global ctrl_ifname: wlan0  error: No such file or directory

solution: - I the device name of the specified parameter is wrong. You can check it through ifconfig and correct it later. Generally, it is because there is no correct network card driver

3. Problems caused by multiple services

ctrl_iface exists and seems to be in use - cannot override it 
Delete ‘/var/run/wpa_supplicant/wlo1’ manually if it is not used anymore 
Failed to initialize control interface ‘/var/run/wpa_supplicant’. 
You may have another wpa_supplicant process already running or the file was 
left by an unclean termination of wpa_supplicant in which case you will need 
to manually remove this file before starting wpa_supplicant again. 

solution : multiple open wpas already exist in the system_ Supply instance, execute kill WPA_ Supplicant kill all WPA_ Supplicant is OK

4. Error caused by no corresponding driver in the kernel rfkill: cannot open rfkill control device solution: add the corresponding driver to the kernel

Networking support
        <*>   RF switch subsystem support  --->
                [*]   Power off on suspend (NEW)
                <*>   Generic rfkill regulator driver 

5:在ASSOCIATING阶段由于丢包导致ASSOC REJECT

Event [IFNAME=wlan0 CTRL-EVENT-DISCONNECTED bssid=08:cc:68:9e:ac:20 reason=3 locally_generated=1]
I/wpa_supplicant(23065): wlan0: CTRL-EVENT-ASSOC-REJECT bssid=0e:bd:51:c7:b6:33 status_code=1

solutions

6. In 4way_ In the stage of handshake W Rong is caused by password error, frame loss or weak signal packet loss_ KEY

It can be divided into the following situations:

Password error in 4way_ Two out of four handshakes in the handshake phase will display wrong key

If it has been connected, it will display:

01-01 23:19:01.778 I/wpa_supplicant(19043): wlan0: CTRL-EVENT-SSID-TEMP-DISABLED id=1 ssid="Onetouch Idol 3 (4.7)" > auth_failures=1 duration=5 reason=WRONG_KEY。

Loss of frame results in disconnection:

Line 127671:< 3>[86294.177961] wlan: [24597:E :PE ] limHandleMissedBeaconInd: 2121: Sending EXIT_BMPS_IND to SME due to Missed beacon from FW

Disconnection due to weak signal:

02-28 21:56:59.703 I/wpa_supplicant(31023): wlan0: CTRL-EVENT-DISCONNECTED bssid=c8:3a:35:2b:71:30 reason=0

02-28 21:56:59.713 E/WifiStateMachine( 821): NETWORK_DISCONNECTION_EVENT in connected state BSSID=c8:3a:35:2b:71:30 RSSI=-89 freq=2437 was debouncing=false reason=0 ajst=0

# reason=0 means disconnected because of weak signal.

7:4WAY_ Hanshak succeeded but DHCP failure (four step handshake succeeded but IP address acquisition failed)

03-14 14:21:59.681 E/WifiStateMachine(28360): WifiStateMachine DHCP failure count=0

03-14 14:21:59.705 E/WifiConfigStore(28360): message=DHCP FAILURE

8. Being kicked out by AP requires sniffer log analysis 2

reason=2,reason=7,reason=15 means kicked out by AP, and the corresponding deauth information can be found in the kernel log.

03-14 14:21:29.932 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-DISCONNECTED bssid=c4:14:3c:29:47:05 reason=7
< 3>[86553.353983] wlan: [28055:E :PE ] limProcessDeauthFrame: 144: Received Deauth frame for Addr: 44:a4:2d:52:bc:a5 (mlm state = eLIM_MLM_LINK_ESTABLISHED_STATE, sme state = 12 systemrole = 3) with reason code 7 from c4:14:3c:29:47:05

03-14 14:20:03.274 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-DISCONNECTED bssid=1c:1d:86:e9:e2:85 reason=15

<3>[86568.199309] wlan: [28055:E :PE ] limProcessDeauthFrame: 144: Received Deauth frame for Addr: 44:a4:2d:52:bc:a5 (mlm state = eLIM_MLM_LINK_ESTABLISHED_STATE, sme state = 12 systemrole = 3) with reason code 15 from 1c:1d:86:e9:e2:85

03-14 13:42:24.354 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-DISCONNECTED bssid=c4:14:3c:29:47:25 reason=2

< 3>[85195.665538] wlan: [28055:E :PE ] limProcessDeauthFrame: 144: Received Deauth frame for Addr: 44:a4:2d:52:bc:a5 (mlm state = eLIM_MLM_LINK_ESTABLISHED_STATE, sme state = 12 systemrole = 3) with reason code 2 from c4:14:3c:29:47:25

9. Roam occurs when the signal difference is 5-10rssi. Roam occurs in the firmware layer and will not be disconnected

03-14 14:19:24.774 I/WifiHAL (28360): event received NL80211_CMD_ROAM, vendor_id = 0x0

03-14 14:19:24.781 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-CONNECTED - Connection to c4:14:3c:29:47:25 completed [id=0 id_str=]

03-14 14:19:30.298 I/WifiHAL (28360): event received NL80211_CMD_ROAM, vendor_id = 0x0

03-14 14:19:30.316 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-CONNECTED - Connection to c4:14:3c:29:47:05 completed [id=0 id_str=]

03-14 14:19:48.681 I/WifiHAL (28360): event received NL80211_CMD_ROAM, vendor_id = 0x0

03-14 14:20:00.162 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-CONNECTED - Connection to 1c:1d:86:e9:e2:85 completed [id=0 id_str=]

10. When auoto join is opened, roam will also occur and will not be disconnected 10

03-14 12:09:32.171 E/WifiStateMachine(28360): WifiStateMachine shouldSwitchNetwork txSuccessRate=0.00 rxSuccessRate=0.00 delta 1000 -> 1000

03-14 12:09:34.505 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-CONNECTED - Connection to 6c:99:89:b0:01:85 completed [id=0 id_str=]

03-14 12:09:55.132 I/wpa_supplicant(28064): wlan0: CTRL-EVENT-DISCONNECTED bssid=6c:99:89:b0:01:85 reason=0

03-14 13:10:51.805 E/WifiStateMachine(28360): WifiStateMachine shouldSwitchNetwork txSuccessRate=0.00 rxSuccessRate=0.00 delta 1000 -> 100

Bash Shell: Check File Exists or Not [How to Do]

How do I test existence of a text file in bash running under Unix like operating systems?

You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:

test -e filename
[ -e filename ]

test -f filename
[ -f filename ]

The following command will tell if a text file called /etc/hosts exists or not usingbash conditional execution:

[ -f /etc/hosts ] && echo "Found" || echo "Not found"

Sample outputs:

Found

The same code can be converted to use withif..else..fiwhich allows to make choice based on the success or failure of a test command:

#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
	echo "$file found."
else
	echo "$file not found."
fi

File test operators

The following operators returns true if file exists:

-b FILE
              FILE exists and is block special

       -c FILE
              FILE exists and is character special

       -d FILE
              FILE exists and is a directory

       -e FILE
              FILE exists

       -f FILE
              FILE exists and is a regular file

       -g FILE
              FILE exists and is set-group-ID

       -G FILE
              FILE exists and is owned by the effective group ID

       -h FILE
              FILE exists and is a symbolic link (same as -L)

       -k FILE
              FILE exists and has its sticky bit set

       -L FILE
              FILE exists and is a symbolic link (same as -h)

       -O FILE
              FILE exists and is owned by the effective user ID

       -p FILE
              FILE exists and is a named pipe

       -r FILE
              FILE exists and read permission is granted

       -s FILE
              FILE exists and has a size greater than zero

       -S FILE
              FILE exists and is a socket

       -t FD  file descriptor FD is opened on a terminal

       -u FILE
              FILE exists and its set-user-ID bit is set

       -w FILE
              FILE exists and write permission is granted

       -x FILE
              FILE exists and execute (or search) permission is granted

(Fig.01: File test operators taken from bash man page)

The syntax is same (seeFile operators (attributes) comparisonsfor more info):

if [ operator FileName ]
then
     echo "FileName - Found, take some action here"
else
   echo "FileName - Not found, take some action here"
fi

Git diff indicates the change of FileMode (old mode 100644, new mode 10075)

In today’s clone code, GIT status shows that a large number of files have been modified, and git diff prompts FileMode to change, as follows:

diff --git a/Android.mk b/Android.mk
old mode 100644
new mode 100755

The original is the change of FileMode. After Chmod, some bits of the file are changed. If we strictly compare the original file with the Chmod file, there is a difference between the two. However, the source code usually only cares about the text content, so the change of Chmod should be ignored. So set the following:

Cut to the root of the source code

git config --add core.filemode false

in this way, all your git libraries will ignore the FileMode change ~

supplement:

When the code is submitted to the warehouse, it is found that the files that have not been changed are prompted to be modified, and many files are prompted to be modified

However, the modified add line and delete line are both 0

So diff it

$ git diff code.c

old mode 100755

new mode 100644

It turns out that the file mode has changed

After thinking about it, maybe someone else submitted it from Mac and I pulled the code on win, which led to the change of file mode

I went to the Internet to see how to modify it

git config core.filemode false

You can also directly modify the FileMode (in the [core] section) field of the config file in the. Git directory of the code warehouse to change it to false

If you want to modify it globally, add the — global option:

git config --global core.filemode false

fileMode:

core.fileMode

If false, the executable bit differences between the index and the

working copy are ignored; useful on broken filesystems like FAT.

See git-update-index(1). True by default.