问:
How to get the url for a video saved in temporary directory
I need to save a video file to a temp directory and save the reference to it URL. Currently I have tried using fileManager to create a temp directory and then createFile(atPath: tempDirString, contents: vidData, attributes: nil). But I dont/am not able to save the full reference to the file.

What I have tried:

PHCachingImageManager().requestAVAsset(forVideo: (cell?.assetPH)!, options: nil) { (avAsset, _, _) in
    if let avAsset = avAsset {
        print(avAsset, " the avasset?")
        // vidAVAsset = avAsset

        let avPlayerItem = AVPlayerItem(asset: avAsset)
        let avPlayer = AVPlayer(playerItem: avPlayerItem)
        print(avPlayer, "<-- good?")

        let finalURL = self.urlOfCurrentlyPlayingInPlayer(player: avPlayer)
        print(finalURL, "<-- finalURL YEAH EYAHY YEAH?!?!?")
        // newUserTakenVideo.videoURL = finalURL

        let url = self.addVidToTempURL(vidURL: finalURL!)
        newUserTakenVideo.videoURL = url
        // let newUserTakenVideo = SelectedMedia(videoURL: finalURL, phAsset: (cell?.assetPH)!, thumbnailImg: (cell?.imageView.image)!, uniqueCellID: indexPath)
        // GlobalSharedData.shared.arrayOfCurrentCreateMedia.append(newUserTakenVideo)
    } else {
        print("did noot work")
    }
}
```
<p>This is the function called:</p>
<pre class="lang-swift prettyprint-override"><code>func addVidToTempURL(vidURL: URL) -> URL? {
    let fileManager = FileManager.default
    let tempDir = fileManager.temporaryDirectory
    let tempDirString = tempDir.path
    do {
        print( "tempDir: \(tempDir)" )
        print( "tempDirString: \(tempDirString)" )
        if fileManager.fileExists(atPath: tempDirString ) {
            print( "tempDir exists" )
            do {
                try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
                print( "tempDir created" )
                if fileManager.fileExists(atPath: tempDirString ) {
                    print( "tempDir exists" )
                    let vidData = try Data(contentsOf: vidURL)
                    fileManager.createFile(atPath: tempDirString, contents: vidData, attributes: nil)
                    print(tempDirString, " the stringfsdsda")
                    // fileManager.urls(for: fileManager.temporaryDirectory, in: fileManager.)
                    let url = URL(string: tempDirString)
                    return url
                } else {
                    print( "tempDir STILL DOES NOT exist" )
                    return nil
                }
            } catch {
                print( "tempDir NOT created" )
                return nil
            }
        } else {
            print( "tempDir DOES NOT exist" )
            do {
                try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
                print( "tempDir created" )
                if fileManager.fileExists(atPath: tempDirString ) {
                    print( "tempDir exists" )
                    let vidData = try Data(contentsOf: vidURL)
                    fileManager.createFile(atPath: tempDirString, contents: vidData, attributes: nil)
                    print(tempDirString, " the fsdfdsdfsdfsfsd")
                    let url = URL(string: tempDirString)
                    return url
                } else {
                    print( "tempDir STILL DOES NOT exist" )
                    return nil
                }
            } catch {
                print( "tempDir NOT created" )
                return nil
            }
        }
    }
}
</code>```

How can I get a URL reference to this files location?

I appreciate any help and can add more information if needed. Thanks, me

答:
Since you don't seem to want your file to be visible to users or persisted between app launches, the Temporary directory sounds perfectly fine for your use case:

```<code>var tempVideoFileUrl: URL {
    return FileManager.default.temporaryDirectory.appendingPathComponent("my_video_name")
}

func storeVideoToTemporaryFolder(videoData: Data) {
    guard !FileManager.default.fileExists(atPath: tempVideoFileUrl.path) else {
        return
    }
    do {
        try videoData.write(to: tempVideoFileUrl)
    }
    catch {
        fatalError()
    }
}

func loadVideoFromTemporaryFolder() -> Data? {
    if let data = try? Data(contentsOf: tempVideoFileUrl) {
        return data
    }
    return nil
}
</code>```

Worth mentioning though, the system may (and most likely will) purge this directory after the app is exited. It's recommended that you remove any temporary directories/files after they're no longer needed.

So in your case, you can simply remove it once you finished uploading to Firebase Storage:

```<code>func deleteVideoFromTemporaryFolder() {
    do {
        try FileManager.default.removeItem(at: videoFileUrl)
    }
    catch {
        fatalError()
    }
}
</code>```

If you prefer to keep your file around between app launches though, you could use Application Support directory. But since Application Support and Documents directories gets automatically backed up, you may want to exclude your file from iCloud backup by setting its URL's isExcludedFromBackupKey key:

```<code>var applicationSupportVideoFileUrl: URL {
    let applicationSupportFolderUrl = try! FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    return applicationSupportFolderUrl.appendingPathComponent("my_video_name")
}

func excludeFromCloudBackup(url: URL) {
    var targetUrl = url
    var isAlreadyExcludedFromBackup: Bool
    do {
        let storedRessourceValues = try targetUrl.resourceValues(forKeys: [URLResourceKey.isExcludedFromBackupKey])
        isAlreadyExcludedFromBackup = storedRessourceValues.isExcludedFromBackup ?? false
    }
    catch {
        fatalError()
    }
    guard !isAlreadyExcludedFromBackup else {
        return
    }
    var ressourceValues = URLResourceValues()
    ressourceValues.isExcludedFromBackup = true
    do {
        try targetUrl.setResourceValues(ressourceValues)
    }
    catch {
        fatalError()
    }
}
</code>```

Edit: To get the data from your PHAsset, this should work:

```<code>import Photos

func loadVideoData(phAsset: PHAsset, completion: @escaping (Data?)->()) {
    guard phAsset.mediaType == .video else {
        return completion(nil)
    }
    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true
    options.deliveryMode = .highQualityFormat
    PHCachingImageManager().requestAVAsset(forVideo: phAsset, options: options) { (avAsset, _, _) in
        guard let avUrlAsset = avAsset as? AVURLAsset else {
            return
        }
        var videoData: Data?
        do {
            videoData = try Data(contentsOf: avUrlAsset.url)
        } catch {
            fatalError()
        }
        DispatchQueue.main.async {
            completion(videoData)
        }
    }
}
</code>```

Then simply call this method and store your video in the Temporary folder:

```<code>loadVideoData(phAsset: yourPhAsset) { [weak self] videoData in
    guard let strongSelf = self else { return }
    guard let videoData = videoData else {
        return
    }
    strongSelf.storeVideoToTemporaryFolder(videoData: videoData)
}
</code>```

Body:
I need to save a video file to a temp directory and save the reference to it URL. Currently I have tried using fileManager to create a temp directory and then createFile(atPath: tempDirString, contents: vidData, attributes: nil). But I dont/am not able to save the full reference to the file.

What I have tried:

PHCachingImageManager().requestAVAsset(forVideo: (cell?.assetPH)!, options: nil) { (avAsset, _, _) in
    if let avAsset = avAsset {
        print(avAsset, " the avasset?")
        // vidAVAsset = avAsset

        let avPlayerItem = AVPlayerItem(asset: avAsset)
        let avPlayer = AVPlayer(playerItem: avPlayerItem)
        print(avPlayer, "<-- good?")

        let finalURL = self.urlOfCurrentlyPlayingInPlayer(player: avPlayer)
        print(finalURL, "<-- finalURL YEAH EYAHY YEAH?!?!?")
        // newUserTakenVideo.videoURL = finalURL

        let url = self.addVidToTempURL(vidURL: finalURL!)
        newUserTakenVideo.videoURL = url
        // let newUserTakenVideo = SelectedMedia(videoURL: finalURL, phAsset: (cell?.assetPH)!, thumbnailImg: (cell?.imageView.image)!, uniqueCellID: indexPath)
        // GlobalSharedData.shared.arrayOfCurrentCreateMedia.append(newUserTakenVideo)
    } else {
        print("did noot work")
    }
}

This is the function called:

