Tag Archives: html

Net Q & A: how to avoid the exception thrown by max() on emptyenumerable?

Consultation area

Naor:

I have the following query:


int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                          .Max(x => x.ShoeSize);

If workers. Where (x = & gt; x. Companyid = = 8) if no workers are found, the above code will throw an exception.

Now the idea is: query can return 0 if it can't be found, but don't throw an exception. How can I modify the query above?

Answer area

Ron K.:

You can use the extension method of IEnumerable defaultifempty() to avoid this embarrassment. Refer to the following code.


    class Program
    {
        static void Main(string[] args)
        {
            List<Worker> Workers = new List<Worker>()
            {
                new Worker(){ CompanyId=1, CompanyName="tweet", ShoeSize=10 },
                new Worker(){ CompanyId=2, CompanyName="google", ShoeSize=20 },
            };

            int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                          .Select(x => x.ShoeSize)
                          .DefaultIfEmpty(0)
                          .Max();

            Debug.WriteLine($"maxShoeSize={maxShoeSize}");
        }

    }

    class Worker
    {
        public int CompanyId { get; set; }

        public string CompanyName { get; set; }

        public int ShoeSize { get; set; }
    }

Output results:


maxShoeSize=0

Of course, the above 0 is not necessary. You can change it to any other number.

CptRobby:

Although the plan provided by the man upstairs can work normally, it doesn't look very eye-catching. It can be transformed into the following one.


    int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                             .Select(x => (int?)x.ShoeSize)
                              .Max() ?? 0;

Does the code look a little lengthy?The best way is to customize a extension method , as shown in the following code:


public static int MaxOrDefault<T>(this IQueryable<T> source, Expression<Func<T, int?>> selector, int nullValue = 0)
{
    return source.Max(selector) ?? nullValue;
}

For simplicity, this extension only deals with the int type. You can change it to any type, such as: (long, double,...), and then you can continue to reform the caller.


int maxShoeSize = Workers.Where(x => x.CompanyId == 8).MaxOrDefault(x => x.ShoeSize);

I hope my answer can help more people.

Comment area

Xiaobian never dares to do Max on the empty collection , after all, it's not once or twice, so every time we judge whether there is a value in the collection in advance, and then execute Max , we didn't expect that there are magic extension methods defaultifempty and empty type that can help us to do it, and we all forget about sensory science????????????.

Nginx realizes the same background service for portal and business

The first stage: modify the initial path access in the framework

The default access address was modified. Because I was not familiar with the configuration of the framework at that time, and there was no architecture related documentation, the attempt failed. Although the modification is completed, you can directly access the home page of the portal according to the domain name, but the back-end business can’t be accessed normally. I doubt that I have changed something. If you are familiar with ruoyi architecture and have completed this modification method, please give me more advice.

The second stage: using nginx to separate the front and back of the portal

The portal page of the website uses static HTML pages, and then the data request is implemented through Ajax. Configure two domain names to resolve to the server where the service is located, the first level domain name to access the portal related functions, and the second level domain name to access the background management page. Two schemes are prepared. One is to simply use HTML and Ajax. First, nginx forwards the request to the HTML page according to the domain name, and then uses Ajax to get the data from the background when the page is initialized. The second is to use Vue, which is actually an optimization on the first one. Through the loop contained in Vue and other tags, it is easy to load and echo the data, but When the page is loaded, the unresolved Vue variables will be displayed first. The experience is very poor, so this method is abandoned. I think the efficiency and page rendering experience of the first method will be very poor, so in the case of other implementation methods, I will not consider this method for the moment. In fact, these two methods can achieve basic requirements such as data loading.

The third stage: directly using the page of the original project

At the beginning, I didn’t think of this method, but later when I modified the second method, I suddenly thought that according to the previous project experience, I can do redirection jump in nginx, so I began to try this way. The basic idea is: configure two servers in nginx to monitor port 80, and judge which server to enter according to the domain name. When the access is a first-class domain name, judge the website related business, that is, judge whether the URL contains only the domain name. If it contains only the domain name, then redirect the request to the path of the portal home page. For other requests, handle them normally .

No more nonsense. Go directly to nginx configuration

