GithubHelp home page GithubHelp logo

book-index's People

Contributors

lauer3912 avatar

Stargazers

 avatar

Watchers

 avatar

book-index's Issues

前端: What is the meaning of this code (0, function) in javascript

https://stackoverflow.com/questions/40967162/what-is-the-meaning-of-this-code-0-function-in-javascript

在这种特殊情况下,这似乎是多余的,但有时这种方法很有用。 例如,使用 eval:

(function() {
  (0,eval)("var foo = 123"); // indirect call to eval, creates global variable
})();
console.log(foo);            // 123
(function() {
  eval("var bar = 123");     // direct call to eval, creates local variable
})();
console.log(bar);            // ReferenceError

当您想调用方法而不将对象作为 this 值传递时,它也很有用:

var obj = {
  method: function() { return this; }
};
console.log(obj.method() === obj);     // true
console.log((0,obj.method)() === obj); // false

另请注意,根据上下文,它可能是参数分隔符而不是逗号运算符:

console.log(
  function(a, b) {
    return function() { return a; };
  }
  (0, function (arg) { /* ... */ })(this)
); // 0

前端:Vue 如何获取render函数的内容?

import Vue from 'vue'
let jsxHellowWorld = new Vue({
  render: function(h){
    return(
      <div className = "example">
        {msg}
      </div>
    )
  }
})

console.log("===========jsx===========")
console.log(jsxHellowWorld.$options.render);

优秀产品:PostHog 是一个为开发人员构建的开源产品分析平台。自动收集你网站或应用程序上的每个事件,无需向第三方发送数据

https://posthog.com/

PostHog 是一个为开发人员构建的开源产品分析平台。自动收集你网站或应用程序上的每个事件,无需向第三方发送数据。它在用户级别提供基于事件的分析,捕获你产品的使用数据以查看哪些用户在你的应用程序中执行了哪些操作。它会自动捕获点击次数和综合浏览量,以分析你的用户在做什么,而无需手动推送事件

Vue: 检测网站是使用Vue搭建的

// 原理,查找关键字
// 源码参照:https://github.com/vuejs/devtools/blob/main/packages/shell-chrome/src/detector.js
function detect (win) {
  setTimeout(() => {
    // Method 1: Check Nuxt.js
    const nuxtDetected = !!(window.__NUXT__ || window.$nuxt)

    if (nuxtDetected) {
      let Vue

      if (window.$nuxt) {
        Vue = window.$nuxt.$root && window.$nuxt.$root.constructor
      }

      win.postMessage({
        devtoolsEnabled: (/* Vue 2 */ Vue && Vue.config.devtools) ||
          (/* Vue 3.2.14+ */ window.__VUE_DEVTOOLS_GLOBAL_HOOK__ && window.__VUE_DEVTOOLS_GLOBAL_HOOK__.enabled),
        vueDetected: true,
        nuxtDetected: true
      }, '*')

      return
    }

    // Method 2: Check  Vue 3
    const vueDetected = !!(window.__VUE__)
    if (vueDetected) {
      win.postMessage({
        devtoolsEnabled: /* Vue 3.2.14+ */ window.__VUE_DEVTOOLS_GLOBAL_HOOK__ && window.__VUE_DEVTOOLS_GLOBAL_HOOK__.enabled,
        vueDetected: true
      }, '*')

      return
    }

    // Method 3: Scan all elements inside document
    const all = document.querySelectorAll('*')
    let el
    for (let i = 0; i < all.length; i++) {
      if (all[i].__vue__) {
        el = all[i]
        break
      }
    }
    if (el) {
      let Vue = Object.getPrototypeOf(el.__vue__).constructor
      while (Vue.super) {
        Vue = Vue.super
      }
      win.postMessage({
        devtoolsEnabled: Vue.config.devtools,
        vueDetected: true
      }, '*')
    }
  }, 100)
}

快速查找 Vue 的版本

    const all = document.querySelectorAll('*');
    let el;
    for (let i = 0; i < all.length; i++) {
      if (all[i].__vue__) {
        el = all[i];
        break;
      }
    }
    if (el) {
      let Vue = Object.getPrototypeOf(el.__vue__).constructor;
      while (Vue.super) {
        Vue = Vue.super;
      }
      console.log('%c%s', 'color: #00bf00', `Vue version = ${Vue.version}`, Vue);
    }

Rust: 宏 print! ,println! 用法大全

格式化输出

rust中由一些宏(macro)负责输出,这些宏定义在 std::fmt 中,下面是一些常用的宏:

  • format!():向字符串中输出格式化字符串。
    
  • print()!:向标准输出打印字符串。
    
  • println()!:向标准输出打印字符串,同时会打印一个换行符。
    
  • eprint()!:向标准错误打印字符串。
    
  • eprintln()!:向标准错误打印字符串,同时也会打印一个换行符
    

使用{}通配符

  • {} 是基础,参数按顺序填充
  • {n} 替换为第 n 个(0 起始)参数
  • {name} 替换为 name = "value" 的指定参数
println!("{} days", 31);

{}中使用位置参数

  • {} 是基础,参数按顺序填充
  • {n} 替换为第 n 个(0 起始)参数
  • {name} 替换为 name = "value" 的指定参数
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