func addVidToTempURL(vidURL: URL) -> URL? {
    let fileManager = FileManager.default
    let tempDir = fileManager.temporaryDirectory
    let tempDirString = tempDir.path
    do {
        print( "tempDir: \(tempDir)" )
        print( "tempDirString: \(tempDirString)" )
        if fileManager.fileExists(atPath: tempDirString ) {
            print( "tempDir exists" )
            do {
                try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
                print( "tempDir created" )
                if fileManager.fileExists(atPath: tempDirString ) {
                    print( "tempDir exists" )
                    let vidData = try Data(contentsOf: vidURL)
                    fileManager.createFile(atPath: tempDirString, contents: vidData, attributes: nil)
                    print(tempDirString, " the stringfsdsda")
                    // fileManager.urls(for: fileManager.temporaryDirectory, in: fileManager.)
                    let url = URL(string: tempDirString)
                    return url
                } else {
                    print( "tempDir STILL DOES NOT exist" )
                    return nil
                }
            } catch {
                print( "tempDir NOT created" )
                return nil
            }
        } else {
            print( "tempDir DOES NOT exist" )
            do {
                try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
                print( "tempDir created" )
                if fileManager.fileExists(atPath: tempDirString ) {
                    print( "tempDir exists" )
                    let vidData = try Data(contentsOf: vidURL)
                    fileManager.createFile(atPath: tempDirString, contents: vidData, attributes: nil)
                    print(tempDirString, " the fsdfdsdfsdfsfsd")
                    let url = URL(string: tempDirString)
                    return url
                } else {
                    print( "tempDir STILL DOES NOT exist" )
                    return nil
                }
            } catch {
                print( "tempDir NOT created" )
                return nil
            }
        }
    }
}

How can I get a URL reference to this files location?

I appreciate any help and can add more information if needed. Thanks, me

Body:
Since you don't seem to want your file to be visible to users or persisted between app launches, the Temporary directory sounds perfectly fine for your use case:

var tempVideoFileUrl: URL {
    return FileManager.default.temporaryDirectory.appendingPathComponent("my_video_name")
}

func storeVideoToTemporaryFolder(videoData: Data) {
    guard !FileManager.default.fileExists(atPath: tempVideoFileUrl.path) else {
        return
    }
    do {
        try videoData.write(to: tempVideoFileUrl)
    }
    catch {
        fatalError()
    }
}

func loadVideoFromTemporaryFolder() -> Data? {
    if let data = try? Data(contentsOf: tempVideoFileUrl) {
        return data
    }
    return nil
}

Worth mentioning though, the system may (and most likely will) purge this directory after the app is exited. It's recommended that you remove any temporary directories/files after they're no longer needed.

So in your case, you can simply remove it once you finished uploading to Firebase Storage:

func deleteVideoFromTemporaryFolder() {
    do {
        try FileManager.default.removeItem(at: videoFileUrl)
    }
    catch {
        fatalError()
    }
}

If you prefer to keep your file around between app launches though, you could use Application Support directory. But since Application Support and Documents directories gets automatically backed up, you may want to exclude your file from iCloud backup by setting its URL's isExcludedFromBackupKey key:

var applicationSupportVideoFileUrl: URL {
    let applicationSupportFolderUrl = try! FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    return applicationSupportFolderUrl.appendingPathComponent("my_video_name")
}

func excludeFromCloudBackup(url: URL) {
    var targetUrl = url
    var isAlreadyExcludedFromBackup: Bool
    do {
        let storedRessourceValues = try targetUrl.resourceValues(forKeys: [URLResourceKey.isExcludedFromBackupKey])
        isAlreadyExcludedFromBackup = storedRessourceValues.isExcludedFromBackup ?? false
    }
    catch {
        fatalError()
    }
    guard !isAlreadyExcludedFromBackup else {
        return
    }
    var ressourceValues = URLResourceValues()
    ressourceValues.isExcludedFromBackup = true
    do {
        try targetUrl.setResourceValues(ressourceValues)
    }
    catch {
        fatalError()
    }
}

Edit: To get the data from your PHAsset, this should work:

import Photos

func loadVideoData(phAsset: PHAsset, completion: @escaping (Data?)->()) {
    guard phAsset.mediaType == .video else {
        return completion(nil)
    }
    let options = PHVideoRequestOptions()
    options.isNetworkAccessAllowed = true
    options.deliveryMode = .highQualityFormat
    PHCachingImageManager().requestAVAsset(forVideo: phAsset, options: options) { (avAsset, _, _) in
        guard let avUrlAsset = avAsset as? AVURLAsset else {
            return
        }
        var videoData: Data?
        do {
            videoData = try Data(contentsOf: avUrlAsset.url)
        } catch {
            fatalError()
        }
        DispatchQueue.main.async {
            completion(videoData)
        }
    }
}

Then simply call this method and store your video in the Temporary folder:

loadVideoData(phAsset: yourPhAsset) { [weak self] videoData in
    guard let strongSelf = self else { return }
    guard let videoData = videoData else {
        return
    }
    strongSelf.storeVideoToTemporaryFolder(videoData: videoData)
}


来源: stackexchange

问:
How do I resolve `The following packages have unmet dependencies`
I was using this script to install basic software, but had to interrupt because of slow internet speed.
Now when I hit $ sudo apt-get install npm , I get following error

```<code>yask123@yaskslaptop:~$ sudo apt-get installed npm
E: Invalid operation installed
yask123@yaskslaptop:~$ sudo apt-get install npm
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
       Depends: node-ansi-color-table but it is not going to be installed
       Depends: node-archy but it is not going to be installed
       Depends: node-block-stream but it is not going to be installed
       Depends: node-fstream (>= 0.1.22) but it is not going to be installed
       Depends: node-fstream-ignore but it is not going to be installed
       Depends: node-github-url-from-git but it is not going to be installed
       Depends: node-glob (>= 3.1.21) but it is not going to be installed
       Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
       Depends: node-inherits but it is not going to be installed
       Depends: node-ini (>= 1.1.0) but it is not going to be installed
       Depends: node-lockfile but it is not going to be installed
       Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
       Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
       Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
       Depends: node-gyp (>= 0.10.9) but it is not going to be installed
       Depends: node-nopt (>= 3.0.1) but it is not going to be installed
       Depends: node-npmlog but it is not going to be installed
       Depends: node-once but it is not going to be installed
       Depends: node-osenv but it is not going to be installed
       Depends: node-read but it is not going to be installed
       Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
       Depends: node-request (>= 2.25.0) but it is not going to be installed
       Depends: node-retry but it is not going to be installed
       Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
       Depends: node-semver (>= 2.1.0) but it is not going to be installed
       Depends: node-sha but it is not going to be installed
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-underscore but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

答:
I tried lots of method but below work like charm....

After this command run these :-

```<code>curl -sL https://deb.nodesource.com/setup_14.x 565 | sudo -E bash -
sudo apt-get install -y nodejs
</code>```

Now check…

```<code>node -v
npm -v
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was using this script to install basic software, but had to interrupt because of slow internet speed.
Now when I hit $ sudo apt-get install npm , I get following error

yask123@yaskslaptop:~$ sudo apt-get installed npm
E: Invalid operation installed
yask123@yaskslaptop:~$ sudo apt-get install npm
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 npm : Depends: nodejs but it is not going to be installed
       Depends: node-abbrev (>= 1.0.4) but it is not going to be installed
       Depends: node-ansi (>= 0.3.0-2) but it is not going to be installed
       Depends: node-ansi-color-table but it is not going to be installed
       Depends: node-archy but it is not going to be installed
       Depends: node-block-stream but it is not going to be installed
       Depends: node-fstream (>= 0.1.22) but it is not going to be installed
       Depends: node-fstream-ignore but it is not going to be installed
       Depends: node-github-url-from-git but it is not going to be installed
       Depends: node-glob (>= 3.1.21) but it is not going to be installed
       Depends: node-graceful-fs (>= 2.0.0) but it is not going to be installed
       Depends: node-inherits but it is not going to be installed
       Depends: node-ini (>= 1.1.0) but it is not going to be installed
       Depends: node-lockfile but it is not going to be installed
       Depends: node-lru-cache (>= 2.3.0) but it is not going to be installed
       Depends: node-minimatch (>= 0.2.11) but it is not going to be installed
       Depends: node-mkdirp (>= 0.3.3) but it is not going to be installed
       Depends: node-gyp (>= 0.10.9) but it is not going to be installed
       Depends: node-nopt (>= 3.0.1) but it is not going to be installed
       Depends: node-npmlog but it is not going to be installed
       Depends: node-once but it is not going to be installed
       Depends: node-osenv but it is not going to be installed
       Depends: node-read but it is not going to be installed
       Depends: node-read-package-json (>= 1.1.0) but it is not going to be installed
       Depends: node-request (>= 2.25.0) but it is not going to be installed
       Depends: node-retry but it is not going to be installed
       Depends: node-rimraf (>= 2.2.2) but it is not going to be installed
       Depends: node-semver (>= 2.1.0) but it is not going to be installed
       Depends: node-sha but it is not going to be installed
       Depends: node-slide but it is not going to be installed
       Depends: node-tar (>= 0.1.18) but it is not going to be installed
       Depends: node-underscore but it is not going to be installed
       Depends: node-which but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Body:
I tried lots of method but below work like charm....

After this command run these :-

curl -sL https://deb.nodesource.com/setup_14.x 565 | sudo -E bash -
sudo apt-get install -y nodejs

Now check…

node -v
npm -v


问:
Create remote that is not HEAD-less but does not have a master branch
I am new to git and was following the following excellent instruction from Missing Semester. About 1 hour in, they discuss remotes. I went through the process of creating a remote (as a sub-directory for testing), however, I purposefully deviated from the instructions because that helps my understanding. I pushed a branch to the remote but did not name it "master". I eventually realized there was no HEAD in this remote, and things just didn't work right. I looked at the git remote set-head command, and thought that would solve the problem. I don't think it did. What eventually worked was creating a branch called "master" on the remote, and HEAD automatically pointed to it. I did not see this requirement in the documentation. Is there a way to have a repository without a branch named "master"? Alternatively, if there is no branch named "master", how does one get the HEAD pointing to a branch after the remote is created?</p>

答:
TL;DR: you need to reach into the server (somehow—the how depends on the server) and have the server's Git set its HEAD.  (Note that GitHub have a clicky web button interface for this, under settings and then branches.)

Usually, though, you just start by having the server create its first branch having the name master, after which everything works the way everyone expects.  Note that if a server Git already has a branch named br1, you can clone that server Git repository with:

git clone -b br1 url

on your client side, followed by:

```<code>git push origin br1:master
</code>```

to ask that server to create the name master, pointing to the same commit as your own br1 in your clone.  Now the server does have a master and all is back to normal.

Long: what, exactly, is going on here?

Every Git repository has a HEAD

All Git repositories have a HEAD.  This is a basic requirement of Git: when Git goes to look for a repository, it makes several sanity checks on each directory it inspects.  The directory must:

exist as a directory;

contain a file or symlink named HEAD that appears valid;

have a refs/ sub-directory; and

have an objects/ sub-directory (unless overridden by setting GIT_OBJECTS_DIRECTORY in the environment).

Failing any one of these tests makes Git move on to the next candidate for a repository directory, or, if it has run out of candidates, give up and declare that there is no Git repository to be found.

