Category Archives: Coder

Laravel 8: How to Use command to create custom files

1. First create a command file with the make: command command command

php artisan make:command ServicesCommand

2. A servicescommand file will be generated under app\console\commands

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

// GeneratorCommand
class ServicesCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $name = 'make:service'; 

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new service';

    /**
     * The console command type.
     */
    protected $type = 'service'; 


    // The template that the generated file depends on can be set by yourself
    // I put the files here in the same level as the Stubs directory
    protected function getStub()
    {
        return __DIR__.'/Stubs/CreateService.stub';
    }

    // Namespaces to be used in the template
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Services';
    }
}

3. Create stubs\createservice Stub file

<?php

namespace {{ namespace }};

class {{ class }}
{
  // You can add the required code yourself      
}

4. Testing

// Check if the command
php artisan list

// Create Test
php artisan make:service TestService

5. Other

In the lower version, the class needs to be registered in the commands attribute of commands \ kernel.

protected $commands = [
  ServicesCommand::class,      
];

C# WinForm: How to Generate two bit random number

Just copy it directly
#region Generate a 2-digit random number
public double NextDouble(Random ran, double minValue, double maxValue, int decimalPlace)
{
double randNum = ran.NextDouble() * (maxValue – minValue) + minValue;
return Convert.ToDouble(randNum.ToString(“f” + decimalPlace));
}
#endregion

Example: Take a random number directly from 70-90 each time
Random ran = new Random();
NextDouble(ran,70,90,2);

[Modified] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0

Error reporting reason:

From is not preceded by a space

An extra space is added after row

After looking for the error for a long time, I thought it was an environmental problem or a problem with the POM. As a result, I was careless. Now I don’t know why the first from added a space less. Why would I report an error

If you encounter this problem, in addition to the methods given online, you can take a look at your own code

The first line is the wrong codes:
"select * from" +"(select * ,ROW_NUMBER() over(partition by windowEnd order by cnt desc)as row_num" +"from agg)" +"where row _num <= 5");

"select * from " +"(select * ,ROW_NUMBER() over (partition by windowEnd order by cnt desc) as row_num" +" from agg) " +" where row_num <= 5 ");


[Solved] Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘custom.property.hello’ in value “${custom.property.hello}” config

Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘scopedTarget.configController’: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘custom.property.hello’ in value “${custom.property.hello}”
The JsonProperySourceLocator class in the spring cloud config source code swap is wrongly written to get the value
Modify get value to get key

OO ALV: How to realize red box positioning of field error

On the ALV page, some custom fields need to report errors during verification, and the red box is located to the error field. For the error reported in the red box, class CL_ GUI_ ALV_ Set in Grid_ ERROR_ The cells method can be implemented, however, this method is protected, so the implementation needs to be rewritten in the program.

Specific implementation:

1. Rewrite set_ERROR_Cells method

Definition.

1 CLASS lcl_gui_alv_grid DEFINITION INHERITING FROM cl_gui_alv_grid.
2 
3     PUBLIC SECTION.
4         METHODS:
5             m_set_error_cells IMPORTING it_err TYPE lvc_t_err.
6 ENDCLASS.

Implement

1 CLASS lcl_gui_alv_grid IMPLEMENTION.
2     METHOD m_set_error_cells.
3         CALL_METHOD me->set_error_cells
4             EXPORTING
5                 cell_table     = it_err.
6     ENDMETHOD.
7 ENDCLASS.

2. Save the row and column IDs of the fields that need to report errors to the internal table.

1 DATA:gt_err TYPE lvc_t_err,
2          gs_err TYPE lvc_s_err.
3 
4 gs_err-row_id = &1.
5 gs_err-row_id = &2.
6 APPEND gs_err TO gt_err.
7 CLEAR:gs_err.

3. When the PbO is refreshed, the method is called

1 IF gt_err IS NOT INITIAL.
2     CALL METHOD go_alv_grid->m_set_error_cells
3         EXPORTING
4             it_err = gt_err.
5 ENDIF.

[GuzzleHttp\Exception\RequestException] cURL error 60: SSL certificate problem: certificate has expired (How to Solve)

How to Solve Error: [GuzzleHttp\Exception\RequestException] cURL error 60: SSL certificate problem: certificate has expired