{}中使用命名参数

  • {} 是基础,参数按顺序填充
  • {n} 替换为第 n 个(0 起始)参数
  • {name} 替换为 name = "value" 的指定参数
println!("{subject} {verb} {object}",
             object="the lazy dog",
             subject="the quick brown fox",
             verb="jumps over");

{}中指定字符串格式化的方式

  • b 是二进制表示
  • o 是八进制数
  • x 是十六进制数(X 是大写的)
  • e 是指数符号(用 E 大写)
// 以二进制的格式打印数字
println!("{} of {:b} people know binary, the other half doesn't", 1, 2);

println!("{:b}", 1234);  // => 10011010010
println!("{:o}", 1234);  // => 2322
println!("{:x}", 1234);  // => 4d2
println!("{:X}", 1234);  // => 4D2
println!("{:e}", 12.34); // => 1.234e1
println!("{:E}", 12.34); // => 1.234E1

{}中指定对齐方式以及对其宽度

  • 在后面指定条件:
  • <n 是 n 位数字和左对齐
  • n 是 n 位数字和右对齐

  • ^ n 是 n 位数字和中心对齐
  • 0n 或 <0n 是“0 填充”

// 右对齐宽度为6
println!("{number:>width$}", number=1, width=6);
// 使用字符0填充对齐的字符串
println!("{number:>0width$}", number=1, width=6);

println!("{0: <8} | {1: >8} | {2: ^8} | {3: <08} | {4: >08} | {hundred: >08}",
         "Left",
         "Right",
         "Center",
         42,
         999,
         hundred=100);
// => Left     |    Right |  Center  | 42000000 | 00000999 | 00000100

占位符{:?}

fmt::Debug的作用是以调试的目的打印字符串
fmt::Debug是Rust标准库已经定义好的,我们可以通过继承的方式,获得fmt::Debug的能力,在格式化中使用占位符{:?}。

#[derive(Debug)]
struct Structure(i32);
println!("Now {:?} will print!", Structure(3));

// 我们可以用稍微优雅的一点的方式打印
println!("{:#?}", Structure(3));
// 構造体の宣言
struct Point {
    x: i32,
    y: i32,
}

// fmt::Display トレイトの実装
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       write!(f, "({}, {})", self.x, self.y)
    }
}

// fmt::Debug トレイトの実装
impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point(x: {}, y: {})", self.x, self.y)
    }
}

let p = Point { x: 1, y: 2 };
println!("{}", p);    // => (1, 2)
println!("{:?} ", p); // => Point(x: 1, y: 2)

前端:Buffer 类型只存在于NodeJS种,原生Javascript中并不含有该类型

参见:https://nodejs.org/dist/latest-v16.x/docs/api/buffer.html

Buffer class is a subclass of JavaScript's Uint8Array class

Buffer objects are used to represent a fixed-length sequence of bytes. Many Node.js APIs support Buffers.

The Buffer class is a subclass of JavaScript's Uint8Array class and extends it with methods that cover additional use cases. Node.js APIs accept plain Uint8Arrays wherever Buffers are supported as well.

While the Buffer class is available within the global scope, it is still recommended to explicitly reference it via an import or require statement.

Rust: 如何获得变量的真实运行类型?

在线演练:https://play.rust-lang.org/

fn print_type_of<T>(_: &T) {
  println!("类型是:{}", unsafe { std::any::type_name::<T>() });
}

fn main() {

    let str = "Hello你好";
    print_type_of(&str);              // 类型是: &str
    print_type_of(&(str.as_bytes())); // 类型是: &[u8]
    println!("---");

    
    let mut vec = Vec::<u8>::new();
    vec.push(1);
    print_type_of(&vec);              // 类型是:alloc::vec::Vec<u8>
    print_type_of(&(vec.as_slice())); // 类型是:&[u8]
    print_type_of(&(vec.to_vec()));   // 类型是:alloc::vec::Vec<u8>
    print_type_of(&(&vec));           // 类型是:&alloc::vec::Vec<u8>  
    print_type_of(&(&*vec));          // 类型是:&[u8] 
    println!("---");
    
    let b = b"some bytes";
    print_type_of(&b);                // 类型是:&[u8; 10]
    
    
}

优秀产品: kubesphere k8s下的Ubuntu

kubesphere

https://github.com/kubesphere/kubesphere

banner

The container platform tailored for Kubernetes multi-cloud, datacenter, and edge management

A+ good first follow on Twitter


What is KubeSphere

English | 中文

KubeSphere is a distributed operating system for cloud-native application management, using Kubernetes as its kernel. It provides a plug-and-play architecture, allowing third-party applications to be seamlessly integrated into its ecosystem. KubeSphere is also a multi-tenant container platform with full-stack automated IT operation and streamlined DevOps workflows. It provides developer-friendly wizard web UI, helping enterprises to build out a more robust and feature-rich platform, which includes most common functionalities needed for enterprise Kubernetes strategy, see Feature List for details.

The following screenshots give a close insight into KubeSphere. Please check What is KubeSphere for further information.

Workbench Project Resources
CI/CD Pipeline App Store

Demo Environment

🎮 Using the account demo1 / Demo123 to log in the demo environment. Please note the account is granted view access.

🖥 You can also have a quick view of Demo video.

Features