The code that does this checking is in setup.c.  The is_valid_ref test is elsewhere (path.c) and basically tests whether HEAD is a symbolic link to refs/*, or starts with the literal ASCII text ref: refs/, or contains a valid hash ID.  The first two tests are the same as testing whether a reference is a symbolic ref (see the git symbolic-ref command).

A HEAD file that contains a commit hash ID is a detached HEAD.  This indicates that the Git repository is not on a branch at all.  There is little more to be said about this (until we get to cloning, below, anyway).  To set a detached HEAD in a repository in which you can run Git commands directly, use git switch --detach or git checkout --detach or git checkout with any argument that automatically causes a detached HEAD condition, i.e., any reference to a commit that is not literally a branch name.

(There is no way to set a detached HEAD with the GitHub web interface.)

A symbolic reference can be made to a reference that does not exist.  This is how a fresh, empty Git repository, with no branches, can be on branch master even though branch master does not yet exist.  Hence, the branch to which HEAD links, if HEAD is not detached, may or may not actually exist—but there definitely will be a HEAD.

A new, totally-empty repository, created by git init, has a symbolic HEAD that refers to the name master.

(There is no way to set a HEAD reference to a branch that does not exist with the GitHub web interface, as far as I can tell.  But a new repository is still created with HEAD symbolically referring to master.)

Remotes

Note that a remote is just a string in your own local Git repository.  That is, you might create the name origin to hold the url https://github.com/user/project.git or ssh://git@bitbucket.com/user/project.git or some such.

Nothing you do with your local repository will change anything in some other Git over on GitHub or Bitbucket, so any tweaks you make here have no effect.  You need to cause the Git over at GitHub, or Bitbucket, or whatever other site actually hosts the server, to do something to its Git repository, before any change you make will actually have any effect.

(For GitHub, you simply log in to GitHub and manipulate your repositories using their web pages.  This lets you do exactly those things they allow you to do, which is less than everything you could do if you could log in to their servers.)

Cloning: the other repository recommends a checkout

When you clone a repository using:

```<code>git clone [<options>] <url>
</code>```

the options allow you to specify, among other things:

What to call the other Git: the name of the remote.  Use -o xyzzy to change the name from the default origin to xyzzy, for instance.

What branch name to check out in step six (see below).  For instance, git clone -b plugh tells your Git to git checkout plugh in step six.

If you leave out the -b option, your Git asks their Git which branch they recommend.  Your Git will, in general, then attempt to git checkout this branch name in step six.

The method and details behind this recommendation have changed over time.  In the distant past, your Git read their Git's HEAD hash ID, if they supplied one, and guessed which branch name that meant.  In modern Git, their Git can supply the literal text string read from the symbolic HEAD reference.  Your Git can choose to use this, or ignore it.

The git clone command is shorthand for a six-step process:

Run mkdir (or whatever your computer's command may be) to create a new, empty directory, in which the new Git repository will be created.  The remaining five steps run in this new empty directory.

Run git init to create a Git repository (a .git sub-directory within the new directory).

Run git remote add to add a remote.  The name of the remote will be origin unless you used the -o option.  The URL for the remote will be the URL you gave to git clone.

Run any extra git config commands required, e.g., from -c options.

Run git fetch origin (or whatever remote name you used), to obtain commits and populate your repository with remote-tracking names like origin/master based on whatever branch names exist in the other repository.

Run git checkout (pre-2.23) or git switch -c (Git 2.23 or later), to create a new branch and check out its commit.

The branch name used in step six is the one from your -b option.  Your Git will look at their branch (and tag!) names and if your -b option matches one of their branch or tag names, will use that name.  If the name is a tag name, your Git will go into detached HEAD mode on the appropriate commit.

If you did not use -b, your Git will ask their Git which branch they recommend, as described above.  If that is a name that works, your Git will create that name and check out that commit.

If both of those fail, your Git will fall back on the name master.  If that name also fails, your Git will tell you that step six failed: that you have a valid repository, and you got it all cloned, but there is no current branch and commit.  It will be up to you to rectify this situation.

If the repository you clone has no master

Suppose you clone a repository from some URL, and that repository:

does have commits; and

does have branches—let's say, without loss of generality, that they have br1 and br2, for instance; but

does not have a branch named master.

Suppose further that you, on your git clone line, did not supply a -b option.  Then:

In step 5, your git fetch obtained their br1 and br2 names and made your origin/br1 and origin/br2 names.  Since they have no master, your Git did not make an origin/master.

In step 6, you did not supply -b, so your Git asks their Git which branch they recommend.

If you have not taken any special action, the branch they'll recommend is the one whose symbolic name is in their HEAD.  If that symbolic name is master, they will recommend their master—which of course does not exist.  Your Git will be puzzled by this recommendation (it doesn't work) and will use its own built in fallback: try master.  This too will not work and you will see what you saw.

Of course, if they do have a branch named master, your step 5 will have created your origin/master so your step 6 will be able to create your own master based on their origin/master, and all will be well.

If you have them change their symbolic name HEAD to point to their br2 branch, the recommendation you will get in step 6 will be that your Git should create a branch named br2 based off their br2, which is now (via step 5) your origin/br2, and that will all work well too.  But you need to reach into the server somehow and get them to change their recommendation.

Body:
TL;DR: you need to reach into the server (somehow—the how depends on the server) and have the server's Git set its HEAD.  (Note that GitHub have a clicky web button interface for this, under settings and then branches.)

Usually, though, you just start by having the server create its first branch having the name master, after which everything works the way everyone expects.  Note that if a server Git already has a branch named br1, you can clone that server Git repository with:

git clone -b br1 url

on your client side, followed by:

git push origin br1:master

to ask that server to create the name master, pointing to the same commit as your own br1 in your clone.  Now the server does have a master and all is back to normal.

Long: what, exactly, is going on here?

Every Git repository has a HEAD

All Git repositories have a HEAD.  This is a basic requirement of Git: when Git goes to look for a repository, it makes several sanity checks on each directory it inspects.  The directory must:

exist as a directory;

contain a file or symlink named HEAD that appears valid;

have a refs/ sub-directory; and

have an objects/ sub-directory (unless overridden by setting GIT_OBJECTS_DIRECTORY in the environment).

Failing any one of these tests makes Git move on to the next candidate for a repository directory, or, if it has run out of candidates, give up and declare that there is no Git repository to be found.

The code that does this checking is in setup.c.  The is_valid_ref test is elsewhere (path.c) and basically tests whether HEAD is a symbolic link to refs/*, or starts with the literal ASCII text ref: refs/, or contains a valid hash ID.  The first two tests are the same as testing whether a reference is a symbolic ref (see the git symbolic-ref command).

A HEAD file that contains a commit hash ID is a detached HEAD.  This indicates that the Git repository is not on a branch at all.  There is little more to be said about this (until we get to cloning, below, anyway).  To set a detached HEAD in a repository in which you can run Git commands directly, use git switch --detach or git checkout --detach or git checkout with any argument that automatically causes a detached HEAD condition, i.e., any reference to a commit that is not literally a branch name.

(There is no way to set a detached HEAD with the GitHub web interface.)

A symbolic reference can be made to a reference that does not exist.  This is how a fresh, empty Git repository, with no branches, can be on branch master even though branch master does not yet exist.  Hence, the branch to which HEAD links, if HEAD is not detached, may or may not actually exist—but there definitely will be a HEAD.

A new, totally-empty repository, created by git init, has a symbolic HEAD that refers to the name master.

(There is no way to set a HEAD reference to a branch that does not exist with the GitHub web interface, as far as I can tell.  But a new repository is still created with HEAD symbolically referring to master.)

Remotes

Note that a remote is just a string in your own local Git repository.  That is, you might create the name origin to hold the url https://github.com/user/project.git or ssh://git@bitbucket.com/user/project.git or some such.

Nothing you do with your local repository will change anything in some other Git over on GitHub or Bitbucket, so any tweaks you make here have no effect.  You need to cause the Git over at GitHub, or Bitbucket, or whatever other site actually hosts the server, to do something to its Git repository, before any change you make will actually have any effect.

(For GitHub, you simply log in to GitHub and manipulate your repositories using their web pages.  This lets you do exactly those things they allow you to do, which is less than everything you could do if you could log in to their servers.)

Cloning: the other repository recommends a checkout

When you clone a repository using:

git clone [<options>] <url>

the options allow you to specify, among other things:

What to call the other Git: the name of the remote.  Use -o xyzzy to change the name from the default origin to xyzzy, for instance.

What branch name to check out in step six (see below).  For instance, git clone -b plugh tells your Git to git checkout plugh in step six.

If you leave out the -b option, your Git asks their Git which branch they recommend.  Your Git will, in general, then attempt to git checkout this branch name in step six.

The method and details behind this recommendation have changed over time.  In the distant past, your Git read their Git's HEAD hash ID, if they supplied one, and guessed which branch name that meant.  In modern Git, their Git can supply the literal text string read from the symbolic HEAD reference.  Your Git can choose to use this, or ignore it.

The git clone command is shorthand for a six-step process:

Run mkdir (or whatever your computer's command may be) to create a new, empty directory, in which the new Git repository will be created.  The remaining five steps run in this new empty directory.

Run git init to create a Git repository (a .git sub-directory within the new directory).

Run git remote add to add a remote.  The name of the remote will be origin unless you used the -o option.  The URL for the remote will be the URL you gave to git clone.

Run any extra git config commands required, e.g., from -c options.

Run git fetch origin (or whatever remote name you used), to obtain commits and populate your repository with remote-tracking names like origin/master based on whatever branch names exist in the other repository.

Run git checkout (pre-2.23) or git switch -c (Git 2.23 or later), to create a new branch and check out its commit.

The branch name used in step six is the one from your -b option.  Your Git will look at their branch (and tag!) names and if your -b option matches one of their branch or tag names, will use that name.  If the name is a tag name, your Git will go into detached HEAD mode on the appropriate commit.

If you did not use -b, your Git will ask their Git which branch they recommend, as described above.  If that is a name that works, your Git will create that name and check out that commit.

If both of those fail, your Git will fall back on the name master.  If that name also fails, your Git will tell you that step six failed: that you have a valid repository, and you got it all cloned, but there is no current branch and commit.  It will be up to you to rectify this situation.

If the repository you clone has no master

Suppose you clone a repository from some URL, and that repository:

does have commits; and

does have branches—let's say, without loss of generality, that they have br1 and br2, for instance; but

does not have a branch named master.

Suppose further that you, on your git clone line, did not supply a -b option.  Then:

In step 5, your git fetch obtained their br1 and br2 names and made your origin/br1 and origin/br2 names.  Since they have no master, your Git did not make an origin/master.

In step 6, you did not supply -b, so your Git asks their Git which branch they recommend.

If you have not taken any special action, the branch they'll recommend is the one whose symbolic name is in their HEAD.  If that symbolic name is master, they will recommend their master—which of course does not exist.  Your Git will be puzzled by this recommendation (it doesn't work) and will use its own built in fallback: try master.  This too will not work and you will see what you saw.

Of course, if they do have a branch named master, your step 5 will have created your origin/master so your step 6 will be able to create your own master based on their origin/master, and all will be well.

If you have them change their symbolic name HEAD to point to their br2 branch, the recommendation you will get in step 6 will be that your Git should create a branch named br2 based off their br2, which is now (via step 5) your origin/br2, and that will all work well too.  But you need to reach into the server somehow and get them to change their recommendation.


问:
Typescript infer that field is truthy(cannot be undefined), without user-defined type guards
```<code>type Item = {
    left?: { photoSrc: string };
};

type ItemRequired = {
    left: { photoSrc: string };
};

const item: Item = {} as any;

if (item.left) {
    const itemRequired: ItemRequired = item; // fails. Typescript still says left may be undefined
    // I'd like Typescript to know that field left is truthy
}
</code>```

I know about user-defined type guards. E.g.

```<code>function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}
</code>```

My questions:

Why is Typescript unable to infer that left cannot be undefined?

Does that mean I need to create a type guard function for every variation of a type I need to check? Isn't there a simpler way? E.g. I expect when inside the scope of an if check that proves that left field cannot be undefined, I expect Typescript to know that.

This seems like a very common case, but I couldn't find the answer, please excuse me if there is one.

答:
To answer your questions:

I'm presuming because Typescript is here making a comparison between the two types: Item and ItemRequired, rather than what you'd like, which is { left:{ photoSrc:string } }.

Typescript can often figure out what part of union types your using without type guards, but it's not yet quite perfect. It's situational as to which will and won't work, there are a great deals of possible situations.

A lot of the time people want to get away without type guards, and that's understandable as often it seems like additional, unnecessary code. But it's really designed for this exact situation:

const itemIsItemRequired = (item: Item): item is ItemRequired =>
  item.left !== undefined;

if (itemIsItemRequired(item)) {
    const itemRequired: ItemRequired = item; // this works
}
```

Body:
type Item = {
    left?: { photoSrc: string };
};

type ItemRequired = {
    left: { photoSrc: string };
};

const item: Item = {} as any;

if (item.left) {
    const itemRequired: ItemRequired = item; // fails. Typescript still says left may be undefined
    // I'd like Typescript to know that field left is truthy
}

I know about user-defined type guards. E.g.

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

My questions:

Why is Typescript unable to infer that left cannot be undefined?

Does that mean I need to create a type guard function for every variation of a type I need to check? Isn't there a simpler way? E.g. I expect when inside the scope of an if check that proves that left field cannot be undefined, I expect Typescript to know that.

This seems like a very common case, but I couldn't find the answer, please excuse me if there is one.


问:
Can't Install dart on macOS Catalina 10.15.4
I want to install dart language with brew in my MacBook Pro. My MacBook OS details is - macOS Catalina 10.15.4. But It's throw an error. Could you please some one help me out ?

I followed the below steps from here - https://dart.dev/get-dart

```<code>brew tap dart-lang/dart
brew install dart
</code>```

Then I got this error message from terminal

```<code>Updating Homebrew...
==> Installing dart from dart-lang/dart
==> Downloading https://storage.googleapis.com/dart-archive/channels/stable/release/2.8.2/sdk/dartsdk-macos-x64-release.zip
-=O=-       ###
curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to storage.googleapis.com:443
Error: Failed to download resource "dart"
Download failed: https://storage.googleapis.com/dart-archive/channels/stable/release/2.8.2/sdk/dartsdk-macos-x64-release.zip
</code>```

答: Have you tried installing using a VPN? As storage.googleapis site is down in Bangladesh for over a month.</p>

Body:
I want to install dart language with brew in my MacBook Pro. My MacBook OS details is - macOS Catalina 10.15.4. But It's throw an error. Could you please some one help me out ?

I followed the below steps from here - https://dart.dev/get-dart

brew tap dart-lang/dart
brew install dart

Then I got this error message from terminal

Updating Homebrew...
==> Installing dart from dart-lang/dart
==> Downloading https://storage.googleapis.com/dart-archive/channels/stable/release/2.8.2/sdk/dartsdk-macos-x64-release.zip
-=O=-       ###
curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to storage.googleapis.com:443
Error: Failed to download resource "dart"
Download failed: https://storage.googleapis.com/dart-archive/channels/stable/release/2.8.2/sdk/dartsdk-macos-x64-release.zip


问:
Nodejs Use a middleware inside another
I'm having some problems using 2 middlewares inside the same function, already tried to search for all internet and didn't find a useful solution.

validator file

```<code>module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, next);

    return res.status(500).json({ message: 'middleware 2'});
},
</code>```

}

routes file

```<code>routes.post('/user', UserValidator.Create ,UserController.create);
</code>```

The celebrate lib filters some basic validations like string lenght, null values, etc. And the celebrate() function returns another function with the (req, res, next) params.

When the celebrate returns the validation error, it stills continues to execute the code, so it tries to execute the next return and I get an error because the return has already been sent.

When using separate middlewares in the routes, it works normally:

```<code>routes.post('/user', celebrate(...), middleware2 ,UserController.create);
</code>```

I also tried this way but the same thing happens, but now without an error, just returning the middleware2 result.

```<code>module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, () => {
        return res.status(500).json({ message: 'middleware 2'});
    });
},
</code>```

Is there a way to fix this?

答:
u should try this structure </p>

```<code>// API
app.post('/something', Middleware.validate, Controller.create)

//Middleware
const validate = (req, res, done) => {
  const errorArray = []
  const body = req.body

  // identifier is required, Validating as String, and length range.
  if (!_.isString(body.identifier) || body.identifier.length < 2 || body.identifier.length > 10) {
    errorArray.push({
      field: 'identifier',
      error: 70000,
      message: 'Please provide only valid \'identifier\' as string, length must be between 2 and 10.'
    })
  }

  if (!_.isEmpty(errorArray)) {
    return errorArray
  }

  done()
}

module.exports = {
  validate
}

// Controller

const create = function (req, res) {
  return // your functionality
}
module.exports = {
  create
}

</code>```

Title: Nodejs Use a middleware inside another

Body:
I'm having some problems using 2 middlewares inside the same function, already tried to search for all internet and didn't find a useful solution.

validator file

module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, next);

    return res.status(500).json({ message: 'middleware 2'});
},

}

routes file

routes.post('/user', UserValidator.Create ,UserController.create);

The celebrate lib filters some basic validations like string lenght, null values, etc. And the celebrate() function returns another function with the (req, res, next) params.

When the celebrate returns the validation error, it stills continues to execute the code, so it tries to execute the next return and I get an error because the return has already been sent.

When using separate middlewares in the routes, it works normally:

routes.post('/user', celebrate(...), middleware2 ,UserController.create);

I also tried this way but the same thing happens, but now without an error, just returning the middleware2 result.

module.exports = {

create: async (req, res, next) => {
    await celebrate(options.create)(req, res, () => {
        return res.status(500).json({ message: 'middleware 2'});
    });
},

Is there a way to fix this?

Body:
u should try this structure

// API
app.post('/something', Middleware.validate, Controller.create)

//Middleware
const validate = (req, res, done) => {
  const errorArray = []
  const body = req.body

  // identifier is required, Validating as String, and length range.
  if (!_.isString(body.identifier) || body.identifier.length < 2 || body.identifier.length > 10) {
    errorArray.push({
      field: 'identifier',
      error: 70000,
      message: 'Please provide only valid \'identifier\' as string, length must be between 2 and 10.'
    })
  }

  if (!_.isEmpty(errorArray)) {
    return errorArray
  }

  done()
}

module.exports = {
  validate
}

// Controller

const create = function (req, res) {
  return // your functionality
}
module.exports = {
  create
}


问:
Jquery limit checkbox selection doesn't work
I have big complex form, there can be similar checkboxes with the same class or even name. So I need that some of them would restricted from checking more then once. I found good examples how to do that but none of them worked for me. Can someone take a look and say what I'am doing wrong thanks. When pushing green button script generates similar form so i need that checkbox pagrindines would be allowed to select once through all generated forms if there is selected no more can be in other places ofcourse would be great that deselect and changing in another checkbox work.

$('#skaicius').val(2);
$(document).ready(function(){
 $('#duomenys').submit(function(){
  $('#skaicius').val($('.fieldGroup').length*1+1);
 })
    //papildomu pareigu limitas
    var maxGroup = 10;
    //$('#skaicius').val(2);
    //papildomu pareigu pridejimas
    $(".prideti").click(function(){
        if($('body').find('.fieldGroup').length < maxGroup){
            var fieldHTML = '
'+$(".fieldGroupCopy").html()+'
';
            $('body').find('.fieldGroup:last').after(fieldHTML);

        }else{
            alert('Viršintas didžiausias papildomų pareigų skaičius.');
        }
    });

 $(document).on("change",".form-check-input",function(){
  var inputklase =$(this).attr("name");
  //console.log(inputklase);
  $(this).closest("div").find("input."+inputklase).val($(this).is(":checked")?1:0);

 })

    //papildomu pareigu salinimas
    $("body").on("click",".salinti",function(){
        $(this).parents(".fieldGroup").remove();

    });

 /* not working limit
 var $ckb = $(":checkbox[name=pagrindines1]").on("change", function(){

 var $checked = $ckb.filter(":checked");
 $ckb.not($checked).prop("disabled", $checked.length >= 1);

 });
 */

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

   <div class="container">
      <div class="row form-group fieldGroup">
      <h4>Darbuotojo pareigos</h4>
      <div style="position: relative; top: 8px; left: 10px;"><span class="fas fa-plus"></span></div>
                            <div class="col-md-12">
                                <label class="text-black" for="kodas">Tabelio nr.</label>
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">
                            </div>
       <div class="col-md-12">
                                <label class="text-black" for="imone">Įmonė</label>
                                <select class="form-control" name="imone[]" >
          @foreach ($imones as $imone)
                                        <option value="{{$imone->id}}">{{$imone->pavadinimas}}</option>
          @endforeach
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="text-black" for="miestas">Miestas</label>
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value="{{$miestas->pavadinimas}}">{{$miestas->pavadinimas}}</option>
                                    @endforeach
                                </select>
                            </div>
       <div class="col-md-2">
                                <label class="text-black" for="test2">Pad. kodas</label>
                                <input type="text" id="test2" name="padkodas[]" class="form-control">
                            </div>
       <div class="col-md-10">
                                <label class="text-black" for="padalinys">Padalinys</label>
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value="{{$p->kodas}}">{{$p->padalinys}} - {{$p->kodas}}</option>
          @endforeach
                                </select>
                            </div>
       <div class="col-md-2">
                                <label class="text-black" for="test2">Pareigu kodas</label>
                                <input type="text" id="test2" name="parkodas[]" class="form-control">
                            </div>
       <div class="col-md-10">
                                <label class="text-black" for="pareigos">Pareigos</label>
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value="{{$par->kodas}}">{{$par->pavadinimas}} - {{$par->kodas}}</option>
          @endforeach
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="dpradzia">Darbo pradžia</label>
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="bandomasis_laikotarpis">Bandomasis laikotarpis</label>
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="terminuota_sutartis">Terminuota sutartis</label>
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="atldata">Atleidimo data</label>
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">
                            </div>

       <div class="col-md-12">
                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
        <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
        <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="vadovastxt">Vadovas</label>
                            </div>
       <div class="col-md-12">
                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" value="1" name="pagrindines1" >
        <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
        <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="pagrindinestxt">Pagrindinės (Generuoti barkodą pagal šią kortelę.)</label>
                            </div>
                        </div>
      <!-- Papildomos pareigos -->
      <div class="row form-group fieldGroupCopy" style="display: none;" >
      <h4>Papildomos pareigos</h4>
      <div style="position: relative; top: 8px; left: 10px;"><span class="fas fa-minus"></span></div>
                            <div class="col-md-12">
                                <label class="text-black" for="kodas">Tabelio nr.</label>
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">
                            </div>
       <div class="col-md-12">
                                <label class="text-black" for="imone">Įmonė</label>
                                <select class="form-control" name="imone[]" >
          @foreach ($imones as $imone)
                                        <option value="{{$imone->id}}">{{$imone->pavadinimas}}</option>
          @endforeach
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="text-black" for="miestas">Miestas</label>
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value="{{$miestas->pavadinimas}}">{{$miestas->pavadinimas}}</option>
                                    @endforeach
                                </select>
                            </div>
       <div class="col-md-2">
                                <label class="text-black" for="test2">Pad. kodas</label>
                                <input type="text" id="test2" name="padkodas[]" class="form-control">
                            </div>
       <div class="col-md-10">
                                <label class="text-black" for="padalinys">Padalinys</label>
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value="{{$p->kodas}}">{{$p->padalinys}} - {{$p->kodas}}</option>
          @endforeach
                                </select>
                            </div>
       <div class="col-md-2">
                                <label class="text-black" for="test2">Pareigu kodas</label>
                                <input type="text" id="test2" name="parkodas[]" class="form-control">
                            </div>
       <div class="col-md-10">
                                <label class="text-black" for="pareigos">Pareigos</label>
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value="{{$par->kodas}}">{{$par->pavadinimas}} - {{$par->kodas}}</option>
          @endforeach
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="dpradzia">Darbo pradžia</label>
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="bandomasis_laikotarpis">Bandomasis laikotarpis</label>
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="terminuota_sutartis">Terminuota sutartis</label>
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <label class="text-black" for="atldata">Atleidimo data</label>
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">
                            </div>

       <div class="col-md-12">
                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
        <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
        <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="vadovastxt">Vadovas</label>
                            </div>
       <div class="col-md-12">
                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" name="pagrindines1" >
        <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
        <label class="form-check-label" style="margin-left: 25px; margin-top:5px;" id="pagrindinestxt">Pagrindinės (Generuoti barkodą pagal šią kortelę.)</label>
                            </div>
                        </div>
      <!-- Papildomos pareigos pabaiga -->

   </div></code>```

答:
If the checkbox with the name pagrindines1 is added dynamically, you have to delegate the change() event from a static parent element that is already there when the page is initially loaded, e.g. from $(document), using on().

```<code> $(document).on("change", ":checkbox[name=pagrindines1]", function() {
    var $ckb = $(":checkbox[name=pagrindines1]");
    var $checked = $ckb.filter(":checked");
    $ckb.not($checked).prop("disabled", $checked.length >= 1);
 });