This problem is because there is a ROOT root certificate expired
Usually it will be automatically updated with the package
But the DST Root CA X3 that let's encrypt uses this time is out of date



# DST Root CA X3
-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow
PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD
Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O
rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq
OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b
xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw
7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD
aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV
HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG
SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69
ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr
AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz
R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5
JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo
Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
-----END CERTIFICATE-----

Because our systems are all unified CentOS8,

Then remember to restart PHP FPM after the update is complete, otherwise the certificate file will not be reloaded

C++ write and read file via fstream in ios::out,ios::in,ios::app mode

#include <iostream>
#include <uuid/uuid.h>
#include <ostream>
#include <istream>
#include <fstream>
#include <iostream>

using namespace std;

void retrieveUuid(char *uuidValue);
void writeFile2();
void readFile3();

int main()
{
    writeFile2(); 
    readFile3();
    return 0;
}

void readFile3()
{
    fstream wFile;
    wFile.open("log3.txt",ios::app|ios::in|ios::out);
    if(!wFile.is_open())
    {
        cout<<"Create or open log3.txt failed!"<<endl;
    }

    string uuidValue;
    int num=0;
    while(getline(wFile,uuidValue))
    { 
        cout<<"Id="<<++num<<",value="<<uuidValue<<endl;
    } 
    wFile.close();
    printf("Finished!\n");
}

void writeFile2()
{
    fstream wFile;
    wFile.open("log3.txt",ios::app|ios::out|ios::in);
    if(!wFile.is_open())
    {
        cout<<"Create or open log3.txt failed!"<<endl;
    }

    char *uuidValue=(char*)malloc(40);
    for(int i=0;i<10000;i++)
    {
        retrieveUuid(uuidValue);
        wFile<<uuidValue<<endl;
    }
    free(uuidValue);   
    wFile.close(); 
}

void retrieveUuid(char *uuidValue)
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID,uuidValue);
}

Complile and run

g++ -g -std=c++2a h2.cpp -o h2 -luuid

Run the ./h2 command
./h2

HDFS Active Namenode synchronizes editlog process to journalnode

FSEditLog

For the classes used in the active namenode process, execute logsync() to synchronize the latest editlog segment to the journalnode

Call procedure

FSEditLog.logSync(long mytxid)
->EditLogOutputStream.flush()
->EditLogOutputStream.flush(boolean durable)
->EditLogOutputStream.flushAndSync(boolean durable)
->JournalSet.flushAndSync(boolean durable)
->JournalSet.mapJournalsAndReportErrors(
      JournalClosure closure, String status)

The final calling function of this procedure is in the journalset

/**
   * Apply the given operation across all of the journal managers, disabling
   * any for which the closure throws an IOException.
   * @param closure {@link JournalClosure} object encapsulating the operation.
   * @param status message used for logging errors (e.g. "opening journal")
   * @throws IOException If the operation fails on all the journals.
   */
  private void mapJournalsAndReportErrors(
      JournalClosure closure, String status) throws IOException{

    List<JournalAndStream> badJAS = Lists.newLinkedList();
    for (JournalAndStream jas : journals) {
      try {
        closure.apply(jas);
      } catch (Throwable t) {
        if (jas.isRequired()) {
          final String msg = "Error: " + status + " failed for required journal ("
            + jas + ")";
          LOG.fatal(msg, t);
          // If we fail on *any* of the required journals, then we must not
          // continue on any of the other journals. Abort them to ensure that
          // retry behavior doesn't allow them to keep going in any way.
          abortAllJournals();
          // the current policy is to shutdown the NN on errors to shared edits
          // dir. There are many code paths to shared edits failures - syncs,
          // roll of edits etc. All of them go through this common function 
          // where the isRequired() check is made. Applying exit policy here 
          // to catch all code paths.
          terminate(1, msg);
        } else {
          LOG.error("Error: " + status + " failed for (journal " + jas + ")", t);
          badJAS.add(jas);          
        }
      }
    }
    disableAndReportErrorOnJournals(badJAS);
    if (!NameNodeResourcePolicy.areResourcesAvailable(journals,
        minimumRedundantJournals)) {
      String message = status + " failed for too many journals";
      LOG.error("Error: " + message);
      throw new IOException(message);
    }
  }