server {
	listen 80;
	server_name ywgl.*****.com;
	index index.html;
	set $ht_server 127.0.0.1:8080;
	
	location /{
		proxy_pass_header Server;
		proxy_set_header Host $http_host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Scheme $scheme;
		proxy_pass http://$ht_server;

	}
  
}
server {
	listen 80;
	server_name www.******.com;
	index index.html;
	set $mh_server 127.0.0.1:8888;


	location /{
		
		proxy_pass_header Server;
		proxy_set_header Host $http_host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Scheme $scheme;
		
		if ($request_uri ~* "^/$") {
			rewrite ^/(.*)$ http://www.******.com/home/index?; # Preventing multiple redirects
		}
		proxy_pass http://$mh_server ;
	}


        
}

explain:

$request_ Uri ~ * “^/$” this condition is to determine whether the access request is www. * * *. Com, not www. * * *. COM/*/*, because even if the access request is www. * * *. Com, nginx will send a $request_ What URI gets will still contain a ‘/’.

Finally, if you have any ideas, welcome to exchange.

Vue error: error matching template:

The error information is as follows:

the above situation is generally caused by the following conditions:

{% verbatim%} {% endverbatim%} there are unclosed tags or redundant tags (such as div unclosed) in the range of tags bound by the UE instance el. After finding, delete or complete some tag statements cannot be bound by {{MSG}}, but by V-model. For example, input and textarea need to be bound with V-model,

[Error] because it violates the following Content Security Policy directive

[Error] because it violates the following Content Security Policy directive

In the process of HTML development, we encountered the following error, which means the permission problem of HTML meta setting

Refused to connect to 'blob:http://localhost:8080/6d57f07f-3c2f-49ca-be30-fd0b7f4cff6e' 
because it violates the following Content Security Policy directive: 
"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: content: ". 
Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Specifically, this bug appears when using vue-html2pdf.
The screenshot is as follows

the last time I encountered a similar problem was when I used the video tag.
These are similar problems

You need to open the source code of the HTML page (for example, index.html ), modify the meta in the head section

  <meta http-equiv="Content-Security-Policy" content="default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: content: https://ssl.gstatic.com; 
    media-src * blob: 'self' http://* 'unsafe-inline' 'unsafe-eval'; 
    style-src * 'self' 'unsafe-inline'; 
    img-src * 'self' data: content:; 
    connect-src * blob:;">

The example is divided into multiple lines and can be modified according to your own needs. For example, IMG SRC allows * and other types of resources.
Connect SRC allows * blob: and other types of resources. Note that * does not contain the blob: type. If it is not declared, blob: may be wrong

reference material

Used to connect to XXX – because it violates the following content security policy
Cordova rejected to connect to xxxxx - white list refuses to send network requests
meta tag official website: https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/meta
Content security policy website: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Security-Policy__ by_ cnvoid

How to increase the effect of onchange event after adding readonly attribute to input tag and display time of laydate plug-in

Trial and error: It is not possible to bind the onChange event to the input tag directly in HTML and JS.
Reason: ReadOnly is read-only, and onChange events respond to value changes. However, the actual onChange event is only valid for the interface input value. Modified values through DOM objects are invalid.
Use onblur instead. Onblur events are triggered when an object loses focus. The measured effect can occasionally start, occasionally fail.
Solution 2: Given that the input box renders the event with layDate, in the done function on layDate, assign the input box to the selected value that needs to be executed during the execution of the onChange event.
Solution # 2 Perfect the problem.
Note: When searching the web, be careful to combine your own scene. For example, the input box has been rendered with laydate, which is equivalent to an event. Therefore, we should consider whether we can achieve our requirements in this event.
 
 

Cross origin requests are only supported for

In this paper, the scene
When writing HTML using VS Code, the imported JS file needs to import modules across domains.
why
Use File protocol, need to use HTTP, Data, Chrome-Extension, Edge, HTTPS and other protocols, commonly speaking is the need to use the server to open a port.
The solution
Right click directly in VS Code and select Open with Live Server.

Datatable plug-in error: uncaught typeerror: cannot read property ‘style’ of undefined

DataTable plug-in: Uncaught TypeError: Cannot read property ‘style’ of undefined
DataTable plug-in: Uncaught TypeError: Cannot read property ‘style’ of undefined
The number of columns defined in the table does not match the number of entries in the aoColumns table
Page presentation (7 columns)

Return data (6 columns)

Ueditor paste word image and upload image file automatically

Tinymce is a very good rich text editor, you can go to the website to download. https://www.tiny.cloud
Here is the source code of PowerPaste, a paid plug-in on its official website, but it does not affect the use of functionality.

umeditor+粘贴word图片


Take Vue as an example:
Install Tinymce under static directory instead of NPM.
PowerPaste is put in the \static\tinymce\plugins directory


Introducing tinymce.min.js in index.html.


Code parameter configuration is shown in the figure below:


Replace paste in plugins with powerpaste and you’re done.
The final effect, can automatically batch upload all the images in Word

After the picture is uploaded, the image address in the editor is changed to the image address of the server.

Invalidation of margin top property of nested box in CSS style box

When we write CSS styles, when two boxes are nested together, the top of the inside box is placed on the top of the outside box, as shown in the figure below:

At this time, if the properties like margin-top are set for the inner box, there will be no space between the top of the inner box and the outer box, but the outer box is pushed down, as if margin-top property is set for the outer box.
set margin-top property for the inner box, as shown in the figure below:

<style>
* {
    margin: 0;
    padding: 0;
}
.wrap {
    width: 200px;
    height: 200px;
    background-color: red;
}
.wrap .box {
    width: 100px;
    height: 100px;
    background-color: blue;
    margin-top: 50px;
}
</style>
<body>
    <div class="wrap">
        <div class="box"></div>
    </div>
</body>


so the simplest way is to add a property to the outer box :

overflow: hidden;

The results are as follows:

Traversing the background data to generate tree structure

var getTree=function(treeData,parentId){
var treeArr=[];
for(var i=0; i< treeData.length; i++){
var node=treeData[i];
if(node.sjchannelcode==parentId ){
var newNode={order:node.order,code:node.channelcode,url:node.url,name:node.name,sjchannelcode:node.sjchannelcode,channelcode:getTree(treeData,node.channelcode)};
treeArr.push(newNode);
}
}
return treeArr;
}
// call tree method
var treeArr=getTree(data,sj);
data is the data returned from the background, sj root directory returned by the node parent id

Practice — CSS3 — frame animation to achieve special effects

Practice ING – Frame animation to achieve special effects
Recently, I wrote another requirement, which used a lot of CSS3 animation, but it is still very deep to go into each attribute of CSS3 animation carefully. Here, I will write down the understanding of the steps attribute of frame animation
We know that CSS3 Animation has eight attributes
animation-name
animation-duration
animation-delay
animation-iteration-count
animation-direction
animation-play-state
animation-fill-mode
animation-timing-function
Most 1-7 are introduced, but the animation-timing function is an attribute that controls the time
In addition to the three Bessel curves commonly used, there is the confusing steps() function
By default, the animation ease the transition. It inserts a tween between each key frame, so the animation is coherent
In addition to ease, transition functions such as Linear, Cubic – Bezier will insert the tween for it. However, some effects do not require tween, but only a jump between key frames, where steps should be used
Understand the steps
The Steps function specifies a step function
The first parameter specifies the number of intervals in the time function (must be positive integers)
The second parameter, which is optional, accepts both start and end values, specifying a step change at the start or end point of each interval, which defaults to end.
Step -start is equal to steps(1,start). The animation is divided into 1 step. The part that starts the left endpoint when the animation is executed is the beginning.
Step-end is the same as steps(1,end) : the animation is divided into steps, and the animation is executed starting with the end endpoint, with the default value of end.
Look at the W3C specification
The wrong understanding of the first parameter of steps:
Steps (5, start)
The first parameter “number” of steps() is the specified number of intervals, that is, the animation is divided into N-step phased display, which is estimated to be the number of changes written for keyframes by most people
A look at the cSS2 frame animation I wrote also gave me a good understanding of cSS3 animation
@-webkit-keyframes circle {
0% {}
25%{}
50%{}
75%{}
100%{}
}

I also wrote a js, please refer to