</code>```

Body:
I have big complex form, there can be similar checkboxes with the same class or even name. So I need that some of them would restricted from checking more then once. I found good examples how to do that but none of them worked for me. Can someone take a look and say what I'am doing wrong thanks. When pushing green button script generates similar form so i need that checkbox pagrindines would be allowed to select once through all generated forms if there is selected no more can be in other places ofcourse would be great that deselect and changing in another checkbox work.

$('#skaicius').val(2);
$(document).ready(function(){
 $('#duomenys').submit(function(){
  $('#skaicius').val($('.fieldGroup').length*1+1);
 })
    //papildomu pareigu limitas
    var maxGroup = 10;
    //$('#skaicius').val(2);
    //papildomu pareigu pridejimas
    $(".prideti").click(function(){
        if($('body').find('.fieldGroup').length < maxGroup){
            var fieldHTML = '
'+$(".fieldGroupCopy").html()+'
';
            $('body').find('.fieldGroup:last').after(fieldHTML);

        }else{
            alert('Viršintas didžiausias papildomų pareigų skaičius.');
        }
    });

 $(document).on("change",".form-check-input",function(){
  var inputklase =$(this).attr("name");
  //console.log(inputklase);
  $(this).closest("div").find("input."+inputklase).val($(this).is(":checked")?1:0);

 })

    //papildomu pareigu salinimas
    $("body").on("click",".salinti",function(){
        $(this).parents(".fieldGroup").remove();

    });

 /* not working limit
 var $ckb = $(":checkbox[name=pagrindines1]").on("change", function(){

 var $checked = $ckb.filter(":checked");
 $ckb.not($checked).prop("disabled", $checked.length >= 1);

 });
 */

});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Darbuotojo pareigos

                                Tabelio nr.
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">

                                Įmonė
                                <select class="form-control" name="imone[]" >
          @foreach ($imones as $imone)
                                        <option value="{{$imone->id}}">{{$imone->pavadinimas}}</option>
          @endforeach
                                </select>

                                Miestas
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value="{{$miestas->pavadinimas}}">{{$miestas->pavadinimas}}</option>
                                    @endforeach
                                </select>

                                Pad. kodas
                                <input type="text" id="test2" name="padkodas[]" class="form-control">

                                Padalinys
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value="{{$p->kodas}}">{{$p->padalinys}} - {{$p->kodas}}</option>
          @endforeach
                                </select>

                                Pareigu kodas
                                <input type="text" id="test2" name="parkodas[]" class="form-control">

                                Pareigos
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value="{{$par->kodas}}">{{$par->pavadinimas}} - {{$par->kodas}}</option>
          @endforeach
                                </select>

                                Darbo pradžia
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">

                                Bandomasis laikotarpis
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">

                                Terminuota sutartis
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">

                                Atleidimo data
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">

                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
        <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
        Vadovas

                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" value="1" name="pagrindines1" >
        <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
        Pagrindinės (Generuoti barkodą pagal šią kortelę.)

Papildomos pareigos

                                Tabelio nr.
                                <input type="text" id="tabelis" name="tabelio_numeris[]" class="form-control">

                                Įmonė
                                <select class="form-control" name="imone[]" >
          @foreach ($imones as $imone)
                                        <option value="{{$imone->id}}">{{$imone->pavadinimas}}</option>
          @endforeach
                                </select>

                                Miestas
                                <select class="form-control" name="miestas[]" >
                                    @foreach($miestai as $miestas)
                                        <option value="{{$miestas->pavadinimas}}">{{$miestas->pavadinimas}}</option>
                                    @endforeach
                                </select>

                                Pad. kodas
                                <input type="text" id="test2" name="padkodas[]" class="form-control">

                                Padalinys
                                <select class="form-control" name="padalinys[]" >
                                        @foreach ($padaliniai as $p)
                                        <option value="{{$p->kodas}}">{{$p->padalinys}} - {{$p->kodas}}</option>
          @endforeach
                                </select>

                                Pareigu kodas
                                <input type="text" id="test2" name="parkodas[]" class="form-control">

                                Pareigos
                                <select class="form-control" name="pareigos[]" >
                                        @foreach ($pareigos as $par)
                                        <option value="{{$par->kodas}}">{{$par->pavadinimas}} - {{$par->kodas}}</option>
          @endforeach
                                </select>

                                Darbo pradžia
                                <input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">

                                Bandomasis laikotarpis
                                <input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">

                                Terminuota sutartis
                                <input type="date" id="terminuota_sutartis" name="terminuota_sutartis" class="form-control">

                                Atleidimo data
                                <input type="date" id="atldata" name="atleidimo_data" class="form-control">

                                <input type="checkbox" name="vadovas1" style="margin-left: 5px; margin-top:10px;" class="form-check-input" value="1" >
        <input class="vadovas1" type="hidden" name="vadovas[]" value="0">
        Vadovas

                                <input type="checkbox" style="margin-left: 5px; margin-top:10px;" class="form-check-input pagrindines" name="pagrindines1" >
        <input class="pagrindines1" type="hidden" name="pagrindines[]" value="0">
        Pagrindinės (Generuoti barkodą pagal šią kortelę.)

Body:
If the checkbox with the name pagrindines1 is added dynamically, you have to delegate the change() event from a static parent element that is already there when the page is initially loaded, e.g. from $(document), using on().

 $(document).on("change", ":checkbox[name=pagrindines1]", function() {
    var $ckb = $(":checkbox[name=pagrindines1]");
    var $checked = $ckb.filter(":checked");
    $ckb.not($checked).prop("disabled", $checked.length >= 1);
 });


问:
Your startup project doesn't reference Microsoft.EntityFrameworkCore.Design
I have 2 projects in my solution, I have a project with Entity Framework Core installed:

And in the other ASP.NET Web API project I have these packages:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net461" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net461" />
  <package id="WebGrease" version="1.6.0" targetFramework="net461" />
</packages>
</code>```