In mapjournalsandreporterrors, if the number of successful journals does not reach minimumredundantjournals, namenode will actively shut down.

Git ignore rule (.Gitignore configuration) does not Wrok [How to Fix]

The first method

.gitignore indicates the files under the ignored file directory. When git pushes, they will also appear in the pushed directory, or use git status to view the status. The files you want to ignore will still display the tracked status.

The reason is that in the GIT ignore directory, new files will be cached in GIT. If some files have been included in version management, even if the ignore path has been declared in .Gitignore, it will not work,

At this time, we should delete the local cache first, and then commit git, so that there will be no ignored files.

Solution: git clears the local cache (changes to untrack state), and then commits:

[root@kevin ~]# git rm -r --cached .
[root@kevin ~]# git add .
[root@kevin ~]# git commit -m 'update .gitignore'
[root@kevin ~]# git push -u origin master

Special attention should be paid to:

1) .gitignore can only ignore files that have not been tracked. If some files have been included in version management, modifying. Gitignore is invalid.

2) If you want .Gitignore to work, you must make sure that these files are not in the staging area .Gitignore only ignores files that are not staged (cached),

For files that have been staged, the ignore file must be removed from the staged file before it can be ignored.

To remove a file from the staging area, use the command

use "git restore <file>..." to discard changes in working directory

Second method: (recommended)

Manually set in the warehouse under each clone. Do not check the changes of specific files.

[root@kevin ~]# git update-index --assume-unchanged PATH         //Enter the files to be ignored in the PATH

[Solved] Exception in thread “main” javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

The project needs to use java to call the third-party HTTPS interface. After debugging many times, it always reports javax.net.ssl.sslhandshakeexception: received fatal Alert: handshake_Failure error, Huangtian pays off his hard work. Finally, the debugging is successful. I don’t talk much nonsense and go directly to the code (my code is relatively complete, which is also convenient for me to check how to use it in the future);

public static String signature(String comeStr) throws Exception {
	SSLContext sc = createIgnoreVerifySSL();
	String serverURL = "https://xxx";
	StringBuffer sbf = new StringBuffer();
	String strRead = null;
	URL url = new URL(serverURL);
	HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
	connection.setSSLSocketFactory(sc.getSocketFactory());
	connection.setRequestMethod("POST");// post
	connection.setDoInput(true);
	connection.setDoOutput(true);
	// The parameters inside the header are set here connection.setRequestProperty("Jian, "value");
	connection.setRequestProperty("Accept", "application/json");// set the format of the received data
	connection.setRequestProperty("Content-Type", "application/json");
	connection.connect();
	OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
	// The body parameter is put into the JSONObject here
	JSONObject outParm = new JSONObject(jsonBuild());//need to convert the json data
	writer.write(outParm.toString());
	writer.flush();
	InputStream is = connection.getInputStream();
	BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	while ((strRead = reader.readLine()) != null) {
		sbf.append(strRead);
		// sbf.append("\r\n");
	}
	String jsonStr = sbf.toString().replace("\"", "'");
	reader.close();
	connection.disconnect();
	JSONObject inParm = new JSONObject(jsonStr);
	String results = (String) inParm.get("pdf");
	return results;
}
/**
 * Get SSL socket object Key point: set the version of tls protocol
 * @return
 */
public static SSLContext createIgnoreVerifySSL() {
	SSLContext sc = null;
	try {
          //Draw the point: here is extremely important need to correspond to each other's TLS version, version is not much online search a search, put in one by one to try (most of the use of TLSv1.2 version)
		sc = SSLContext.getInstance("TLSv1.2");// specify the TLS version
	} catch (NoSuchAlgorithmException e) {
		System.out.println("Failed to create a socket!");
		e.printStackTrace();
	}
	SSLSessionContext sslsc = sc.getServerSessionContext();
	sslsc.setSessionTimeout(0);
	// Implement the X509TrustManager interface for bypassing authentication
	X509TrustManager trustManager = new X509TrustManager() {
		@Override
		public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
				String paramString) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
				String paramString) throws CertificateException {
		}

		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};
	try {
		sc.init(null, new TrustManager[] { trustManager }, null);
	} catch (KeyManagementException e) {
		System.out.println("Failed to initialize the socket!");
		e.printStackTrace();
	}
	return sc;
}