🕸 Provisioning Kubernetes Cluster Support deploy Kubernetes on any infrastructure, support online and air-gapped installation, learn more.
🔗 Kubernetes Multi-cluster Management Provide a centralized control plane to manage multiple Kubernetes clusters, support propagate an app to multiple K8s clusters across different cloud providers.
🤖 Kubernetes DevOps Provide out-of-box CI/CD based on Jenkins, and offers automated workflow tools including binary-to-image (B2I) and source-to-image (S2I), learn more.
🔎 Cloud Native Observability Multi-dimensional monitoring, events and auditing logs are supported; multi-tenant log query and collection, alerting and notification are built-in, learn more.
🧩 Service Mesh (Istio-based) Provide fine-grained traffic management, observability and tracing for distributed microservice applications, provides visualization for traffic topology, learn more.
💻 App Store Provide an App Store for Helm-based applications, and offer application lifecycle management on Kubernetes platform, learn more.
💡 Edge Computing Platform KubeSphere integrates KubeEdge to enable users to deploy applications on the edge devices and view logs and monitoring metrics of them on the console, learn more.
📊 Metering and Billing Track resource consumption at different levels on a unified dashboard, which helps you make better-informed decisions on planning and reduce the cost, learn more.
🗃 Support Multiple Storage and Networking Solutions
  • Support GlusterFS, CephRBD, NFS, LocalPV solutions, and provide CSI plugins to consume storage from multiple cloud providers.
  • Provide Load Balancer Implementation OpenELB for Kubernetes in bare-metal, edge, and virtualization.
  • Provides network policy and Pod IP pools management, support Calico, Flannel, Kube-OVN
  • ..
    🏘 Multi-tenancy Provide unified authentication with fine-grained roles and three-tier authorization system, and support AD/LDAP authentication.

    Architecture

    KubeSphere uses a loosely-coupled architecture that separates the frontend from the backend. External systems can access the components of the backend through the REST APIs.

    Architecture


    Latest Release

    🎉 KubeSphere 3.1.1 is now available! See the Release Notes For 3.1.1 for the updates.

    Installation

    KubeSphere can run anywhere from on-premise datacenter to any cloud to edge. In addition, it can be deployed on any version-compatible Kubernetes cluster.

    Quick Start

    1. Run the following commands to install KubeSphere on an exiting Kubernetes cluster:
    kubectl apply -f https://github.com/kubesphere/ks-installer/releases/download/v3.1.1/kubesphere-installer.yaml
       
    kubectl apply -f https://github.com/kubesphere/ks-installer/releases/download/v3.1.1/cluster-configuration.yaml
    1. You can run the following command to view the installation logs. After KubeSphere is successfully installed, you can use http://IP:30880 to access the KubeSphere Console with the default account and password (admin/P@88w0rd).
    kubectl logs -n kubesphere-system $(kubectl get pod -n kubesphere-system -l app=ks-install -o jsonpath='{.items[0].metadata.name}') -f

    👨‍💻 No Kubernetes cluster? Try All-in-one to install a single-node Kubernetes and KubeSphere on your Linux machine.

    KubeSphere for hosted Kubernetes services

    KubeSphere is hosted on the following cloud providers, you can try KubeSphere by one-click installation on their hosted Kubernetes services.

    You can also install KubeSphere on other hosted Kubernetes services within minutes, see the step-by-step guides to get started.

    👨‍💻 No internet access? Refer to the Air-gapped Installation on Kubernetes or Air-gapped Installation on Linux for instructions on how to use private registry to install KubeSphere.

    Contributing, Support, Discussion, and Community

    We ❤️ your contribution. The community walks you through how to get started contributing KubeSphere. The development guide explains how to set up development environment.

    Please submit any KubeSphere bugs, issues, and feature requests to KubeSphere GitHub Issue.

    Who are using KubeSphere

    The user case studies page includes the user list of the project. You can leave a comment to let us know your use case.

    Landscapes



        

    KubeSphere is a member of CNCF and a Kubernetes Conformance Certified platform , which enriches the CNCF CLOUD NATIVE Landscape.

    GitHub: GitHub Gist 是什么?

    https://gist.github.com/

    刚才看博客的时候,发现有位童鞋(@arliang725 )在评论问 gist 是什么。于是我也试着搜索了一下,搜到了一篇译文:

    Github作为代码分享平台在开发者中非常流行。此平台托管了包括游戏、书籍以至于字体在内的一千两百多万个项目(现在更多),这使其成为互联网上最大的代码库。

    Github还提供另一个非常有用的功能,就是Gist。开发人员常常使用Gist记录他们的代码片段,但是Gist不仅仅是为极客和码农开发的,每个人都可以用到它。如果您听说过类似Pastebin或者 Pastie这样的web应用的话,那您就可以看到它们和Gist很像,但是Gist比它们要更优雅。因为这些免费应用一般含有广告,而且带有很多其他杂 七杂八的功能。

    Gist – 任何人都能用得着

    如果您不是极客您可以按照如下方式使用Gist:

    1. 匿名张贴

    您不需要拥有Github账号就可以使用Gist。用浏览器打开http://gist.github.com,在窗口中写下你想说的就可以创建一个Gist。您可以发布一个私密的Gist,也就是说这个Gist将不能被他人搜索到而只对直接在浏览器中输入其URL的人可见。

    1. 能像wiki一样记录历史

    如果您修改了已经发布了的Gist的话,之前的所有版本都将被保存。您可以点击Revisions按钮按时间浏览,而且您可以通过内置的diff引擎查看任意两个版本间的差异。 这也可以用于比较文本文件。

    1. 发布富文本内容

    虽然Gist只能用纯文本来写,但是您可以用markdown来发布html格式的Gist。您可以添加列表、图片(已有图床上的)和表格。当您用markdown的时候不要忘了文件名要以.md为后缀。

    1. 把Gist当作一个写作平台

    虽然现在有很多写作引擎,比如Blogger、Medium、Tumblr,但您还可以用Gist来快速发布您的作品。您可以用纯文本或者markdown等文档标记语言些一个Gist然后用http://roughdraft.io来把它作为一个独立的网页发布。

    1. 托管gist上的单个页面

    Bl.ocks 是一个非常有趣的专为Gist开发的应用。

    您可以用纯文本把HTML、CSS、JavaScript代码写下来以index.html为文件名保存为Gist,然后用http://bl.ocks.org把渲染好的结果在浏览器中展示出来。比如,这个gist展示出来就是这样。

    显然宽带限制是一个问题,但是http://bl.ock.org作为一个通过Gist托管HTML的工具仍然是相当不错的。 当然您也可以用Google Drive。

    1. 制作任务列表

    您可以用Gist跟踪待处理任务(举个栗子)。这是用纯文本的特殊语法写的但是你可以任意勾选。

    • Pick the flowers
    • Call John 9303032332
    • Cancel cable subscription
    • Book the flight tickets

    您可以勾选或者勾去任意选项,源文本将会自动变更。如果您的Gist是公有的的话,任何人都可以看到您的列表,但是只有您(拥有者)可以改变其勾选状态。

    备注:其实任务列表也可以在issue中建立,所有拥有写权限的人都可以uncheck/check。

    1. 把Gist作为一个网页收藏夹

    在Chrome浏览器您可以找到一个叫GistBox的插件,通过这个插件您可以在浏览网页时选择保存网页内容为Gist。您甚至可以添加标注或者话题标签以易于以后更容易找到它们。

    1. 把Gist嵌入网页中

    您用一行js代码就可以把任何一条Gist嵌入到网页中。嵌入的Gist格式不发生任何变化,而且访问者可以非常方便的把它们fork到他们的Github中。要嵌入wordpress的话有这个插件和这个短代码可以使用。

    1. 测量访问量

    您可以使用Google Analytics查看您的Gist的访问量。因为Gist纯文本中不允许运行js代码,所以我们可以用GA Beacon来记录实时访问Gist的情况。
    把如下代码添加到Gist中,用markdown格式保存,这样就在这个Gist中添加了一个透明追踪图像了。
    Analytics

    1. 在桌面端管理Gist

    Gisto是一个能让您在浏览器之外管理Gist的桌面应用。您可以对Gist进行搜索、编辑、查看历史和分享。 此应用可运行于苹果、微软和linux系统。 当然您也可以用GistBox这个web应用替代它。

    您是不是对Gist有了一个全新的认识呢?

    英文:Github Gist Tutorial
    译者:知乎网友章乐,2015/08/30
    链接:http://www.zhihu.com/question/21343711/answer/32023379

    Deno: 读取JSON文件,写入JSON文件,格式化JSON文件

    /**
     * 读取json文件
     *
     * ## 参照文档
     * https://deno.land/[email protected]/examples/read_write_files
     *
     * ## 运行命令
     * ```bash
     * # cli
     * deno run --allow-read --allow-write fmt-json-file.ts
     * ```
     * */
    
    // 引入 lodash 模块,如需要使用 deno.land/x 中的es版本
    import * as _ from 'https://deno.land/x/[email protected]/lodash.js';
    
    console.log('lodash=', Object.keys(_));
    
    /**
     * 读取json文件
     * @param filePath 文件路径
     * @returns 
     */
    export async function readJsonFile(filePath: string): Promise<any> {
      const data = await Deno.readTextFile(filePath);
      return JSON.parse(data);
    }
    
    /**
     * Writes json file
     * @param filePath 
     * @param data
     * @returns json file
     */
    export async function writeJsonFile(filePath: string, data: object): Promise<any> {
      try {
        const dataStr = JSON.stringify(data, null, 2);
        await Deno.writeTextFile(filePath, dataStr);
      } catch (error) {
        throw error;
      }
    }
    
    // 读取原来的数据
    const jsonObj = await readJsonFile("./database.json");
    console.log(jsonObj);
    
    // 写入数据
    _.set(jsonObj, "name", "deno");
    _.set(jsonObj, "age", 18);
    
    await writeJsonFile("./database.json", jsonObj);

    工具:CodeTour(代码之旅)是微软官方开发的 VS Code 扩展,允许记录和回放代码的演练和思路

    简介

    CodeTour 是一个 VS Code 插件,允许记录和回放代码库的演练和思路。我们通常都是通过代码注释或者文档来解释某段代码或方法的功能及逻辑,这样的方法相对简便,但是对阅读的人来说还不够友好,CodeTour 允许我们为代码添加备注,并且将这些备注串联起来,动态地展示我们的思路以及代码逻辑。

    就像一个目录,可以轻松地加入到新的项目/功能,并且可视化错误报告或了解代码审查/PR 更改的上下文。"code tour"只是一系列交互步骤,每个步骤都与特定目录或文件/行进行关联,并包括对相应代码的描述。开发人员可以 clone 一个仓库,然后立即开始学习,而无需参考 CONTRIBUTING.md 文件或依赖他人的帮助。

    https://mp.weixin.qq.com/s/55snlZvRuxD4xS_KZPVZYA

    VSCode 地址:

    https://marketplace.visualstudio.com/items?itemName=vsls-contrib.codetour

    项目地址:

    https://github.com/microsoft/codetour

    Rust: rust中String,&str,Vec <u8>和&[u8]的惯用转换

    &str    -> String--| String::from(s) or s.to_string() or s.to_owned()
    &str    -> &[u8]---| s.as_bytes()
    &str    -> Vec<u8>-| s.as_bytes().to_vec() or s.as_bytes().to_owned()
    String  -> &str----| &s if possible* else s.as_str()
    String  -> &[u8]---| s.as_bytes()
    String  -> Vec<u8>-| s.into_bytes()
    &[u8]   -> &str----| s.to_vec() or s.to_owned()
    &[u8]   -> String--| std::str::from_utf8(s).unwrap(), but don't**
    &[u8]   -> Vec<u8>-| .to_vec()
    Vec<u8> -> &str----| &s if possible* else s.as_slice()
    Vec<u8> -> String--| std::str::from_utf8(&s).unwrap(), but don't**
    Vec<u8> -> &[u8]---| 使用 &*

    前端:开发模式下,浏览器多个标签打开同一网址出错

    目前,在 chrome 上以开发模式 (SPA) 打开超过 3 个标签时,新打开的标签和热重载将不起作用,标签冻结了一段时间,然后显示类似这样的错误

    Uncaught (in promise) Error: Manifest request to /dashboard/_nuxt/1.js timed out.
        at XMLHttpRequest.request.onreadystatechange (runtime.js:92)
    
    import React from 'react';
    import { VueWrapper } from 'vuera';
    import VueVideoComponent from '../../assets/components/video-tpl.vue';
    
    export default () => {
      const videoList = [{src: '/assets/video/errors/dev-server-error-when-opening-more-than-3-tabs-on-chrome.mp4',type: 'mp4'}]
      return (
        <div>
          <VueWrapper component={VueVideoComponent} sourceList={videoList} />
        </div>
      );
    }

    1. 问题引用

    2. 原因

    在开发模式下 Nuxt.js/Next.js 创建 2 个到服务器的持久连接以接收热更新并保持页面处于活动状态。 每个浏览器对一个站点允许拥有的特定服务器的并发连接数都有自己的限制,因此如果您在同一浏览器的多个选项卡中打开同一个 Nuxt.js/Next.js 站点,您可能会超过浏览器的限制。

    更多内容参见:https://tools.ietf.org/html/rfc6202#section-5.1

    5.1. 最大连接数限制
    
    HTTP [RFC2616],第 8.1.4 节,建议单用户客户端
    不与任何服务器或代理保持两个以上的连接,在为了防止服务器过载并避免拥塞网络中的意外副作用。 直到最近,这限制是由最常用的浏览器实现的,因此连接是一种稀缺资源,需要在内部共享浏览器。 请注意,浏览器中可用的 JavaScript API隐藏连接,安全模型禁止共享帧之间的任何资源。 新的 HTTP 规范 [HTTPBIS]消除了两个连接的限制,只鼓励客户端打开多个连接时保守。 事实上,最近浏览器已将此限制增加到 6 或 8 个连接; 然而,它仍然无法发现本地限制和使用多个框架和选项卡仍然可以轻松放置 8 个连接抵达。
    
    Web 应用程序需要限制长轮询请求的数量发起,理想情况下是在之间共享的单个长轮询同一浏览器的框架、选项卡或窗口。 然而,安全浏览器的限制使这种共享变得困难。
    
    服务器的最佳实践是使用 cookie 来检测来自同一浏览器的多个长轮询请求并避免推迟两个请求,因为这可能会导致连接匮乏和/或管道问题。

    3. 可能的解决办法

    • 在开发模式中,不要在同一浏览器中,同时使用多个标签页打开同一个站点。
    • 如果使用 Firefox,您可以通过导航到 about:config 并将 network.http.max-persistent-connections-per-server 设置为更高的数字来增加此限制

    前端:NPM版本控制符^,~,>,||,-的含义详解, https://semver.npmjs.com/

    版本控制符

    对于使用者来说,版本前面的控制符是需要关注的,这决定引用依赖是否与期望相同。
    npm 支持的符号是比较丰富的,下面的版本符号均支持:

    { "dependencies" :
      {
        "foo" : "1.0.0 - 2.9999.9999",// 大于等于1.0.0 小于 2.9999.9999
        "bar" : ">=1.0.2 <2.1.2",     // 比较清晰  左闭右开
        "baz" : ">1.0.2 <=2.3.4",     // 左开右闭
        "boo" : "2.0.1",              // 规定版本  
        "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0", // 表达式也算清晰
        "asd" : "http://asdf.com/asdf.tar.gz"                 // 指定下载地址代替版本
        , "til" : "^1.2.3"                                    // 同一主版本号,不小于1.2.3 即 1.x.y  x>=2 y>=3
        , "elf" : "~1.2.3"                                    // 同一主版本和次版本号 即1.2.x x>= 2
        , "two" : "2.x"                                       // 这个比较形象,x>=0  即2.0.0 以上均可
        , "thr" : "3.3.x"                                    // 同上 x>= 0  即3.3.0 以上
        , "lat" : "latest"                                   // 最新版本
        , "dyl" : "file:../dyl"                              // 从本地下载
      }
    }

    验证网址:https://semver.npmjs.com/

    Rust:Vec 是什么?如何使用 Vec?常用的 Vec 函数

    标准库网址:https://doc.rust-lang.org/std/vec/

    Rust中的狭义的Vec,相当于一些其它语言可变长度的List,ArrayList,Array(Julia语言),是核心的数据结构。

    let vec = vec![1,2,3];
    let vec:Vec<i32> =vec![1,2,3]; //Vec<i32>也可不加,可以推断出来
    // 或
    let data =Vec::new();
    // 或
    let data:Vec<i32> =Vec::new(); //Vec<i32>具体看后面的应用

    如果广义上的vector,分动态数组和固定数组,有必要了解一下:

    let mut vec = vec!["a", "b", "c", "d"];//动态数组
    let mut array = ["a", "b", "c", "d"];//固定数组
    let mut array:[&str4] = ["a", "b", "c", "d"];//固定数组: 
    
    //[&str;4] :其中是分号隔开,4表示这个固定数组的长度,不可变的。
    
    
    两者的相同之处:
    
    assert_eq!(vec, array);//从目前来看,两者的值是相同的;
    
    两者的不同之处:
    
    //array :可以进行元素数不变下操作,包括改变其中值之类;
    //array.insert(3,"e");error:没有insert这个函数
    //array.push("e"); error:没有push这个函数
    // vec: 不限制

    下面,我们有函数是应用在动态数组上的,有些也可以应用在固定数组上的。请留意,并不要搞混了。

    关于相关函数,有空大家可以仔细看了一下官方手册:

    https://doc.rust-lang.org/std/vec/struct.Vec.html

    其相关函数非常多,功能十分强大,能做到活学活用需要一定的时间摸索。

    现在初步COPY了官方手册中主要函数的用法,具体如下:

    is_empty(), len: 判断空,或者获得长度

    let mut v = Vec::new();
    assert!(v.is_empty());
    
    v.push(1);
    assert!(!v.is_empty());
    
    let a = vec![1, 2, 3];
    assert_eq!(a.len(), 3);

    get_mut:

    和HashMap中有所不同,在vec中,get_mut(1)的1是第1个值(从0开始…)

        let x = &mut ["a", "b", "c"];
    
        if let Some(elem) = x.get_mut(1) {
            *elem = "42";
        }
        assert_eq!(x,&["a","42","c"]);

    swap: 交换特定的两个值

    let mut v = ["a", "b", "c", "d"];
    v.swap(1, 3);
    assert!(v == ["a", "d", "c", "b"]);

    reverse:逆序

    let mut v = [1, 2, 3];
    v.reverse();
    assert!(v == [3, 2, 1]);

    iter_mut:循还改值

    let x = &mut [1, 2, 4];
    for elem in x.iter_mut() {
        *elem += 2;
    }
    assert_eq!(x, &[3, 4, 6]);

    windows:有交叉的迭代循环

    let slice = ['r', 'u', 's', 't'];
    let mut iter = slice.windows(2);
    assert_eq!(iter.next().unwrap(), &['r', 'u']);
    assert_eq!(iter.next().unwrap(), &['u', 's']);
    assert_eq!(iter.next().unwrap(), &['s', 't']);
    assert!(iter.next().is_none());
    
    如果
    
    let slice = ['f', 'o', 'o'];
    let mut iter = slice.windows(4);
    assert!(iter.next().is_none());

    chunks:无交叉的迭代循环

    let slice = ['l', 'o', 'r', 'e', 'm'];
    let mut iter = slice.chunks(2);
    assert_eq!(iter.next().unwrap(), &['l', 'o']);
    assert_eq!(iter.next().unwrap(), &['r', 'e']);
    assert_eq!(iter.next().unwrap(), &['m']);
    assert!(iter.next().is_none());
    
    再有:
    let v = &mut [0, 0, 0, 0, 0];
    let mut count = 1;
    
    for chunk in v.chunks_mut(2) {
        for elem in chunk.iter_mut() {
            *elem += count;
        }
        count += 1;
    }
    assert_eq!(v, &[1, 1, 2, 2, 3]);

    split: 把符合条件的做为分隔

    let slice = [10, 40, 33, 20];
    let mut iter = slice.split(|num| num % 3 == 0);
    
    assert_eq!(iter.next().unwrap(), &[10, 40]);
    assert_eq!(iter.next().unwrap(), &[20]);
    assert!(iter.next().is_none());

    contains:包括

    let v = [10, 40, 30];
    assert!(v.contains(&30));
    assert!(!v.contains(&50));

    starts_with,end_with:以…开始(结尾)

    let v = [10, 40, 30];
    assert!(v.starts_with(&[10]));
    assert!(v.starts_with(&[10, 40]));
    assert!(!v.starts_with(&[50]));
    assert!(!v.starts_with(&[10, 50]));
    
    注意:
    
    let v = &[10, 40, 30];
    assert!(v.starts_with(&[]));
    let v: &[u8] = &[];
    assert!(v.starts_with(&[]));

    sort,sort_by,sort_by_key:排序

    let mut v = [-5, 4, 1, -3, 2];
    
    v.sort();
    assert!(v == [-5, -3, 1, 2, 4]);
    
    let mut v = [5, 4, 1, 3, 2];
    v.sort_by(|a, b| a.cmp(b));
    assert!(v == [1, 2, 3, 4, 5]);
    
    // reverse sorting
    v.sort_by(|a, b| b.cmp(a));
    assert!(v == [5, 4, 3, 2, 1]);
    
    let mut v = [-5i32, 4, 1, -3, 2];
    
    v.sort_by_key(|k| k.abs());
    assert!(v == [1, 2, -3, 4, -5]);

    to_vec(),into_vec()

    let s = [10, 40, 30];
    let x = s.to_vec();
    // Here, `s` and `x` can be modified independently.
    
    let s: Box<[i32]> = Box::new([10, 40, 30]);
    let x = s.into_vec();
    // `s` cannot be used anymore because it has been converted into `x`.
    
    assert_eq!(x, vec![10, 40, 30]);

    insert,在相应个序号上insert

    let mut v = vec!["a", "b", "c"];
    v.insert(1, "d");//在第1个序列号上insert 元素"d"
    assert_eq!(v, vec!["a", "d", "b", "c"]);
    // 值相等,再次举例
    assert_eq!(v, ["a", "d", "b", "c"]);

    remove,删除第n个值

    let mut v = vec!["a", "b", "c"];
    assert_eq!(v.remove(1), "b");//删除第1个值(0,1,....)

    retain: 只保留符合条件的值

    let mut vec = vec![1, 2, 3, 4];
    vec.retain(|&x| x%2 == 0);
    assert_eq!(vec, [2, 4]);

    push、pop、append

    // push:对元素的压入操作
    let mut vec = vec![1, 2];
    vec.push(3);
    assert_eq!(vec, [1, 2, 3]);
    
    //pop:对元素的弹出操作,后进先出型
    let mut vec = vec![1, 2, 3];
    assert_eq!(vec.pop(), Some(3));
    assert_eq!(vec, [1, 2]);
    
    // append :两个vec之间
    let mut vec = vec![1, 2, 3];
    let mut vec2 = vec![4, 5, 6];
    vec.append(&mut vec2);
    assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
    assert_eq!(vec2, []);

    drain、clear: 清空

    let mut v = vec![1, 2, 3];
    let u: Vec<_> = v.drain(1..).collect();
    assert_eq!(v, &[1]);
    assert_eq!(u, &[2, 3]);
    
    // drain(..)==clear()
    v.drain(..);
    assert_eq!(v, &[]);
    assert!(v.is_empty());
    
    // clear()
    let mut v = vec![1, 2, 3];
    v.clear();
    assert!(v.is_empty());
    

    truncate :截取前面<n的值

     let mut n =3;
     let mut vec = vec!["a", "b", "c", "d", "e"];
     vec.truncate(n);//取0,1,2序列值
     assert_eq!(vec, ["a", "b", "c"]);
     //如果n>vec.len()-1,则会报错

    extend、extend_from_slice: 扩展

    //extend
    let mut vec = vec![4, 5, 6];
    vec.extend([1, 2, 3].iter().cloned());//[4,5,6,1,2,3]
    vec.sort();
    println!("vec :{:?}", vec); //[1,2,3,4,5,6]
    
    //extend_from_slice
    let mut vec = vec![1];
    vec.extend_from_slice(&[2, 3, 4]);
    assert_eq!(vec, [1, 2, 3, 4]);

    前端:Nodejs是如何引入执行一个C++插件的

    图片

    https://zhuanlan.zhihu.com/p/94682309

    图中我们还发现有下面这么一个结论:为啥我们直接require JSON文件的时候,可以自动转化为一个对象?

    因为模块解析的时候,如果是json后缀的时候,会调用JSON.parse这个方法

    Tips:上图还可以作为面试题《请说说在Nodejs中require一个文件后一个简单流程》的一个简单答案

    我们重点关注到v8里面的DLOpen方法。

    该方法是为了解析node后缀的模块而写,node模块本质是一个动态链接库(windows下后缀是dll,linux下后缀是so),所以你看v8源码下,如果是支持POSIX标准的话,是使用系统APIdlopen()打开即可,如果是非POSIX的话,就只能借助libuv的uv_dlopen方法去打开。

    其次文件打开之后,执行以下几个判断:

    判断模块的初始化函数是否符合标准判断是否是普通的C++插件,如果是的话,看看是否当前的nodejs版本ABI版本是否可以支持加载该模块
    

    最后执行模块的初始化函数

    这里可以看到N-API的模块是不需要判断的,从这里也印证了这句话:

    A given version n of N-API will be available in the major version of Node.js in which it was published, and in all subsequent versions of Node.js, including subsequent major versions.

    前端:阿里云企业级的微前端解决方案

    网址: https://alfajs.io/

    https://github.com/aliyun/alibabacloud-alfa

    Alfa

    介绍

    Alfa 是在阿里云控制台体系中孵化🐣的微前端方案, 定位是面向企业级的微前端体系化解决方案。

    特性

    • 📦 开箱即用,无代码侵入
    • 📎 完善的微前端体系支撑
    • 🕋 完整前端容器沙箱
    • ♋️ 多实例兼容

    使用文档

    子应用

    import { mount }  from '@alicloud/console-os-react-portal';
    import App from './app';
    
    const appID = 'aliyun-console-slb'
    
    export default mount(
      (props) => <App/>,
      document.getElementById('app'),
      appID
    );

    宿主应用

    import Application from '@alicloud/console-os-react-app'
    
    const appConfigUrl = 'http://localhost:7100/aliyun-console-slb.manifest.json';
    
    const Home =  () => (
      <Application
        manifest={appConfigUrl}
        id="aliyun-console-slb"
      />
    );
    export default Home;

    其他框架使用

    React

    see Alfa React Portal

    Vue

    see Alfa Vue Portal

    Try Example

    克隆仓库到本地

    git clone https://github.com/aliyun/alibabacloud-console-os.git
    

    运行 React 子应用

    $ cd example/SubApp/React
    $ yarn install # or npm install
    $ npm run start
    # you will visit app on http://localhost:8080/

    运行 Vue 子应用

    $ cd example/SubApp/Vue
    $ yarn install # or npm install
    $ npm run serve
    # you will visit app on http://localhost:8081/

    运行 宿主 应用

    $ cd example/HostApp/ReactHost
    $ yarn install # or npm install
    $ npm run start
    # you will visit app on http://localhost:3000/

    你可以在 http://localhost:3000/ 访问到当前加载的两个子应用。

    Try Live Demo

    React

    Angular

    Vue

    贡献指南

    参见贡献指南

    Swift: Swift -- __FUNCTION__ ,__FILE__等函数

    OC Swift  
    FILE #file 打印当前文件路径,c字符串
    LINE #line 打印当前行号,整数
    FUNCTION #function 打印当前函数或方法

    我们在使用代码调试中 经常使用print打印函数,有时打印的多了,不好定位到时哪一控制器,哪一行代码,我们今日就是解决这个问题

    获取打印的所在文件
    在Swift中获取 文件的命的函数是 #file 转化成 OC字符串获取

    let file = (#file as NSString).lastPathComponent;
    print("(file)-123");
    获取打印的方法名称 #function函数
    let funcName = #function;
    print("(file):(funcName)--123");
    //打印结果: ViewController.swift:viewDidLoad()--123
    获取代码所在的行数 #line函数
    let file = (#file as NSString).lastPathComponent;
    print("(file):(#line)");
    写一个全局的函数 定义打印

    ///全局函数 T是泛型 传入不同的参数
    func CCLog(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){

    let file = (file as NSString).lastPathComponent;
    

    // 文件名:行数---要打印的信息
    print("(file):((lineNum))--(message)");

    }
    调整在哪一个状态下打印 (Dbug 和Release)
    配置文件.jpg
    定义 全局函数 添加#if DEBUG #endif 判断

    ///全局函数
    func CCLog(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){

    #if DEBUG
    
    let file = (file as NSString).lastPathComponent;
    
    print("\(file):(\(lineNum))--\(message)");
    
    #endif
    

    }

    作者:追逐_chase
    链接:https://www.jianshu.com/p/de222deded93
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    Swift 编译错误: Function declares an opaque return type, but the return statements in its body do not have matching underlying types

    解决方案

    SwiftiUI 提供了一个结构体 AnyView 来表示任意一个 View 实例,和 Any 一样可以用来抹除具体的类型。
    假设我们有一个页面展示用户的信息,如果没有用户没有登录我们就展示一个登录按钮。根据状态不同,一个 View 可能会返回不同实例类型的 View:

    struct UserInfoView: View {
        
        @State var isLogin = false
        
        var body: some View {
            if isLogin {
                return Text("Logined”)
            } else {
                return Button(action: {
                    // 去登录
                }, label: {
                    return Text("Login")
                })
            }
        }
    }

    那么上面的代码能不能被编译通过呢?
    直觉上我们认为返回的只要是实现了 View 协议的都能满足,应该能编译通过。不过实际上这样写会编译器会提供一个错误:

    Function declares an opaque return type, but the return statements in its body do not have matching underlying types

    问题就出在前面的关键字 some 上。加了 some 后协议透明,**编译器在编译时推断具体代码的实际返回类型,因此要求必须只能有一个确定的类型。**具体关于 some 我在之前的博客 Swift 5.1 新特性:透明类型关键字 some 有介绍过。
    上面的例子中用户已登录时返回 Text,没登录返回 Button 类型。不是同一种类型,编译器因此抛出错误。为了解决这个问题我们很自然想到用一个通用的类型把所有的 View 都包起来,这样编译器可以编译通过。反正运行的时候是 View 就可以了。这就是 AnyView 的使用场景了,抹掉具体 View 类型,对外有一个统一的类型,上面的代码这样改一下就可以了:

        var body: some View {
            if isLogin {
                return AnyView(
                    Text("User logined")
                )
            } else {
                return AnyView(
                    Button(action: {
                        // 去登录
                    }, label: {
                        return Text("Login")
                    })
                )
            }
        }

    重点说明:AnyView() 要这样使用

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.