When I run Add-Migration in PMC:

Your startup project 'API' doesn't reference
  Microsoft.EntityFrameworkCore.Design. This package is required for the
  Entity Framework Core Tools to work. Ensure your startup project is
  correct, install the package, and try again.

I installed Microsoft.EntityFrameworkCore.Design in the startup project instead of the data project that will contain all the entities and now it works, is this how the project should be setup?

答: In order for the migration tool to work, I had to add the Microsoft.VisualStudio.Web.CodeGeneration.Design NuGet package as well.

Body:
I have 2 projects in my solution, I have a project with Entity Framework Core installed:

And in the other ASP.NET Web API project I have these packages:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.5.1" targetFramework="net461" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net461" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net461" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net461" />
  <package id="WebGrease" version="1.6.0" targetFramework="net461" />
</packages>

When I run Add-Migration in PMC:

Your startup project 'API' doesn't reference
  Microsoft.EntityFrameworkCore.Design. This package is required for the
  Entity Framework Core Tools to work. Ensure your startup project is
  correct, install the package, and try again.

I installed Microsoft.EntityFrameworkCore.Design in the startup project instead of the data project that will contain all the entities and now it works, is this how the project should be setup?


问:
What is the best data structure to store, search and delete the element out of array, linked list, stack and queue?
I have a program where I will add the user name and delete the user name on certain conditions such as user return the book to library which means I will have to search the name in the data and the user data will be deleted now from some array or list or whatever data structure is best to use it. </p>

<p>I have four data structure. Array, Linked list, Stack and Queue? I was wondering which one is consider best for adding, searching and deleting the elements? </p>

答: From the four mentioned data structures none supports efficient search, and only Linked list support efficient deletion. If the user name is string (and I suppose it is) the trie data structure would be the optimal one. It supports Θ(k) addition, search, and deletion where k is the length of a string.

Body:
I have a program where I will add the user name and delete the user name on certain conditions such as user return the book to library which means I will have to search the name in the data and the user data will be deleted now from some array or list or whatever data structure is best to use it.

I have four data structure. Array, Linked list, Stack and Queue? I was wondering which one is consider best for adding, searching and deleting the elements?


问:
CUDA array addition and block size
```<code>__global__ void add(int *a, int *b, int *c, int n)
{
    size_t index = threadIdx. + blockId.x * blockDim.x;
    if(index < n)
    c[index] = a[index] + b[index] ;

}
</code>```

Hello, I am trying to remember the reason why the if test is necessary. I remember it is something about block size in this kernel. Is it just about array bounds ?

What will happen for threads whose index are above n ?

答:
I remember it is something about block size in this kernel. Is it just about array bounds ?

Yes. Unless the number of elements in the input and output arrays exactly match the number of threads launched, then out of bounds memory access would occur. In practice that is rarely the case, and it would be normal to round up the grid size to ensure there are more threads than required for the array sizes. The alternative would be to run less threads than inputs, which would leave part of the inputs and outputs unprocessed, and that doesn't make a lot of sense.

What will happen for threads whose index are above n ?

Nothing. They will branch around the memory access portion of the code and exit without touching memory that would otherwise result in a runtime error for out-of-bounds memory access.

Title: CUDA array addition and block size

Body:
__global__ void add(int *a, int *b, int *c, int n)
{
    size_t index = threadIdx. + blockId.x * blockDim.x;
    if(index < n)
    c[index] = a[index] + b[index] ;

}

Hello, I am trying to remember the reason why the if test is necessary. I remember it is something about block size in this kernel. Is it just about array bounds ?

What will happen for threads whose index are above n ?


问:
Problem in Executing Mulesoft Batch Component
I am facing problem in executing batch functionality in MuleSoft 4, I am trying to print the final payload but I am not able to print the final processed payload.Request anyone to help on the same .The code xml is given below .

Thanks.

Code XML :

```<code><http:listener-config name="parentListener" doc:name="HTTP Listener config" doc:id="fbfff994-e442-42eb-84f7-0d6481ef1198" basePath="/" >
    <http:listener-connection host="0.0.0.0" port="8085" />
</http:listener-config>
<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="742dd6a4-706e-473d-96f9-9719f34ed2b6" >
    <http:request-connection host="0.0.0.0" port="8086" />
</http:request-config>
<flow name="parent" doc:id="a8cb06bf-866d-4ec6-9f9f-0f492cc05044" >
    <scheduler doc:name="Scheduler" doc:id="c2a54ae1-7de0-4daf-962c-99a5eef5b78a" >
        <scheduling-strategy >
            <fixed-frequency frequency="10000"/>
        </scheduling-strategy>
    </scheduler>
    <set-payload value="#[['Apple','Banana']]" doc:name="[Apple,Banana]" doc:id="5694f264-e91d-4f2e-81aa-1267cb45f250" />
    <batch:job jobName="processRecordsBatch_Job" doc:id="c3290b63-08ba-4abc-a963-02089df89b7a" >
        <batch:process-records >
            <batch:step name="Batch_Step1" doc:id="79158da3-251b-46ec-b276-0421308fe34c" >
                <set-payload value='"1" ++ payload' doc:name="Step One" doc:id="8cb8905c-4e62-4115-995f-5416ac3a26bd" />
            </batch:step>
            <batch:step name="Batch_Step2" doc:id="00e4f7a3-83a8-46be-8b58-9e5d38850fec" >
                <set-payload value='"2"  ++ payload' doc:name='"StepTwo" ' doc:id="41a80eda-d4db-4a6a-9b0e-b79fade09f45" />
            </batch:step>
        </batch:process-records>
        <batch:on-complete >
            <logger level="INFO" doc:name="Logger" doc:id="56feea1f-6e23-4979-b66b-9d08037b56ef" message='#[payload]'/>
        </batch:on-complete>
    </batch:job>
</flow>
</code>```

Flow Screenshot:

答: Finally I got successful in printing the final output after successful processing of records through it .Screenshot of it is given below . The solution is if we add one more logger component in step 2 as last component we can see the complete output .

Body:
I am facing problem in executing batch functionality in MuleSoft 4, I am trying to print the final payload but I am not able to print the final processed payload.Request anyone to help on the same .The code xml is given below .

Thanks.

Code XML :

<http:listener-config name="parentListener" doc:name="HTTP Listener config" doc:id="fbfff994-e442-42eb-84f7-0d6481ef1198" basePath="/" >
    <http:listener-connection host="0.0.0.0" port="8085" />
</http:listener-config>
<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="742dd6a4-706e-473d-96f9-9719f34ed2b6" >
    <http:request-connection host="0.0.0.0" port="8086" />
</http:request-config>
<flow name="parent" doc:id="a8cb06bf-866d-4ec6-9f9f-0f492cc05044" >
    <scheduler doc:name="Scheduler" doc:id="c2a54ae1-7de0-4daf-962c-99a5eef5b78a" >
        <scheduling-strategy >
            <fixed-frequency frequency="10000"/>
        </scheduling-strategy>
    </scheduler>
    <set-payload value="#[['Apple','Banana']]" doc:name="[Apple,Banana]" doc:id="5694f264-e91d-4f2e-81aa-1267cb45f250" />
    <batch:job jobName="processRecordsBatch_Job" doc:id="c3290b63-08ba-4abc-a963-02089df89b7a" >
        <batch:process-records >
            <batch:step name="Batch_Step1" doc:id="79158da3-251b-46ec-b276-0421308fe34c" >
                <set-payload value='"1" ++ payload' doc:name="Step One" doc:id="8cb8905c-4e62-4115-995f-5416ac3a26bd" />
            </batch:step>
            <batch:step name="Batch_Step2" doc:id="00e4f7a3-83a8-46be-8b58-9e5d38850fec" >
                <set-payload value='"2"  ++ payload' doc:name='"StepTwo" ' doc:id="41a80eda-d4db-4a6a-9b0e-b79fade09f45" />
            </batch:step>
        </batch:process-records>
        <batch:on-complete >
            <logger level="INFO" doc:name="Logger" doc:id="56feea1f-6e23-4979-b66b-9d08037b56ef" message='#[payload]'/>
        </batch:on-complete>
    </batch:job>
</flow>

Flow Screenshot:


问:
PHP naming conventions?
I'm coding smt right now, and am a little bit peeved by the fact that PHP sometimes calls its functions with underscore, and sometimes as one word. What's up with that?

Example:

int strlen(string $str)

and

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

I'm hoping that there is a good reason for this, and would really like to know what it is.

答:
Quoted from: http://tnx.nl/php.html

PHP has inconsistent function naming

  There is no apparent system in underscore(s) versus no underscore(s):

```<code>underscore               no underscore:

stream_get_line          readline
disk_free_space          diskfreespace
is_object                isset
mcal_day_of_week         jddayofweek
set_error_handler        setlocale
snmp_get_quick_print     snmpget
get_browser              getallheaders
base64_encode            urlencode
image_type_to_mime_type  imagetypes
msql_num_fields          mysql_numfields
php_uname                phpversion
strip_tags               stripslashes
bind_textdomain_codeset  bindtextdomain
cal_to_jd                gregoriantojd
str_rot13                strpos
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP naming conventions?

Body:
Quoted from: http://tnx.nl/php.html

PHP has inconsistent function naming

  There is no apparent system in underscore(s) versus no underscore(s):

underscore               no underscore:

stream_get_line          readline
disk_free_space          diskfreespace
is_object                isset
mcal_day_of_week         jddayofweek
set_error_handler        setlocale
snmp_get_quick_print     snmpget
get_browser              getallheaders
base64_encode            urlencode
image_type_to_mime_type  imagetypes
msql_num_fields          mysql_numfields
php_uname                phpversion
strip_tags               stripslashes
bind_textdomain_codeset  bindtextdomain
cal_to_jd                gregoriantojd
str_rot13                strpos


问:
How to create sliding up panel with icon in flutter?
How to create bottom sliding up panel like that?

I added plugin sliding up panel plugin for flutter. Here is the following code

```<code>collapsed:Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: radius
            ),
            child: Padding(
                padding: EdgeInsets.only(left: 5,right: 5),
                child:Container(
                  height: 90,
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Container(//first container
                          height: 20,
                          width: 60,
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 5,top: 5),
                            child:RaisedButton(
                                color: Colors.white,
                                onPressed: (){},
                                shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
                            ) ,
                          ),
                        ),
                        Container(//second container
                          height: 60,
                          child: ListTile(
                            onTap: (){},
                            title: Text('Cart: ',style: TextStyle(color: Colors.black),),
                            trailing: Text("Total( "+" :sum)"),
                          ),
                        )
                      ]
                  ),
                )
            )
        ),
</code>```

The result is

So how can move first container like first image?

答:
I change the SlidingUpPanel color to transparent and only use Background color white on the Wanted Header. Maybe you should fix the box shadow to your preference, and I think you should reduce the padding and the icon height a bit.

```<code>SlidingUpPanel(
      minHeight: 90,
      maxHeight: MediaQuery.of(context).size.height / 2,
      backdropEnabled: true,
      borderRadius: BorderRadius.vertical(
        top: Radius.circular(20),
      ),
      color: Colors.transparent,
      collapsed: Container(
        child: Container(
          height: 90,
          child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                  //first container
                  height: 20,
                  width: 60,
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 10),
                    child: RaisedButton(
                        color: Colors.white,
                        onPressed: () {},
                        shape: RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(30.0))),
                  ),
                ),
                Container(
                  //second container
                  height: 60,
                  decoration: BoxDecoration(
                  color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(20),
                    ),
                  ),
                  child: ListTile(
                    onTap: () {},
                    title: Text(
                      'Cart: ',
                      style: TextStyle(color: Colors.black),
                    ),
                    trailing: Text("Total( " + " :sum)"),
                  ),
                )
              ]),
        ),
      ),
);
</code>```

Body:
How to create bottom sliding up panel like that?

I added plugin sliding up panel plugin for flutter. Here is the following code

collapsed:Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: radius
            ),
            child: Padding(
                padding: EdgeInsets.only(left: 5,right: 5),
                child:Container(
                  height: 90,
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Container(//first container
                          height: 20,
                          width: 60,
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 5,top: 5),
                            child:RaisedButton(
                                color: Colors.white,
                                onPressed: (){},
                                shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
                            ) ,
                          ),
                        ),
                        Container(//second container
                          height: 60,
                          child: ListTile(
                            onTap: (){},
                            title: Text('Cart: ',style: TextStyle(color: Colors.black),),
                            trailing: Text("Total( "+" :sum)"),
                          ),
                        )
                      ]
                  ),
                )
            )
        ),

The result is

So how can move first container like first image?

Body:
I change the SlidingUpPanel color to transparent and only use Background color white on the Wanted Header. Maybe you should fix the box shadow to your preference, and I think you should reduce the padding and the icon height a bit.

SlidingUpPanel(
      minHeight: 90,
      maxHeight: MediaQuery.of(context).size.height / 2,
      backdropEnabled: true,
      borderRadius: BorderRadius.vertical(
        top: Radius.circular(20),
      ),
      color: Colors.transparent,
      collapsed: Container(
        child: Container(
          height: 90,
          child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Container(
                  //first container
                  height: 20,
                  width: 60,
                  child: Padding(
                    padding: EdgeInsets.only(bottom: 10),
                    child: RaisedButton(
                        color: Colors.white,
                        onPressed: () {},
                        shape: RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(30.0))),
                  ),
                ),
                Container(
                  //second container
                  height: 60,
                  decoration: BoxDecoration(
                  color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(20),
                    ),
                  ),
                  child: ListTile(
                    onTap: () {},
                    title: Text(
                      'Cart: ',
                      style: TextStyle(color: Colors.black),
                    ),
                    trailing: Text("Total( " + " :sum)"),
                  ),
                )
              ]),
        ),
      ),
);


问:
Local Storage - React Native
As Async Storage is deprecated what other way is there to store a variable locally??

I have a React Native ios App with a Notification Centre.
Each time the user enters the Notification Centre a Cognito access Token was generated. To avoid excess of token generation the Tokens were saved through Async storage and their expiry was checked.

Now is there some other local storage in React Native that i can use??

答:
Async storage from react-native library is deprecated, they split it from react-native core into a community library.

You can always use Async Storage from this library

Just follow installation steps from docs. And you can import AsyncStorage like this

```<code>import AsyncStorage from '@react-native-community/async-storage';
</code>```

Title: Local Storage - React Native

Body:
Async storage from react-native library is deprecated, they split it from react-native core into a community library.

You can always use Async Storage from this library

Just follow installation steps from docs. And you can import AsyncStorage like this

import AsyncStorage from '@react-native-community/async-storage';


问:
How to decompile an android app from the google play store
I want to decompile one android app that is available on google play store.
Can anybody suggest to me an online tool or any apktool that will help me to decompile source code of apk?

Thanks in advance.

答:
I found apktool much faster as you can run it on your computer.
The problem with the websites pointed to in other answers is that most of the time they have a little bit longer queue while processing decompilation requests.
Also, internet speeds can be a limiting factor in many countries as not everyone gets good upload speed when they want to decompile large apk files.

check this tool out. https://ibotpeaches.github.io/Apktool/install/

After installing run this command to decompile your apk files.
apktool d myfile.apk


问:
How do I linear search two arrays in c++?
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

```<code>string linSearch (double array1[10], double array2[8]);
</code>```

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

```<code>//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7
</code>```

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

```<code>string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}
</code>```

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!

答:
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
using namespace std;

string linSearch(double array1[10], double array2[8])
{

    string result = "";
    bool found;
    for (int j = 0; j < 8; j++)
    {
        if(j > 0)
            result.append(", ");

        found = false;
        for (int i = 0; i < 10; i++){
            if (array1[i] == array2[j]) {
                result.append(to_string(i));
                found = true;
            }
        }
        if(!found)
            result.append("NA");
    }
    return result;
}

int main(){

    double a1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    double a2[8] = {11, 25, 3, 41, 5, 6, 7, 8};
    cout << linSearch(a1, a2) << endl;
    return 0;
}
</code>```

Body:
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

string linSearch (double array1[10], double array2[8]);

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!


问:
How to call multiple properties in powershell
```<code>$loadbalancer = Get-AzureRmLoadBalancer | select Name,ResourceGroupName
</code>```

$loadbalancer has two value ILB name and its resource group.
I want call both value in single PS command, Like when I call ILB name its respective resource group should be called.

答:
The problem isn't entirely clear, can you please give an example of the function being used in the next step. I used "get-command" for the examples rather than get-azurermloadbalancer to avoid being package dependent.

To get the propety from $loadbalancer you use a dot and the name.

To get the current row from pipeline you can use $_

```<code>$loadbalancer = Get-Command get-* | Select-Object -Property CommandType,Name

#get a particular property
$loadbalancer.CommandType

#Use both properties in one function
$loadbalancer | Where-Object{($_.CommandType -eq "function") -and ($_.Name -match "Token")}
</code>```

Body:
$loadbalancer = Get-AzureRmLoadBalancer | select Name,ResourceGroupName

$loadbalancer has two value ILB name and its resource group.
I want call both value in single PS command, Like when I call ILB name its respective resource group should be called.

Body:
The problem isn't entirely clear, can you please give an example of the function being used in the next step. I used "get-command" for the examples rather than get-azurermloadbalancer to avoid being package dependent.

To get the propety from $loadbalancer you use a dot and the name.

To get the current row from pipeline you can use $_

$loadbalancer = Get-Command get-* | Select-Object -Property CommandType,Name

#get a particular property
$loadbalancer.CommandType

#Use both properties in one function
$loadbalancer | Where-Object{($_.CommandType -eq "function") -and ($_.Name -match "Token")}