text:
Q: How do I use Bash on Windows from the Visual Studio Code integrated terminal? Visual Studio Code on Windows uses PowerShell by default as the integrated terminal. If you want to use Bash from Visual Studio Code, what steps should be followed?

A: This, at least for me, will make Visual Studio Code open a new Bash window as an external terminal.
If you want the integrated environment you need to point to the sh.exe file inside the bin folder of your Git installation.
So the configuration should say C:\\<my-git-install>\\bin\\sh.exe.

A: (2021, VSC v.1.55.1)
How to add Git Bash as default Terminal, for those who installed their Git Bash not in the default path:

*

*In Visual Studio Code open Settings using Ctrl + ,

*a) In Search settings (red box on screenshot) field type integrated automation

b) Or just click through Features -> Terminal (blue boxes on ss)

*Click any Edit in settings.json

*Type your bash.exe location into the "terminal.integrated.shell.windows": " " field

Note1: As it's a JSON file, remember to use double \\ instead of \ in your pathway.
Note2: Don't confuse the bash.exe(it's in bin folder) with git-bash.exe, in first case the bash terminal will stay inside VSC, in second it will be opened externally.

A: *

*Install Git from https://git-scm.com/download/win

*Open Visual Studio Code and press and hold Ctrl + ` to open the terminal.

*Open the command palette using Ctrl + Shift + P.

*Type - Select Default Profile

*Select Git Bash from the options

*Click on the + icon in the terminal window

*The new terminal now will be a Git Bash terminal. Give it a few seconds to load Git Bash

*You can now toggle between the different terminals as well from the dropdown in terminal.

A: It depends on whether you have installed Git Bash in the current user only or all users:
If it is installed on all users then put "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).
If it is installed on only the current user then put "terminal.integrated.shell.windows": "C:\\Users\\<name of your user>\\AppData\\Local\\Programs\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).
If the methods listed above do not work then you should try Christer's solution which says -

If you want the integrated environment you need to point to the sh.exe file inside the bin folder of your Git installation.
So the configuration should say C:\\<my-git-install>\\bin\\sh.exe.

Note: The sh.exe and bash.exe appear completely same to me. There should be no difference between them.

A: This answer is similar to the top voted answer, but with an important distinction: a lot of the previous answers on this question focus on running Git Bash while my answer focuses on running WSL Bash.

*

*Enable Windows Subsystem for Linux on your Windows 10 machine.

*Open Visual Studio Code and press and hold Ctrl + ` to open the terminal.

*Open the command palette using Ctrl + Shift + P.

*Type - Select Default Shell.

*Select WSL Bash (NOT Git Bash) from the options.

*Click on the + icon in the terminal window. The new terminal now will be a WSL Bash terminal!

A: My VS Code version: 1.56.1 (code --version)
User settings for configuring integrated terminals:

*

*Ctrl + Shift + P

*type: user

*select: Preferences: Open User Settings

*click: Open Settings (JSON) button (near to upper right corner)

settings.json:
{
    "terminal.integrated.tabs.enabled": true,
    "terminal.integrated.shell.windows": "<your installation path>\\Git\\bin\\bash.exe",
    "terminal.integrated.defaultProfile.windows": "Git Bash",
    "terminal.integrated.profiles.windows": {
        "Git Bash": {
            "path": "<your installation path>\\Git\\bin\\bash.exe",
            "icon": "terminal-bash"
        },
        "Command Prompt": {
            "path": "${env:windir}\\System32\\cmd.exe",
            "icon": "terminal-cmd"
        },
        "Windows PowerShell": {
            "path": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
            "icon": "terminal-powershell"
        }
    }
}

terminal.integrated.defaultProfile.windows
This property will only set GitBash to be default when you hit the "add new terminal" ("+") button. It is not enought to make it default on startup.
terminal.integrated.shell.windows
Depricated warning will be shown. But this configuration is needed to make the selected shell (GitBash here) default on startup.
Problem filtering
On PROBLEMS tab, next to the input field, clicking on the filter icon I checked "Show Active File Only" option to make this deprecated error disappear when dealing with anything else.

A: Latest VS code :

*

*if you can't see the settings.json, go to menu File -> Preferences -> Settings (or press on Ctrl+,)

*Settings appear, see two tabs User (selected by default) and Workspace. Go to User -> Features -> Terminal

*Terminal section appear, see link edit in settings.json. Click and add "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",

*Save and Restart VS code.

Bash terminal will reflect on the terminal.

A: Press and hold Ctrl + ` to open the terminal.
Inside the terminal, type bash to use Git Bash in the terminal.
Note: Make sure you have Git Bash installed on your machine.
If you wish to use PowerShell again, just type powershell in the terminal. To use the Windows command line, type cmd in the terminal.
The setting you choose will be used as your default.

A:

You no longer need to type in bash.exe path manually. This answer is deprecated. Now you can switch to bash directly, if you have git installed in the default path. If you installed git to a different path you need to use the below solution.

Install Git from https://git-scm.com/download/win.
Then open Visual Studio Code and open the command palette using Ctrl + Shift + P. Then type "open user setting", and then select "Open User Settings" from the drop down menu.

Then this tab will open up with default settings on left and your settings on the right:

Now copy this line of code to your own settings page (the pane on the right hand side) and save -
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
Note: "C:\\Program Files\Git\bin\bash.exe" is the path where the bash.exe file is located from the Git installation.  If you are using the Windows Subsystem for Linux (WSL) Bash shell, the path would be "C:\Windows\System32\bash.exe"
Now press Ctrl + ` to open up the terminal from Visual Studio Code. And you will have Bash -

A: Add the Git\bin directory to the Path environment variable. The directory is %ProgramFiles%\Git\bin by default. By this way you can access Git Bash with simply typing bash in every terminal including the integrated terminal of Visual Studio Code.
How to set the path and environment variables in Windows

A: I had already set up lots of conda environments on WSL (Bash on Ubuntu on Windows), so I wanted to use the same Bash installation on Visual Studio Code.
To do that, I just had to specify the path of this particular Bash executable (instead of the Git-Bash) on Visual Studio Code's settings:
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\bash.exe"

PS: to make sure where your Ubuntu on Bash executable is installed on your Windows machine, open the Command prompt (search: cmd) and run:
where bash.exe

A: For scoop users:
"terminal.integrated.shell.windows": "C:\\Users\\[YOUR-NAME]\\scoop\\apps\\git\\current\\usr\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": [
  "-l",
  "-i"
],

A: VS CODE 1.60.0
As I was facing the preceding problem that Git Bash has not been recognized at all, although being previously installed. To let any of the above-mentioned solutions work, you need to follow the instructions discussed in this thread and listed below.

*

*Go to your settings.json

*enable git bash by adding "git.enabled": true

*and define it's path by adding "git.path": "<YOUR PATH TO GIT>\\Git\\bin\\bash.exe"
Afterward, the instructions, for instance as defined by @rustyhu, will work.
PS: Hopefully I'm gonna save you a couple hours of time while debugging the originally stated problem

A: simply go to settings.json in visual studio code and add this line:
  "terminal.integrated.defaultProfile.windows": "Git Bash",

A: Update: (June 2022 , VsCode 1.67)
Many answers here (as this one, highly upvoted) rely on the setting "terminal.integrated.shell.windows" which is now deprecated.
And many others (as the accepted one) assume Git for Windows to be installed with bash.exe in the PATH - which is not the currently recommended/default installation option.
My current recipe:
Add the following to your  settings (Ctrl-Shift-P -> Preferences: Open Settings (JSON) ), replacing with your own bash path:
  "terminal.integrated.profiles.windows": {
    "GitBash": {
      "path": "C:\\devel\\Git\\bin\\bash.exe",
      "icon": "terminal-bash"
    }
  },
  "terminal.integrated.defaultProfile.windows": "GitBash",

Close your current terminals and restart VsCode.

A: What about detached or unrelated shells and code [args] support?
While other answers talk about how to configure and use the VScode integrated WSL bash terminal support, they don't solve the problem of "detached shells": shells which were not launched from within VScode, or which somehow get "disconnected" from the VScode server instance associated with the IDE.
Such shells can give errors like:
Command is only available in WSL or inside a Visual Studio Code terminal.
or...
Unable to connect to VS Code server.
Error in request
Here's a script which makes it easy to solve this problem.
I use this daily to connect shells in a tmux session with a specific VScode server instance, or to fix an integrated shell that's become detached from its hosting IDE.
#!/bin/bash
# codesrv-connect
#
#  Purpose:
#     Copies the vscode connection environment from one shell to another, so that you can use the
#     vscode integrated terminal's "code [args]" command to communicate with that instance of vscode
#     from an unrelated shell.
#
#  Usage:
#    1.  Open an integrated terminal in vscode, and run codesrv-connect
#    2.  In the target shell, cd to the same directory and run
#       ". .codesrv-connect", or follow the instruction printed by codesrv-connect.
#
#  Setup:
#    Put "codesrv-connect somewhere on your PATH (e.g. ~/bin)"
#
#  Cleanup:
#    - Delete abandoned .codesrv-connect files when their vscode sessions die.
#    - Do not add .codesrv-connect files to git repositories.
#
#  Notes:
#     The VSCODE_IPC_HOOK_CLI environment variable points to a socket which is rather volatile, while the long path for the 'code' alias is more stable: vscode doesn't change the latter even across a "code -r ." reload.  But the former is easily detached and so you need a fresh value if that happens.  This is what codesrv-connect does: it captures the value of these two and writes them to .codesrv-connect in the current dir.
#
#   Verinfo: v1.0.0 - les.matheson@gmail.com - 2020-03-31
#

function errExit {
    echo "ERROR: $@" >&2
    exit 1
}

[[ -S $VSCODE_IPC_HOOK_CLI ]] || errExit "VSCODE_IPC_HOOK_CLI not defined or not a pipe [$VSCODE_IPC_HOOK_CLI]"
if [[ $(which code) != *vscode-server* ]]; then
    errExit "The 'code' command doesn't refer to something under .vscode-server: $(type -a code)"
fi
cat <<EOF >.codesrv-connect
# Temp file created by $(which codesrv-connect): source this into your working shell like '. .codesrv-connect'
# ( git hint: add ".codesrv-connect" to .gitignore )
#
cd "$PWD"
if ! test -S "$VSCODE_IPC_HOOK_CLI"; then
    echo "ERROR: $VSCODE_IPC_HOOK_CLI not a socket. Dead session."
else
    export VSCODE_IPC_HOOK_CLI="$VSCODE_IPC_HOOK_CLI"
    alias code=$(which code)
    echo "Done: the 'code' command will talk to socket \"$VSCODE_IPC_HOOK_CLI\" now."
    echo "You can delete .codesrv-connect when the vscode server context dies, or reuse it in other shells until then."
fi
EOF

echo "# OK: run this to connect to vscode server in a destination shell:"
echo ". $PWD/.codesrv-connect"

A: VSCODE 1.63.2
Even combining the answers here, I couldn't get it to work. Maybe, I have a somewhat exotic setup. I'd get this error, Setting "terminal.integrated.defaultProfile.windows": "Git Bash" and it would still only open Powershell and Git Bash is nowhere to be seen:

My workaround was to modify the entry for Command Prompt by changing its path pointing to bash and then set that as default, like so:
"terminal.integrated.profiles.windows": {
    "PowerShell": {
        "source": "PowerShell",
        "icon": "terminal-powershell"
    },
    "Command Prompt": {
        "path": [
            "C:\\Path\\To\\Git\\bin\\bash.exe",
            // "${env:windir}\\Sysnative\\cmd.exe",
            // "${env:windir}\\System32\\cmd.exe"
        ],
        "args": [],
        "icon": "terminal-cmd"

},
"terminal.integrated.defaultProfile.windows": "Command Prompt",

A: In July 2022, I fixed this by adding the following inside the curly braces.
"terminal.integrated.defaultProfile.windows": "Git Bash"

Notice the space between Git and Bash.
So, my settings.json looks like this:
{
    "python.defaultInterpreterPath": "C:\\Users\\Prakh\\AppData\\Local\\Programs\\Python\\Python39\\python.exe",
    "python.diagnostics.sourceMapsEnabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
    "code-runner.runInTerminal": true,
    "terminal.integrated.defaultProfile.windows": "Git Bash"
}

Now restart VS code and close all existing terminals and open a new one.

A: Ctrl+Shift+P > Open User Settings > Paste the following inside { }
"terminal.integrated.profiles.windows": {
    "Git Bash": {
    "path": "D:\\Git\\bin\\bash.exe",
    "icon": "terminal-bash"
    }
},
"terminal.integrated.defaultProfile.windows": "Git Bash",
"git.enabled": true,
"git.path": "D:\\Git\\bin\\bash.exe",
"terminal.integrated.shell.windows": "D:\\Git\\bin\\bash.exe"

If you are in a Workspace!
Ctrl+Shift+P > Open Workspace Settings > Paste the following inside "settings": { }:
"terminal.integrated.profiles.windows": {
    "Git Bash": {
    "path": "D:\\Git\\bin\\bash.exe",
    "icon": "terminal-bash"
    }
},
"terminal.integrated.defaultProfile.windows": "Git Bash",
"git.enabled": true,
"git.path": "D:\\Git\\bin\\bash.exe",
"terminal.integrated.shell.windows": "D:\\Git\\bin\\bash.exe"

Finally close all of your Vscode windows/instances, reopen and you're good to go.
With regard to leonbloy and soulshined
solutions!

A: For me this is the only combination worked!
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\git-cmd.exe",
"terminal.integrated.shellArgs.windows": [
  "--command=usr/bin/bash.exe",
  "-l",
  "-i"
]

With git-bash.exe as the ...shell.windows, every time the bash was opening outside VS!!
Thank God it worked finally!! Else, I was planning to wipe out VS completely and reinstall it (making me to reinstall all my extensions and redo my customizations!)

A: Things has been a little bit changed due to the latest updates on Visual Studio Code. The following steps work for me.

*

*Press Ctrl + Shift + P to open the Visual Studio Code command palate.

*Type >preferences: Open Settings (JSON) in the text area.

*Add the following lines at the end of the JSON file which is displayed in your
right hand pane.
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"

*Close and reopen your Visual Studio Code instance.

A: Visual Studio Code can detect and list installed Git Bash in the menu of config Terminal: Select Default Profile, as many other answers have already described, but this has never happened to me. For those also not-so-lucky as me, you can add custom profile into Visual Studio Code's settings.json manually:
{
    // Tested in Visual Studio Code version 1.58.2, 1.59.1
    // Notice: my git install path is `D:\Git\bin\bash.exe`

    //"terminal.integrated.shell.windows": "D:\\Git\\bin\\bash.exe",
    // This works fine for me for a long time,
    // but in latest versions this is reported as deprecated,
    // you can keep this and sometimes Visual Studio Code will prompt to help
    // `migrate` it into new setting.

    // This part can be generated by Visual Studio Code
    "terminal.integrated.profiles.windows": {
        // This seems to be a reserved profile name, and also does not work for
        // me
        "Git Bash": {
            "path": "D:\\Git\\bin\\bash.exe",
            "icon": "terminal-bash"
        },
        "PowerShell": {
            "source": "PowerShell",
            "icon": "terminal-powershell"
        },
        "Command Prompt": {
            "path": [
                "${env:windir}\\Sysnative\\cmd.exe",
                "${env:windir}\\System32\\cmd.exe"
            ],
            "args": [],
            "icon": "terminal-cmd"
        },

        // Add your custom one with a different profile name from "Git Bash"
        "gitbash": {
            "path": "D:\\Git\\bin\\bash.exe",
            "icon": "terminal-bash"
        }
    },
    // Set the custom profile as default
    "terminal.integrated.defaultProfile.windows": "gitbash",

    // ...
}

A: Updated: Newer versions of Visual Studio Code have the Select Default Shell command in the terminal pull down menu:

Remember that it just lists the shells that are in your %PATH% environment variable. For shells that aren't in your path, see other answers.
Extra tip: when you start bash it will just execute .bashrc, if you have initialization commands in .bash_profile you must copy it to .bashrc. It's essential for using Conda enviroments in Git Bash.
Before version 1.36 (June 2019)
The easiest way now (at least from Visual Studio Code 1.22 on) is to type Shift + Ctrl + P to open the Command Palette and type:
Select Default Shell

Now you can easily select your preferred shell between the ones found in your path:

For shells that aren't in your %PATH%, see the other answers.
See the complete Visual Studio Code shell reference. There's lot of meaty stuff.

A: I followed this tutorial from Paul DeCarlo to use the Bash from the Windows Subsystem for Linux (WSL) instead of what comes with Git Bash for Windows. They are the same steps as above in the answer, but use the below in your User Settings instead.
"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe",
This worked for me the first time... which is rare for this stuff.

A: I happen to be consulting for a Fortune 500 company and it's sadly Windows 7 and no administrator privileges. Thus Node.js, Npm, Visual Studio Code, etc.. were pushed to my machine - I cannot change a lot, etc...
For this computer running Windows 7:
Below are my new settings. The one not working is commented out.
{
    "update.channel": "none",
    "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
    //"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe"
}

A: I tried the above answers as of vscode 1.42.1 and they worked inasmuch as to get me a git bash terminal. So, bottom line this setting works just for opening a bash shell from terminal:
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"

However it has the unwanted side effect of also being the shell used to build things and that breaks the MS C++ chain because the \ character used for path separator is understood by bash as an escape character. The complete fix for me then required me to add this extra variable, setting it to powershell:
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"

Now, I can have my bash terminal and Ctrl-Shift-B or F5 work without problems.
Oh, and as other posters mentioned, the source for this information is VSCode's documentation.

A: To open a terminal in Visual Studio Code you do not need to use Ctrl + ` as recommended everywhere, since it's highly inconvenient finger operation. A better solution would be this:
Ctrl + j

A: If you already have "bash", "powershell" and "cmd" CLI's and have correct path settings then switching from one CLI to another can done by the following ways.

Ctrl + ' : Opens the terminal window with default CLI.
bash + enter : Switch from your default/current CLI to bash CLI.
powershell + enter : Switch from your default/current CLI to powershell CLI.
cmd + enter : Switch from your default/current CLI to cmd CLI.

VS Code Version I'm using is 1.45.0

A: In the latest stable build, i.e. 1.54, Disabling ConPTY solved my problem. I am writting this incase it does solve yours too.
{

 "terminal.integrated.shell.windows": "C:\\path\\to\\bin\\bash.exe",
 "terminal.integrated.windowsEnableConpty": false
}

A: Add this to settings.json
{
    "terminal.integrated.profiles.windows": {
        "PowerShell": {
            "source": "Git Bash",
            "icon": "terminal-bash"
        },


text:
Q: Node Analysis - current calculation I have a cicuit here that's giving me trouble when finding out what V1 and V2 equal.The book says that I1 is traveling through the 8 ohm resistor (R1) towards ground. But when I build the circuit on multi-sim it says that I1 is traveling through (R1) upwards "clockwise. I'm confused why the book says I1 is counter clockwise and my simulator says clockwise.
R1 = 8 ohm   R2 = 4 ohm   R3 = 10 ohm  I = 2A   E = 64V
I thought I2 and I add up to I1. I'm so confused. How do I determine the direction of the current so I can build my equation. I always seem to be confused on how to determine the direction of the current. Does it matter? I"m still very confused on node analysis.

A:
The book says that I1 is traveling through the 8 ohm resistor (R1) towards ground. But when I build the circuit on multi-sim it says that I1 is traveling through (R1) upwards "clockwise. I'm confused why the book says I1 is counter clockwise and my simulator says clockwise. ...  I always seem to be confused on how to determine the direction of the current.

You don't need to know the direction of the current before you solve the circuit. You can guess whichever way you want. If the current is actually flowing the other way, you'll just get a negative number for the value of the current.

The book says that I1 is traveling through the 8 ohm resistor (R1) towards ground. But when I build the circuit on multi-sim it says that I1 is traveling through (R1) upwards "clockwise.

In the example in the book, what was the value they found for I1? If it was negative, there's no contradiction with the simulation result.

A: If I1 is the current from the voltage source there is no contradiction.  All paths to ground from the 64V source flow - upwards - through the 8 ohm resistor.

A: Nodal analysis is the application of Kirchoff's Current Law (KCL) to solution of circuit node voltages.  KCL basically says that all currents into a node (any branch or junction between components) equals the current out of the node.  It has to be this way because otherwise the charges would pile up in the node, and the circuit would just explode :^) .  It may seem counter-intuitive that by using KCL you end up focused on and solving for voltages, but that's the way it is.
To use KCL you need to choose a current flow convention.  There are only 2 possible:

*

*Positive current flow out of the node, and negative current flow into the node.  You could state this as: \$I_{\text{out-of }\text{node} }\$ = \$I_{\text{into } \text{node}}\$, or   0 = \$I_{\text{out-of }\text{node} }-I_{\text{into } \text{node}}\$

*Or, negative current flow out of the node, and positive current flow into the node.  You could state this conventions as: \$I_{\text{into } \text{node}}\$ = \$I_{\text{out-of }\text{node} }\$, or 0 = \$I_{\text{into } \text{node}}\$ - \$I_{\text{out-of}\text{node} }\$ .

It doesn't matter which of these conventions you choose as long as you are consistent.  Consistency may be the hobgoblin of little minds, but those hobgoblins are essential for Nodal analysis to work.
After choosing a current convention, make a process to follow.

*

*Define the circuit nodes.

*Discount or substitute any degenerate nodes.  A degenerate node is any node which you can tell by inspection what it's voltage would be.  Usually that will be a voltage source connected between a node and the ground node.  Voltage at that node is just the value of the voltage source.

*Write a current equation for all the non-degenerate nodes using Ohms Law.

*Solve the set of equations simultaneously.

Let's use this process to solve your circuit.  First I'm going to make a couple of name changes:  calling the battery voltage \$V_B\$ (not E), and calling the current source \$I_S\$ (not I).  I'm going to choose the convention of current out of the node being positive.  (I like the positive out convention because it makes it obvious at a glance which node the equation is covering.  For example, if the equation is for node 2 ( \$v_2\$ ) then in each term of the equation \$v_2\$ will be first and positive.)
Now, start the process:

*

*Define the circuit nodes.  Node 1 is the junction of \$V_B\$ and \$R_1\$.  Node 2 is the junction of \$R_1\$ , and \$R_2\$ and \$I_S\$ .   Node 3 is the junction of \$R_2\$ and \$I_S\$,  and \$R_3\$.

*Degenerate nodes.  Node 1 is a degenerate node, so no equation is for node 1, just substitute \$V_B\$ in where ever \$v_1\$ would be in any node equations.

*Write the current equations.
   Node 2:  0 = \$\frac{v_2-V_B}{R_1}+\frac{v_2-v_3}{R_2}+I_S\$
   Node 3:  0 = \$\frac{v_3}{R_3}+\frac{v_3-v_2}{R_2}-I_S\$

*Solve the equations.
\$v_1\$ = \$-\frac{-R_2 V_B-R_3 V_B+R_1 R_2 I_S}{R_1+R_2+R_3}\$ = 37.82V
\$v_2\$ = \$\frac{R_3 \left(V_B+R_2 I_S\right)}{R_1+R_2+R_3}\$ = 32.73V
You would get the same end result if you used the other current convention.  That is basic Nodal analysis.  Practice until you can do it without thinking much about it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: X64 memory page permission Can I set specific memory page as Only executable not readable and writable?
I've heard that X86 and X64 has no X permission bit on the page table
and there is a NX bit for enforce R/X and R/W
But, can we allocate or set the specific page a executable only?
Thanks.


text:
Q: sudden github page error: Github Build and Deploy Error: No uploaded artifact was found There was no problem for me committing and pushing my changes to my github page but suddenly it failed with this error Github Build and Deploy Error: No uploaded artifact was found.
Here is the github page workflow: https://github.com/brian6484/brian6484.github.io/actions
I have looked at similar question posed by Github Build and Deploy Error: No uploaded artifact was found but my issue seems different from his because mine failed halfway. What is this artifact that I am missing?

A: Oh finally found the solution. The build tab on the right (not the default deploy tab) in workflow page shows the cause of error and mine was this

Liquid Exception: Liquid syntax error (line 147): Unknown tag 'endhighlight' error

, which was caused when I was incorrectly formatting my code in md file. Hope this helps someone with similar issue! :)


text:
Q: Redirect php product link to other page I need to redirect
https://www.eurekahomehealthcare.com/eureka/services-details.php?id=34
to
https://www.eurekahomehealthcare.com/service/babysitting-services/
can anyone guide me on how to do this using htaccess

A: Check this rule on top of your .htaccess file
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^\/eureka\/services-details\.php
RewriteCond %{QUERY_STRING} id=34
RewriteRule ^(.*)$ https://www.eurekahomehealthcare.com/service/babysitting-services/? [L,R=301]


text:
Q: Derivative of simple fraction What is the fastest way of finding the derivative of:
$\frac{x}{x+K}$ (simplified form)
is there a substitution I miss or does the quotient rule the job here? There should be a quick way of finding the derivative

A: Quotient rule works, although here's a probably slightly faster method.
Let $$\begin{align}y &= \dfrac{x}{x+K}
\\\ln y &= \ln x - \ln(x+K)
\\&\text{Differentiating w.r.t.} x
\\\dfrac{1}{y}\dfrac{dy}{dx} &= \dfrac{1}{x} - \dfrac{1}{x+K}
\\\dfrac{dy}{dx} &= y \left(\dfrac{1}{x} - \dfrac{1}{x+K}\right)
\\ &= \dfrac{x}{x+K}\left(\dfrac{1}{x} - \dfrac{1}{x+K}\right)
\\&= \dfrac{1}{x+K}-\dfrac{x}{(x+K)^2}
\\&= \dfrac{x+K-x}{(x+K)^2}
\\&= \dfrac{K}{(x+K)^2}\end{align}$$

A: by th quotient rule we get
$y'=\frac{x+K-x}{(x+K)^2}=\frac{K}{(x+K)^2}$


text:
Q: Django Unit test is written but coverage report says there are missing statements I try to get coverage reports using a simple django model.
Unit test for model was written but report says there are missing statements.
The model:
from django.db import models
from model_utils import FieldTracker

from generics.base_model import BaseModelMixin

class AModel(BaseModelMixin):
    record_name = models.CharField(max_length=255)
    tracker = FieldTracker()

    class Meta(BaseModelMixin.Meta):
        db_table = 'a_model_records'

    def __str__(self):
        record _name = self. record_ name
        if record_name is None:
            record_name = "N/A"
        return record name

The unit test:
class TestAModel(TestCase):

    def setUp(self):
        super().setUp()

    def test_amodel(self):
        record_name = "some name"
        is_active = True

        user = User.objects.first()
        record = AModel.objects.create(
            record_name=record_name,
            is_active=is_active,
            created_by_id=user.id,
        )
        self.assertEqual(str(record), record_name)
        self.assertEqual(record.name, record_name)
        self.assertEqual(record.is_active, is_active)

The command line code I run:
source activate
set -a
source local.env
set +a
coverage run --source="unit_test_app" --rcfile=.coveragerc project/manage.py test -v 2
coverage report
coverage html

The coverage configuration is like this:
[run]
omit=
    */migrations/*
    */tests/*
    */manage.py
    */apps.py
    */settings.py
    */urls.py
    */filters.py
    */serializers.py
    */generics/*

[report]
show_missing = true

Coverage result shows missing statements:

This is the simplest example.
There are many ignored functions by coverage which descends percentage average, but actually covered by unit tests.
Why does coverage act like this?


text:
Q: How to get SSID and pswd of hidden network over ethernet on CMD I have a router that the network is hidden, and I do not know the SSID or pswd. Instead, I connect it manually using an ethernet cable. How can I get the SSID and pswd over ethernet?

A: If you are connected via Ethernet, you should be able to log into the router. The IP address to connect to the router is usually 192.168.1.1 or 10.0.0.1. For my Cox router it was different, so check what the IP is for your model.
The default login is usually "admin", and the default password is usually "admin", "password", or blank. Once logged in, you should be able to find information on the Wi-Fi SSID. I was also able to see the Wi-Fi Passkey as well.


text:
Q: My sql update statement is not filling my column I have two tables A and B.
Table A  has columns:
LI
PC (key)
CI (key)
DI
TM
V
AI (no data in this column at this time)
Table B has columns:
PC (key)
CI (key)
CT
CS
CV
AI
I would like to update Table A so that A.AI = B.AI
The update statement I wrote is as follows:
     Update A
        Set A.AI *= B.AI
       From A, B
      where A.PC *= B.PC
        And A.CI *= B.CI

When I attempted to test this I used the SQL statement:
     Select A.*
       From A, B
      Where A.CI *= B.CI
      And A.PC *= B.PC
      And A.AI *= B.AI
      Group by A.AI, A.CI, A.PI;

And everything populates while the AI column remains empty. Can anyone help me realize my error?

A: Looks like a typo here:
Set A.AI *= B.AI

Should be:
Set A.AI = B.AI


text:
Q: Trying to add string element to array using map I try to add string string element to array using map as follows, but the code do not work. What's wrong there?
function towerBuilder(nFloors) {
 let towerArray = [];
 towerArray.length = nFloors;
 let arrItem = '*' + ' ';
 let newArr = towerArray.map(function(item, i) {
   let n = 2 * i + 1;
   item = arrItem.repeat(n);
   return item;
 });
}

A: Array.map will skip undefined values. So you will have to use new Array(length).fill(dummyValues)

function towerBuilder(nFloors) {
  let towerArray = new Array(nFloors).fill("")
  let arrItem = '*' + ' ';
  let newArr = towerArray.map(function(item, i) {
    let n = 2 * i + 1;
    item = arrItem.repeat(n);
    return item;
  });
  console.log(newArr)
}
towerBuilder(3)

Reference

*

*Array.map doesn't seem to work on uninitialized arrays

A: You can try the following code to solve your issue:
function towerBuilder(nFloors) {
  var stars = '*';
  var count;
  var array=[];
 for (var i = 0; i<=nFloors-1; i++){
  count = stars.repeat(2 * i + 1);
  array.push(count);
}

return array;
}


text:
Q: Android App published with limited countries and tester is outside of that countries My current scenario:

*

*I launched app with 2 country named XX and YY. The app's tester are from ZZ country.

*App is launched in Beta Channel in Google play developer console

*We created Close Beta testing and added those all user's email address who are from ZZ country

*If we send APK to user by email, then they can download and install and test it as well in his device.

*if we send opt-in URL and they can not download APP from url, Google play shows "This app is incompatible with your device." message in browser and "This item is not available in your country" message in Googleplay app in android device

So is there any possibilities that we can setup such environment ?


text:
Q: Tkinter custom background image I want to put as the entire app background a custom image.
I read somewhere that I have to do something like this:
root = Tk()
bg_image = PhotoImage(file="C:/Users/Matteo/Desktop/fisica.png")
app = App(root,image=bg_image)
root.title("Fisica")
root.geometry("330x470")
root.mainloop()

When I try to run the code, it says:
TypeError: init() got an unexpected keyword argument 'image'
I can't understand what's the problem

A: you should add the image to a label:
 Label(root, image=bg_image)

then use .pack() or .grid() to position the label to the grid.
see here:
how to put a image as a background in tkinter in python
You could have found this by searching stackoverflow/google.
You can't add the image directly to the root window.


text:
Q: Multipart upload in amazon s3 not calling delegates I'm using multipart upload for file upload its working. But, not calling delegates how to call delegates.
Here my code:
AmazonS3Client *s31 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
            s31.endpoint = [AmazonEndpoints s3Endpoint:US_WEST_2];
            s31.timeout = 240;
            @try
            {
                [s31 createBucketWithName:bucket];

                S3InitiateMultipartUploadRequest *initReq = [[S3InitiateMultipartUploadRequest alloc] initWithKey:key inBucket:bucket];
                S3MultipartUpload *upload = [s31 initiateMultipartUpload:initReq].multipartUpload;
                S3CompleteMultipartUploadRequest *compReq = [[S3CompleteMultipartUploadRequest alloc] initWithMultipartUpload:upload];

                int numberOfParts = [self countParts:imageData];
                for ( int part = 0; part < numberOfParts; part++ ) {
                    NSData *dataForPart = [self getPart:part fromData:imageData];
                    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
                    [appDelegate.dataArray addObject:dataForPart];

                    // The S3UploadInputStream was deprecated after the release of iOS6.
                    NSInputStream *stream = [NSInputStream inputStreamWithData:dataForPart];
                    //if ( using3G ) {
                    // If connected via 3G "throttle" the stream.
                    //stream.delay = 0.2; // In seconds
                    //stream.packetSize = 16; // Number of 1K blocks
                    // }

                    S3UploadPartRequest *upReq = [[S3UploadPartRequest alloc] initWithMultipartUpload:upload];
                    upReq.partNumber = ( part + 1 );
                    upReq.contentLength = [dataForPart length];
                    upReq.stream = stream;

                    S3UploadPartResponse *response = [s31 uploadPart:upReq];
                    [compReq addPartWithPartNumber:( part + 1 ) withETag:response.etag];
                    NSLog(@"Coming222");
                }
                [s31 completeMultipartUpload:compReq];
                [self textfileupload];
            }
            @catch ( AmazonServiceException *exception )
            {
                isUpload=NO;
                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

                NSLog( @"Multipart Upload Failed, Reason: %@", exception  );
            }

Please help me.

A: If you want it to call delegate methods, you need to perform this, as with any objects that rely on delegate methods:
 putObjectRequest.delegate = self;
 [putObjectRequest setDelegate:self];

If you mean how you are using an instance of AppDelegate: AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];, then double check on if type casting as an AppDelegate pointer is the correct thing to do. Perhaps try another way of initializing/allocation, as I have run into issues with relying on a returned object typecasted into a cocoa pointer.


text:
Q: how to calculate the time complexity of this code ? and what it will be? What will be the time complexity?
This is the code of which the complexity needed to be found:
I can't understand the recursion part mainly :/
void xyz(int n)
{
    for (int i=0;i<n;i++)
      do something;
    if (n)
      for (int i=0;i<n;i++)
        xyz(n-1);
    else return;
}

A: As someone commented on your question, watch your use of n and i. if(n) will always evaluate to true if n > 0. Also, currently the nesting seems like it might be off, try using brackets to make it clearer.
The general idea for calculating time complexity is to count (mathematically, not manually) how many times the basic operation (the most time-consuming operation, usually the most time-consuming operation inside the deepest nested loop) and seeing how the complexity (number of times the basic operation is done) relates to the input size.
If the time complexity increases at the same speed as the input size increasing, it's linear, or in the complexity class O(n). If the complexity increases exponentially compared to the input size, it might be in the class O(n^2) for instance.
Recursion definitely can get tricky, but the idea is to "expand it out", specifically by setting up a recurrence relation. Here's a really good tutorial on using recurrence relationships to find the time complexity of recursive algorithms:
http://www.cs.duke.edu/~ola/ap/recurrence.html


text:
Q: Reading .xlsx in java I've read every single question here and couldn't find the easy answer.
What I need is just 1 .jar, which I will add into my project in Eclipse. Then I just want to import it and use a library that can extract data from .xlsx file.
Apache POI needs a lot of .jar files. It crashes and throws a lot of exceptions that don't make sense.
Smartxlsx has absolutely no documentation and it's horribly hard to use/understand it.

A: I believe that Apache POI would be one of best solutions to read XLSX files.
It's only required two dependencies(As you mentioned it doesn't required lot of jars) and if you interested please go through following example where you can get some idea about how to integrate Apache POI with in couple of minutes.


text:
Q: A solution of a second order homogenous ODE has infinite zeros on a closed interval is $y=0$
We have the ODE $y''+p(x)y'+q(x)y=0$, the functions $p(x)$ and $q(x)$
  continuous on a closed interval $[a,b]$. Prove that if the solution
  $y(x)$ has an infinite number of roots ($x$s such that $y(x)=0$) on
  the interval $[a,b]$, then $y(x)=0$.

I tried negating the claim, saying there is an $x_0$ such that $y(x_0)\neq 0$, but got nowhere.
A hint or a direction of thought would be appreciated.

A: Choose a sequence $\{x_n\}_{n=1}^{\infty}$ of distinct roots of $y$ so $y(x_n) = 0$ and $x_n \in [a,b]$. Since $[a,b]$ is compact, the sequence $\{ x_n \}_{n=1}^{\infty}$ has a convergent subsequence which we will still denote by $\{ x_n \}_{n=1}^{\infty}$ with $x_n \to x_0$ and $x_0 \in [a,b]$. Since $y$ is continuous, we have $y(x_0) = 0$.
Consider
$$ y'(x_0) = \lim_{x \to x_0} \frac{y(x) - y(x_0)}{x - x_0} = \lim_{x \to x_0} \frac{y(x)}{x - x_0}. $$
The limit exists and so we can calculate it using an arbitrary sequence approaching $x_0$. Since the $x_n$ are distinct, then by throwing at most one element from the sequence we can assume that $x_n \neq x_0$ for all $n \in \mathbb{N}$. Calculating the derivative using $\{ x_n
\}$, we get
$$ y'(x_0) = \lim_{n \to \infty} \frac{y(x_n)}{x_n - x_0} = \lim_{n \to \infty} \frac{0}{x_n - x_0} = 0. $$
The uniqueness of solutions to the initial value problem then guarantees that $y(x) = 0$ for all $x \in [a,b]$.


text:
Q: Test Babel transpiled(AMD) ES6 code in Karma + Jasmine I have written test in ES6, which is transpiled to ES5 in AMD format using Babel.
Now I want to run the test using Karma(+requirejs) and Jasmine, but getting following error:
Error: Mismatched anonymous define() module: function (exports) {
    "use strict";

    describe("App", function () {
        it("tests something", function () {
            expect(true).toBe(true);
        });
    });
}

The test file looks like:
define(["exports"], function (exports) {
    "use strict";

    describe("App", function () {
        it("tests something", function () {
            expect(true).toBe(true);
        });
    });
});
//# sourceMappingURL=app.js.map

A: I'm not transpiling to ES5 first, but use karma-babel-preprocessor.


text:
Q: RingtonePreference not firing onSharedPreferenceChanged My Preferences all trigger the onSharedPreferenceChanged event upon a change. It works for all preferences: Checkbox, List, custom, etc. But it won't be called if I select a ringtone from the RingtonePreference. I have this code:
    <CheckBoxPreference android:title="@string/pref_notification"
        android:defaultValue="true" android:summary="@string/pref_notification_summary"
        android:key="prefNotification" />
    <RingtonePreference android:title="@string/pref_ringtone"
            android:key="prefRingtone"
            android:summary="@string/pref_ringtone_summary" android:ringtoneType="all" />
    <CheckBoxPreference android:title="@string/pref_vibrate"
        android:defaultValue="true" android:summary="@string/pref_vibrate_summary"
        android:key="prefVibrationOn" />
    <ListPreference android:title="@string/pref_notification_interval"
        android:summary="@string/pref_notification_interval_summary"
        android:key="prefNotificationInterval" android:defaultValue="60"
        android:entries="@array/prefs_interval" android:entryValues="@array/prefs_interval_values" />

And my class:
public class TimePrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    context = this;

    addPreferencesFromResource(R.layout.preferences);

    Preference dbPref = (Preference) findPreference("prefDeleteDb");
    dbPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference)
        {
            showWipeDbDialog();
            return true;
        }
    });
}

@Override
public void onResume() {
    super.onResume();

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    toggleEnableList();
}

@Override
public void onPause() {
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onPause();
}

@Override
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1)
{
    boolean enabled = toggleEnableList();

    if (enabled)
    {
        OnBootReceiver.setAlarm(TimePrefsActivity.this);
    }
    else
    {
        OnBootReceiver.cancelAlarm(TimePrefsActivity.this);
    }
}
}

All the preferences, except the RingtonePreference, reach method onSharedPreferenceChanged. Does anyone have an idea? Thanks.

A: I also thought this was a bug in the system at first, but the issue is actually more subtle. RingtonePreference launches a new activity via an intent. This means that your PreferenceActivity gets paused. And you're unregistering your listener in onPause(). If you don't do this, it'll work fine (at least it did for me).
But naturally, you can't have your handler stay registered forever. I compromised by using onStart()/onStop() instead of onResume()/onPause().

A: I struggled with the same problem which seems to be a bug in the android system.
After debugging the code I noticed the listener is not added to our RingtonePreference listeners map, unlike other classes like ListPreference.
I opened a ticket, but for now I found a way to overcome it using OnPreferenceChangeListener.
My code sets the preference summary to the selected ringtone, you can use your logic instead.
First make your activity implement OnPreferenceChangeListener and write the onPreferenceChange method
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    updateRingtoneSummary((RingtonePreference) preference, Uri.parse((String) newValue));
    return true;
}

private void updateRingtoneSummary(RingtonePreference preference, Uri ringtoneUri) {
    Ringtone ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
    if (ringtone != null)
        preference.setSummary(ringtone.getTitle(this));
    else
        preference.setSummary("Silent");
}

Notice that unlike onSharedPreferenceChanged, onPreferenceChange is called before the preference is updated, so you must use the newValue parameter to get the selected data instead of getting it from the preference.
Then, set the listener on OnResume:
@Override
protected void onResume() {
    super.onResume();

    // A patch to overcome OnSharedPreferenceChange not being called by RingtonePreference bug
    RingtonePreference pref = (RingtonePreference) findPreference(getString(R.string.pref_ringtone));
    pref.setOnPreferenceChangeListener(this);

}

Hope this helps.

A: I had to manually set the OnPreferenceChangeListener myself on my SettingsFragment:
    Preference notificationSoundPref = findPreference(Constants.PREFS_NOTIFICATION_SOUND);
    notificationSoundPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // do what you need here
            return true;
        }
    });


text:
Q: Open HTML page with href I have HTML template code like
<!doctype html>
<html>
<head>
<title>Our Funky HTML Page</title>
<meta name="description" content="Our first page">
<meta name="keywords" content="html tutorial template">
</head>
<body>
Content goes here.
</body>
</html>

I want generate a link in my html template who render this code into a new page
For now I have done a function like this
function stringToHtml(htmlString: string) {
  let parser = new DOMParser();
  let doc = parser.parseFromString(htmlString, 'text/html');
  return doc.body;
}

who take html string (my template) as argument.
In my template (where I need to render this link) I interpolate this function
function generateLink(myHtmlTemplate: string, text: string){
  const page = stringToHtml(myHtmlTemplate)
  return `<a href="${page}" target="_blank">${text}</a>`
}

But I don't know I can I do to open the HTML render after a click on the link


text:
Q: Jquery code doesn't work without alert var countChecked = function () {
  var n = $("input:checked").length;
  $("#count").text(n + (n === 1 ? " is" : " are") + " checked!");
};

countChecked();
alert();        // this alert

$("input[type=checkbox]").on("click", countChecked);

I use this code to count the number of checkbox inputs that are checked.
With alert() this works well. But without the alert this is not working. How can i fix it?

A: Only one line code is enough for your outcome:-

$( "input[type=checkbox]" ).on( "click",function(){
    alert($("input[type=checkbox]:checked").length);
});

<input type="checkbox" name="vehicle" value="Cycle"> I have a cycle

<input type="checkbox" name="vehicle" value="Bike"> I have a bike

<input type="checkbox" name="vehicle" value="Auto"> I have a Auto

<input type="checkbox" name="vehicle" value="Car"> I have a car

<input type="checkbox" name="vehicle" value="Bus"> I have a bus

<input type="checkbox" name="vehicle" value="Truck"> I have a truck

Note:- your code starts processing without waiting the document to load properly so basically it need to be failed, but when alert() comes then it waits for document to be rendered properly, and then you code outputs the result.
Put the whole code inside $(document).ready(function(){ and you are good to go (then you can remove alert()also).
But more easiest solution is given by me.Thanks

A:
With alert() this work well.But without alert() this is not working.How can i fix it

The code doesn't wait until the DOM is ready. alert() is a blocking event, after which the DOM is usually loaded. One way to achieve the desired functionality without the alert is by observing the DOMContentLoaded event on the DOM with .ready() (i.e. $(document).ready()).

$(document).ready(function() {
  var countChecked = function() {
    var n = $("input:checked").length;
    $("#count").text(n + (n === 1 ? " is" : " are") + " checked!");
  };

  countChecked();

  $("input[type=checkbox]").on("click", countChecked);
});

Count:

<input type="checkbox" value="1" id="one">1

<input type="checkbox" value="2" id="two">2

A: Your code needs to be enclosed with document.ready Jquery function
$(document).ready(function(){
  var countChecked = function () {
    var n = $("input:checked").length;
    $("#count").text(n + (n === 1 ? " is" : " are") + " checked!");
  };

 countChecked();
 alert();        // this alert

 $("input[type=checkbox]").on("click", countChecked);
})


text:
Q: Why does fread() not work for files with html content? I tried to read some files with the following code:
Main:
#define RESPONSE_MAX_LENGTH (1024 * 1024)       // Should be 1MB
char file_content[RESPONSE_MAX_LEGNTH];
memset(&file_content, 0, RESPONSE_MAX_LEGNTH);

request_get_file("/User/...", file_content);

Function Declaration:
int request_get_file(char* requested_file_path, char* buf) {
    int file_size = 0;
    FILE* fp = NULL;

    if ((fp = fopen(requested_file_path, "r+")) == NULL) {
        return errno;
    }

    fseek(fp, 0L, SEEK_END);
    file_size = (int)ftell(fp);
    rewind(fp);
    errno = 0;
    if (fread(buf, 1, file_size, fp) == 0) {
        if (!feof(fp)) {
            if (ferror(fp)) {
                printf("An error occured while reading the requested file. File size: %d\n", file_size);
                perror("fread()");
                return errno;
            }
        }
    }
    fclose(fp);
}

I am able to read .txt files, but when I open a html file, I get an error saying:
fread(): Bad address (Created with perror("fread"))
errno = 14
For some reason, this error only occurs for some specific documents.
Solution:
I just realized that the problem seems to be related to a specific file. After renaming my test.html to test.txt and trying to open this one, the error is still there. Could that have to do with the file content?
=> Yes, as the buffer I was writing the data was way too small.
How can I fix this issue?

A: The problem was that the buffer I was writing to was way too small to hold all the data read by fread().
My updated code:
Main:
char* buf = NULL;
request_get_file("/User/...", &buf);

Function Declaration:
int request_get_file(char* requested_file_path, char** buf) {
    int file_size = 0;
    FILE* fp = NULL;

    if ((fp = fopen(requested_file_path, "r+")) == NULL) {
        return errno;
    }

    fseek(fp, 0L, SEEK_END);
    file_size = (int)ftell(fp);
    rewind(fp);
    errno = 0;

    if ((*buf = calloc(file_size + 1, sizeof(char))) == NULL) {
        perror("calloc()");
        return errno;
    }

    if (fread(*buf, 1, file_size, fp) == 0) {
        if (!feof(fp)) {
            if (ferror(fp)) {
                printf("An error occured while reading the requested file. File size: %d\n", file_size);
                perror("fread()");
                return errno;
            }
        }
    }
    fclose(fp);
}


text:
Q: why does mv not work if the destination directory is too large I was at work and debugging an automated program that moves x number of files into a directory.
After freezing when listing the directory, I moved it out of the way because it seemed to have too many files (~75000 files | 297MB). At this point I also noticed that when I did "ps ax | grep mv" that a lot of other processes that used move were stuck (even though they were not moving to the same directory).
After moving the directory out of the way and recreating an empty directory it seemed to work and the programs continued to write to the newly created directory but I am curious to know why? Is it because of the limitation of the file system in linux or does it have to do with the way the move command works?


text:
Q: How to find cause of server hanging while having only 3 seconds of access Remote debian buster server, so can't go to console.
Yesterday it worked properly, today it has stopped responding. I can reboot it remotely, so after reboot I can reconnect, but I can only run short command like top and I lose the connection. On top, I found that 100% is clamd, but when I tried to /etc/init.d/clamd-daemon sto I lost the connection before typing last the letter. So I copied it next time, but it doesn't help. I wonder which logs should I try to get (via scp) for better diagnosis....

A: Fail2ban has add my address into blacklist, and 3 seconds fail2ban needs to load the list....
Hope somebody helps....

A: The only solution I found is to go rescue mode and turn off programs which I saw it top during 3 seconds of access.. And when it goes back to work - one of programs is a bad guy... So one after one...

A: You should check the output from sudo dmesg -T


text:
Q: CSS and DIV 3 columns with " TILES " I'm trying to do a website that would look like this :

So each cell has a size based on content.  I'm stuck with the CSS part of it any idea on how I could do this ?
For a real example of what I'm trying to do :
http://yourquestions.mcdonalds.ca/
Thanks

A: You have two possible ways around this problem.

*

*Use a jQuery API which does it for you (Masonry is a good start).

*Split your data into three sections (See working example)

table {
  float: left;
  margin-right: 0.2em;
}
table.left tr td {
  background-color: red;
}

table.middle tr td {
  background-color: blue;
}

table.right tr td {
  background-color: green;
}

Left 1

Left 2

 Left 3

Middle 1

Middle 2

Middle 3

Right 1

Right 2

Right 3

A: If you don't need to support browsers under ie10 you can do this natively in CSS. Just give your container a column style...
ul {
    -webkit-column-count: 3; /* Chrome, Safari, Opera */
    -moz-column-count: 3; /* Firefox */
    column-count: 3;
}

List Item

List Item

List Item

List Item

List Item

List Item

List Item

List Item

You can also specify how much room is in-between each column. See: http://www.w3schools.com/css/css3_multiple_columns.asp for more info


text:
Q: Could not find a part of the path "/content:/com.android.externalstorage.documents/document/6759-130B%3ANew%20Text%20Document.txt" I am using FilePicker-Plugin-for-Xamarin-and-Windows and got this error while accessing external storage:
Could not find a part of the path "/content:/com.android.externalstorage.documents/document/6759-130B%3ANew%20Text%20Document.txt".

Note:I have both read and write permissions And also I ask user at runtime.
When using this path problem gone:
storage/6759-130B%3ANew%20Text%20Document.txt

This is very known old bug in picker as officially mentioned.
For me it looks like I have to convert content:// into file path.
More info

A: I remembered the thing, You need to get the absolute path from your uri. Usually, content:// path is returned from download folder or any drive path, you need to get actual path for it. You can try this.

Its an device specific code for Android, Inject it with dependency service.

I faced above issue in Native android & solved that as follows in Java, below is the converted code for the same in c#
private string GetRealPathFromURI(Uri contentURI)
{
    ICursor cursor = ContentResolver.Query(contentURI, null, null, null, null);
    cursor.MoveToFirst();
    string documentId = cursor.GetString(0);
    documentId = documentId.Split(':')[1];
    cursor.Close();

    cursor = ContentResolver.Query(
    Android.Provider.MediaStore.Images.Media.ExternalContentUri,
    null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new [] { documentId }, null);
    cursor.MoveToFirst();
    string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
    cursor.Close();

    return path;
}

EDIT -

Try this

       FileData fileData = await CrossFilePicker.Current.PickFile();
       string filePath;
       if (fileData != null)
       {
            await Task.Run(() => {
            filePath = DependencyService.Get<IImageUtilities>().SaveFileFromStream(new MemoryStream(fileData.DataArray), fileData.FileName));
        });

Code for Xamarin.Android

public string SaveFileFromStream((System.IO.Stream imageStream,  string filename)
{
            string name = filename;
            string filePath = null;
            try
            {
                byte[] imageData = ((MemoryStream)imageStream).ToArray();
                IFolder folder = FileSystem.Current.GetFolderFromPathAsync(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString()).Result;
                IFile file = folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName).Result;
                filePath = System.IO.Path.Combine(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString(), file.Name);

                System.IO.Stream outputStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
                outputStream.Write(imageData, 0, imageData.Length);
                outputStream.Flush();
                outputStream.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return filePath;
}

Later on, the new path of the file is used everywhere needed accordingly.

This is what I actually do in my project, whichever file is selected by the user, it is copied to Pictures Dir in internal storage & returns the path.
We deal with the ImageStream to make a copy of the original document.
The idea to make a duplicate copy is that we uses the copy for uploading purpose as the user may delete the original document selected. So after pushing the document to the server, we delete the copied file as well. So as we deal with the stream we don't face any issue with Content://.
Hope this maybe helpful.


text:
Q: MySQL Calling A Stored Procedure Error I am really hoping someone can help me out.
I had a SQL Server 2014 database which I used for a desktop application I wrote. After having to expand, I want to convert to MySQL to access the database over the internet.
I user MySQL WorkBench Migration Tool to copy all the tables and data from the SQL Server to the MySQL Server. The only problem is the procedures would not copy, so had to modify them manually.
Example of a Procedure in MySQL:
DELIMITER $$
CREATE DEFINER=`johandre`@`%` PROCEDURE `sp_GetAllOrdersBySuburb`( IN `@SuburbID` VARCHAR(50) )
NO SQL
SELECT * from Orders  WHERE DeliverySuburb = @SuburbID$$
DELIMITER ;

The server created the procedures, and all procedures not using IN inputs do show what they must, but the procedures that user inputs give me an error:
When calling from PhpMyAdmin SQL:
Error

SQL query: Edit Edit
SET FOREIGN_KEY_CHECKS = ON;
MySQL said: Documentation
2014 - Commands out of sync; you can't run this command now

And when I run the procedure in C# Winforms App, it just returns a empty result set.
The code I used to call the procedure:
SET @p0='1'; CALL `sp_GetAllOrdersBySuburb`(@p0);

When I run the code in the procedure as a normal SQL query, then it also returns the data as expected.
I hope this is enough information, and hope this isn't a repeat question, but I did look around and still found no help.
Thank You

A: I think, your problem might be your delimiter when defining the procedure.
Also, when using backticks to define your param (otherwise @ won't be allowed), you need them when accessing the param, too:
DELIMITER $$ /* make $$ the delimiter for actually executing something */

CREATE DEFINER=`johandre`@`%` PROCEDURE `sp_GetAllOrdersBySuburb`( IN `@SuburbID` VARCHAR(50) )
NO SQL
SELECT * from Orders  WHERE DeliverySuburb = `@SuburbID`; /* normal ; here, you just define your proc */

$$ /* now execute the definition */

DELIMITER ; /* reset the delimiter */

For the delimiters:
You change your delimiter because you don't want any ; in your procedure being interpreted as an execution delimiter but being part of your procedure instead. After that, you want to execute the whole definition and then reset the delimiter.
For @ in parameters:
@ is a reserved character only for accessing global variables. If you really want to use @ in your param, you need backticks to make this work. Backticks allow you to use white spaces, reserved words and even strange characters or those who have a special meaning in regular syntax and are not allowed in an identifier otherwise to be used within identifiers anyway. However, you have to use backticks for a correct dereference as well then.
`@identifier`

and
@identifier

resolve to different things. That means, you need
SELECT * from Orders  WHERE DeliverySuburb = `@SuburbID`;

instead of
 SELECT * from Orders  WHERE DeliverySuburb = @SuburbID;


text:
Q: Set A Field the same as ID (IDENTITY) in the insert I have a Code (int) in my table, the ID is set to identity. How can I set a default value for my code to be filled by the same value az ID? I mean Identity.

A: If it always has the same value - why don't you just drop that field. Otherwise it can be maintained with triggers (BEFORE INSERT one).

A: You could use an after insert trigger:
create table TestTable (id int identity, col1 int)
go
create trigger TestTrigger on TestTable after insert
    as begin
    update  TestTable
    set     col1 = id
    where   col1 is null
            and id in (select id from inserted)
    end
go

Test code:
insert TestTable default values
insert TestTable (col1) values (666)
insert TestTable default values
select * from TestTable

In general, I try to stay clear of triggers.  In the long run using a stored procedure for insert is much more maintainable:
create procedure dbo.InsertTestRow(
    @col1 int)
as
insert  TestTable (col1) values (@col1)

if @col1 is null
    begin
    update  TestTable
    set     col1 = id
    where   id = SCOPE_IDENTITY()
    end

A:
I'm looking for something in the
  default value! If it is null it should
  be filled with the same value as id
  but if it is provided with some value,
  it should keep that value

You could solve the issue by using coalesce in your queries instead.
create table T (ID int identity, ID2 int)

insert into T values (default)
insert into T values (null)
insert into T values (78)

select
  ID,
  coalesce(ID2, ID) as ID2
from T

Result
ID  ID2
--  ---
1   1
2   2
3   78

A: Assuming your table's ID is an Identity column, you could consider using a constraint:
ALTER TABLE MyTable
ADD CONSTRAINT MyTableCodeDefault
DEFAULT IDENT_CURRENT('MyTable') FOR Code

This works for these use cases:
INSERT INTO MyTable DEFAULT VALUES
INSERT INTO MyTable ({columns NOT including 'Code'})
  VALUES ({value list matching insert columns})
INSERT INTO MyTable (Code) VALUES (666)
INSERT INTO MyTable (Code) SELECT 8 UNION SELECT 13 UNION SELECT 21

But it does not work for bulk inserts:
INSERT INTO MyTable ({columns NOT including 'Code'})
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}
UNION
SELECT {value list matching insert columns}

This restriction may seem onerous, but in my practical experience, it's rarely a problem. Most of the use cases I've encountered that need a default value involve user/UI 'convenience': don't force the user to pick a value if they don't want to.
OTOH, rarely do I encounter bulk insert situations where it's impractical to specify the value for the columns you're targeting.

A: You could use computed column, like this:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id)

insert into TempTable
default values

insert into TempTable
default values

insert into TempTable
default values

select * from TempTable

Of course if you have other columns, then you dont need default values:
if object_id('TempTable') is not null drop table TempTable
create table TempTable (Id int identity(1,1), Code as Id, SomethingElse int)

insert into TempTable (SomethingElse)
select 10 union all
select 11 union all
select 12

select * from TempTable

But, like zerkms said - why do you need two columns that are same?

A: If the field is an Identity field in SQL Server, the database engine will take care of its value. What we normally do is to read the record back (after inserting) to get to the generated Id.
EDIT: It sounds like you are trying to "override" the identity? If so, before you insert, run:
SET IDENTITY_INSERT [tableName] ON

You'll have to be careful not to insert a value that already exists. This can get tricky, though. So maybe consider removing the identity property altogether, and managing the default values yourself?


text:
Q: computational complexity of the following algorithm? I have an array arr of size n containing the integers 1 through n in a random order; for example, it might be arr = [4 5 3 6 2 1].
For each element e in arr, I need to find the closest element k that is less than e. ("Closest" in terms of position, not value; so in the above example, 5 is closer to 3 than to 6.) If there are equally-close lesser elements in both directions — as with 6 in the example above, whose immediate neighbors are both less than it — then it doesn't matter which of those elements is chosen.
So with the example above, arr = [4 5 3 6 2 1], one valid result is [3 3 2 2 1 NIL].
I know of a O(n) algorithm to solve this; it works by maintaining a stack to find the nearest smaller element in left and right of every element.
But surprisingly, a simple linear bidirectional search performed better than that algorithm, even though it seems to me to be O(n2) in the worst case:
for i = 1 to N
  right = i + 1
  left = i - 1
  while (left > 0 && right <= n)
    // ...find the closest element that is smaller than arr[i] and break while loop

What is the worst-case complexity of the above? Am I right that it's O(n2)?

A: It is worst-case Θ(n log n) time (assuming you implement the fix that Daniel mentions above — you need to make sure that you can scan all the way to the end in each direction).
First, observe that if two elements a and b are neighbors, then either a < b or b < a. In either case, at least one of these elements will require a "search distance" of only 1.
By extension, at least half the elements of the array will require a search distance of only 1.
Similarly, if four elements [a, b, c, d] are all in a row, then one of these is less than the other three. So at least three of these elements will require a search distance of at most 3. And as noted above, two of them actually require a search distance of only 1, so really this means that two have a search distance of 1 and a third has a search distance of at most 3. The total search distance is then at most 2·1 + 1·3 + (n−1).
We can continue this logic for increasing runs of length 2k: we have at most 2k−1·(21−1) + 2k−2·(22−1) + 2k−3·(23−1) + ⋯ + (n−1).
If n is a power of 2, then we can write it as 2k, and the total search distance is at most:
2k−1·(21−1) + 2k−2·(22−1) + 2k−3·(23−1) + ⋯ + 20·(2k−1) =
      = (2k−2k−1) + (2k−2k−2) + (2k−2k−3) + ⋯ + (2k−20)
      = k·2k − 2k + 1
      = n log n − log n + 1
      < n log n
(If n is not a power of 2, then we can obtain a somewhat larger array by appending the values n+1, n+2, etc., until we do have a power of 2, and observe that the resulting total search distance is less than 2n log 2n, which is still in Θ(n log n).)
Of course, the above just sets an upper bound (O rather than Θ); but I think it shows how to actually achieve the worst-case: we want the least numbers spread as far apart as possible, in a powers-of-two fashion. For example, we can "expand" a list like this:
1       2
1   3   2   4
1 5 3 6 2 7 4 8

The total search distance for the above is 7 + 1 + 2 + 1 + 4 + 1 + 2 + 1 = 17 = 3·8 − 8 + 1, as predicted.


text:
Q: Div resizing height with Gridstack container I'm using the Gridstack.js framework in an app and have some div columns:

And I'm setting the height of the 1st Div to be the same as whatever the Gridstack container is like this:
$(document).ready(function () {
     var divHeight = $('.grid-stack').css("height");
     $('.cont').css('height', divHeight);
});

So on load the divs are both the same height, but if the Gridstack div has more items added to it and grows in height I wanted the 1st div to also be the same height.
Is there a way to dynamically make the 1st div change height to be the same as the Gridstack div as its adjusted?

A: In case you're using ajax call, I would suggest you should create a function of height change instead of $(document).ready like so:
var helpers = {
    heightChange() {
        var divHeight = $('.grid-stack').css("height");
        $('.cont').css('height', divHeight);
    }
};

And then in your ajax call to makes change/put data in .grid-stack you only need to call your function, full code for example:

Hope this help, feel free to tell me your other problem.

A: This might help you https://jsfiddle.net/4uqd3jqL/

$(document).ready(function () {
  $('.cont').css('height', $('.grid-stack').css("height"));

   setTimeout(function(){
       $('.grid-stack').css("height", $(this).height() + 100);
       $('.cont').css('height', $('.grid-stack').css("height"));
   }, 1000);
});
.grid-stack{
  height:300px;
  background: red;
}

.cont{
  height:200px;
  background: blue;
}

.col-lg-6{
  width:50%;
  display: inline-block;
  float:left;
}

Since I don't have any Ajax call, I have used setTimeout.
In setTimeout I'm increasing the height of grid-stack container by 100px & then setting the height of cont by height of grid-stack

A: You can achieve this simply using css without nay jquery or javascript.
Use css flex properties.

.s_panel_container {
  display: flex;
}
.s_panel {
    flex: 1;
}
.cont {
  background-color: pink;
}
.grid-stack {
  background-color: #ccfff5;
}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

         1st div content

        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


text:
Q: How to Cancel changes in a form? I have a settingsForm and in this form the user will change different values , Add/delete things from the database and I need when the use hit cancel button all changes he made will be cancelled and return to last saved state ,how this works ?

A: The easiest way is to not make changes at all until the user hits OK. Make a list of all changes that have to be done and only execute that list on OK. Simply close the form on Cancel.

A: You can use BeginTransaction then after that execute query against the database.
private static SqlTransaction transaction;
private static SqlConnection conn;

public static void BeginTransaction()
    {
        try
        {
            transaction = conn.BeginTransaction();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

If a user clicks OK then execute CommitTransaction:
public static void CommitTransaction()
    {
        try
        {
            transaction.Commit();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

If a user clicks cancel then execute RollbackTransaction:
public static void RollbackTransaction()
    {
        try
        {
            transaction.Rollback();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

you can use BeginTransaction on Form load event, example:
private void Form1_Load(object sender, EventArgs e)
{
        conn.Open();
        ClassName.BeginTransaction();
}

And then close connection depending on a click event. Use cancel button and all changes he made will be cancelled and return'd to last saved state. If ok button is clicked all changes are committed to the database.
    private void cancel_Click(object sender, EventArgs e)
    {
        ClassName.RollbackTransaction();
        conn.Close();
    }

    private void ok_Click(object sender, EventArgs e)
    {
        ClassName.CommitTransaction();
        conn.Close();
    }

ClassName is your class that defines the connection. Now you can execute a query based on a connection that is opened at Form_Load. Until the user presses the OK or the Cancel button. For example you can execute delete all from table button click.
private void deleteAll_Click(object sender, EventArgs e)
{
    SqlCommand cmnd = CreateCommand("TRUNCATE TABLE TABLE_1", CommandType.Text);
    cmd.ExecuteNonQuery();
}

and the changes (delete all) to a database will be made or not, depending on a user clicking cancel or ok.


text:
Q: Determining the memory access pattern of a program I want to extract all the virtual memory addresses accessed by a program and the sequence in which these memory addresses are accessed. Is there some tool/system call on Windows(preferred) or Linux which would let me do this?
Say there is a program P which accesses memory addresses m1,m2,m3 etc. I want to log what addresses were accessed and the sequence in which these addresses were accessed. I also want to know whether the memory address belongs to stack or heap.
Thanks!

A: What you need is called a tool for dynamic binary instrumentation. A famous one, which I am currently working with is Intel Pin. Be warned that you have to do a lot of reading and reviewing the examples in order to produce something functional.


text:
Q: How to summarize view-components/widgets-information in a JAR-File? I would like to use an ajax toolkit/framework like ZK (www.zkoss.org) or GWT. But I don't know whether it's possible to bundle resources in a JAR? Do you know which one support such resource loading?

A: Not sure what your goal is, but if its to bundle a web application into one file, then you can do that with a WAR file - assuming your deploying onto a java webcontainer like tomcat or jboss.

A: My goal is to summarize the Java-classes and also their Templates-files for the view of various application modules, each in one Java-Jar-File. These modules I use in another application, which of course I summarize in a WAR-File for Deployment. I would like to know which ajax-Framework/Toolkit does support this.

A: Take a look at http://www.ztemplates.org which is simple and easy to learn. This one allows you to put all related templates, javascript and css into one jar and use it transparently. Means you even have not to care about declaring the needed javascript in your page when using a provided component, as the framework does it for you.


text:
Q: CakePHP multiple time and condition with price not working I have this query in CakePHP and it is not working. But I have record in db when I remove the inner price condition the it return result but not working with price.
SELECT `Car`.`id`, `Car`.`title`, `Car`.`description`, `Car`.`image`, `Car`.`state`,
    `Car`.`state_code`, `Car`.`city`, `Car`.`zipcode`, `Car`.`person_name`, `Car`.`email`,
    `Car`.`phone`, `Car`.`mobile`, `Car`.`ad_type`, `Car`.`ad_status`, `Car`.`make`,
    `Car`.`model`, `Car`.`year`, `Car`.`conditiion`, `Car`.`transmision`, `Car`.`color`,
    `Car`.`fuel`, `Car`.`body`, `Car`.`doors`, `Car`.`mileage`, `Car`.`price`,
    `Car`.`accessories`, `Car`.`security`, `Car`.`created`, `Car`.`user_id`
FROM `portal_Carsnew`.`cars` AS `Car`
WHERE `Car`.`ad_status` = '1'
    AND `Car`.`make` = 'Ferrari'
    AND `Car`.`model` = '458 Italia'
    AND `Car`.`state` = 'New York'
    AND `Car`.`city` = 'Albany' AND ((`Car`.`price` < 95000)
    AND (`Car`.`price` > 0))
ORDER BY `Car`.`id`
desc LIMIT 10

A: Use cakephp find method to select records from table
Try bellow code
$this->Car->find('all', array(
     'conditions' => array(
         'Car.ad_status' => 1,
         'Car.make' => 'Ferrari',
         'Car.model' => '458 Italia',
         'Car.state' => 'New York',
         'Car.city' => 'Albany',
         'Car.price >' =>0,
         'Car.price <' =>95000
       ),
       'order'=> 'id DESC',
       'limit' => 10
 ));

A: Try this:
$this->Car->find('all', array(
 'conditions' => array(
 'and' => array(
                    array('Car.price > ' => 0,
                          'Car.price < ' => 95000
                         ),
     'Car.ad_status' => 1,
     'Car.make' => 'Ferrari',
     'Car.model' => '458 Italia',
     'Car.state' => 'New York',
     'Car.city' => 'Albany',
    )),
   'order'=> 'id DESC',
   'limit' => 10
));

A: Try this one:
$price = array();
$price['Car.price >'] = 0;
$price['Car.price <'] = 95000;

$this->Car->find('all', array(
     'conditions' => array_merge($price,
         array(
             'Car.ad_status' => 1,
             'Car.make' => 'Ferrari',
             'Car.model' => '458 Italia',
             'Car.state' => 'New York',
             'Car.city' => 'Albany',
             'Car.price >' => 0,
             'Car.price <' => 95000
         )
     ),
     'order' => 'Car.id DESC',
     'limit' => 10
));


text:
Q: Although the header is correct From: does not change in php mail Hello i am trying to build an email class in which the user can send html mail. The user must be able to set the To:, Cc:, Bcc:, From:. Everything works except from. The From Name changes but the email does not.
The addFrom Function:
public function addFrom($from, $name = 'Test Email'){
        $this->_headers .= "From: " . $name ." ". strip_tags($from) . "" . PHP_EOL;
    }

In Gmail i see this:

Even though when i call the addFrom Method i set:
$mail->addFrom('dotpass@hotmail.com');

I also tried adding the <> around the from in the function but no email show up.
I also print_r my headers:

How can i set the from to change? I am running this on localhost.


text: Q: Откуда у последовательного интерфейса столько каналов передач? Разбираюсь с шиной PCI Express. Есть разные ее виды при разных версиях - x1, x4, x8, x16, x32. Пропускная способность растет в геометрической прогрессии, как и количество каналов передач под каждый вид. Почему такое количество линий, если PCIe использует передачу бит за битом?


text:
Q: Line bundle on the Jacobian of a curve which restricts to the canonical bundle Consider $J$, the Jacobian of a smooth projective genus two curve  $C$over complex numbers. Let $L$ be a line bundle such that $L|_C$ is $K_C$, the canonical bundle of $C$. Can we say that $L\simeq O_J(C)$. If not, is there some relation between these two line bundles. Do we know that $L$ has a section?

A: If $g(C) = 2$ so that $C \subset J$ is a divisor, then by adjunction
$$
K_C = (K_J + C)\vert_C = C\vert_C
$$
since $K_J = 0$. So, indeed, $L = O_J(C)$ works.
Since the restriction map $Pic^0(J) \to Pic^0(C)$ is an isomorphism, this is the only line bundle with this property.


text:
Q: Replace all occurrences of an array of words in page I'm trying to highlight all occurrences of an array of words anywhere on the page, regardless of their parent element.
I've adapted the following question's solution and it works great if I know the selector to use the function on. However, the words could appear in ANY selector, so I'm trying to use a wildcard selector, but it's not working.
(function($) {
var keywords = ['Breathalyzer', 'Marijuana', 'Alcohol'];

function highlightWords(element) {
    full_text = element.html();
    $.each(keywords, function(i) {
        full_text = full_text.replace(RegExp(keywords[i], "gi"), ""+keywords[i]+"");
    });
    element.html(full_text);
  }
highlightWords($("*"));

})(jQuery);

I'm using a regexp that's case insensitive so that it matches the search terms regardless of case. And I'm expecting the function to wrap all matched terms in  but it's not working...
EDIT: I guess I should add that I'm not getting any sort of errors in the console

A: Answer:
There are a few things that need to be changed for this to work as you'd expect:

*

*$("*") returns a collection. It's an array of elements, not a single element. Therefore passing the array into a function expecting a single element will not work.

Solution:
We can fix the above by using JQuery's .each function to iterate over each item in the collection and then calling your highlight function.

*We have to adjust your highlightWords function to be on the receiving end of the each method.

Solution:
We change the parameters to match what's passed
   in. This is why instead of element, we use index, element.

*.html is a JQuery method. We need to be sure that the element variable that we receive contains this method or we won't be able to use it.

Solution:
Since the element is not a JQuery object, we wrap the element within a JQuery object by passing the element variable in as a selector. element = $(element);

Working Code:

(function($) {
var keywords = ['Breathalyzer', 'Marijuana', 'Alcohol'];

function highlightWords(index, element) {
    element = $(element);
    full_text = element.html();
    $.each(keywords, function(i) {
        full_text = full_text.replace(RegExp(keywords[i], "gi"), ""+keywords[i]+"");
    });
    element.html(full_text);
  }
$("*").each(highlightWords);

})(jQuery);
.highlighttext {
 color: green;
}

Hello Alcohol

This is a test of marijuana

Maybe we should get a Breathalyzer?

No, no, we should get more Alcohol.


text:
Q: React component doesn't get event when action is dispatched from inside an ajax call When I try to dispatch an action from inside an ajax call, while the store itself gets updated (Checked in the browser redux plugin), the component doesn't receive the event, and therefore doesn't re-render.
class SomeComponent extends React.Component{
  constuctor (props) {
    super(props);
    this.someAjaxCall();
  }
    someAjaxCall(){
        this.props.dispatch(someAction('Work'));
            $.ajax({
         type: "POST",
         url: "someURL",
        success: function(data)
        {
            this.props.dispatch(someAction("Does Not Work"));

         }.bind(this)
  });
  }
  render(){
    return (

);
  }
}

 const mapStateToProps = (store, ownprops) => {
    return {
      store: store.get("Some_Key")
    }
  }

const render = (store,container) => {
   let ConnectedComponent = ReactRedux.connect(this.mapStateToProps)(SomeComponent);
      ReactDOM.render(
                <Provider store={ store }>
                  <ConnectedComponent/>
                </Provider>
        , container);
}

const someAction = (state) => {
  return {
    type: 'SOME_CASE',
    state: state
  }
}

const reducer = (state, action) => {
  switch (action.type) {
    case 'SOME_CASE':{
      return state.set("stateKey",action.state);
    }
    default: {
      return state;
    }
  }
}

From the above sample, when I call         this.props.dispatch(someAction('Work'));
The store gets updated, the component gets the event and re-renders itself. However, when I call from inside the 'success' function of an ajax call, the store gets updated, but the component never receives the event.

A: If I am wrong, please correct me.
The second Action creator call should not be failed as someAction is not global. Did you get any errors.


text:
Q: Clarification of this solution: Nash equilbirum of splitting 10 dollars between 2 people So the game is each player chooses an amount between 0 and 10, if the sum is greater than 10 they win nothing. If the sum is less than or equal to 10 each player gets what they selected.
The solution states that "the Nash equilibrium of the game is any two numbers that add to 10. This is obvious because any amount greater than 10 destroys the value of the game and any amount less than 10 induces regret".
However the solution goes on to further state that "the unique Nash equilibrium is for each player to choose $5".
Where I am getting confused is that the two statements contradict each other. The first states any pair that adds to 10 is a Nash equilibrium, but then the second statement seems to suggest only 5,5 is a Nash equilibrium.

A: Here is an explanation of why $(5,5)$ is not the only nash equilibria in this problem. The important thing to remember about game theory is that the two players have no idea of what the other shall choose.
Let us consider from each player's perspective.
Player 1's perspective
From player 1's perspective player 2 has picked some choice $c_2$ such that $ 0 \leq c_2 \leq 10$. So what is player 1's most profitable decision? He/she should pick $10-c_2$. Any higher and he gets 0, any lower and he isn't maximizing profit.
Player 2's perspective
This game is symmetric so the same hold from player 2's perspective. Player 1 has picked some choice $c_1$ such that $ 0 \leq c_1 \leq 10$ and so player 2's most profitable decision is to pick $10-c_1$. Any higher and he gets 0, any lower and he isn't maximizing profit.
So what is the optimal strategy? Well if we define the optimal strategy for player 1 as a best response function of player 2's choice ($c_2$), then $f_1(c_2) = 10-c_2$ and similarly for player 2: $f_2(c_1) = 10-c_1$, then the optimal strategy is the intersection of these two functions. These are the pure strategy nash equilibria.
This is demonstrated graphically below, where the filled circles are player 1's optimal decisions at each choice x of player 2 and the gray empty circles are player 2's optimal decisions for each choice y of player 1. Clearly the best response functions intersect at every point.
Edit: I managed to find an analogous problem to this one online. You should check it out too. It's called splitting a dollar (p.23).

A: I am Economist and do Game Theory. So I can assure you that while {5,5} is an equilibrium of the game, it is not unique.
Any pair {x,y}, such that $x\geq0$, $y\geq0$ and $x+y=10$ is an equilibrium.
To verify that {x,y} is an equilibrium we have to verify that no player has incentives to deviate given the actions of the other (in other words, he cannot do better by choosing different action then prescribed in equilibrium given the actions prescribed for the other player by our candidate equilibrium).
Here, if player 1 chooses $x \geq 0$, player 2 chooses $y\geq 0$ and $x+y=10$ then no player has incentives to deviate. To see this consider Player 1 (the case for player 2 is analogous). Player 1 can deviate by choosing z>x or zx then, given that the other player plays $y$, the sum will be z+y>10 and hence he will get nothing. This is worse then choosing $x$ since in that case he gets $x$. Clearly, choosing $z<x$ is also not an equilibrium. In this case $z+y<10$, and Player 1 will get $z$ which is less than $x$. So again, he has no incentives to deviate. Thus, we conclude that Player 1 has no incentives to deviate. Since the case of Player 2 is analogous, we conclude that {x,y}, such that x+y=10 is an equilibrium.
A little bit more counter-intuitive might be the case $x=0$ and $y=10$. But in this case Player that chooses $x$ is indifferent to playing the proposed strategy and deviating. In the Nash Equilibrium definition we require that player has no STRICT incentives to deviate. Hence this is still equilibrium.

A: I would interpret the first sentence as:

The Nash equilibrium must be given by a couple of numbers that sum to $10$.

Then the second sentence doesn't contradict the first one.

A: This doesn't make much sense. The $(5,5)$ Nash equilibrium might seem like the most "fair" equilibrium of all the possible Nash equilibria (and this can be formalized using notions that compare different Nash equilibria) but it is definitely not the unique Nash equilibrium.


text:
Q: Thunar/PCManFm/Nautilus freeze 25 seconds at startup I'm on Kali Linux with everything up-to-date.
It freezes 25 seconds whe lauch Thunar/PCManFm/Nautilus or other file manager based on GTK. It doesn't happen when PC is just booted on, it start happening after being used for a while, maybe half hour, maybe 24 hours later.
EDIT: Workaround
killall gvfsd-trash fixes the problem temporary, if it still freezes, try killall gvfsd.
EDIT 2: Fixed
It seems that the bug was fixed in recent updates, it has been working all fine for about 2 months, try a system update if it still happens.


text:
Q: How can scrollTop has no effect in Javascript while scrolling is available by mouse? All of
$(document).scrollTop(100);

$(window).scrollTop(100);

$('html body').scrollTop(100);

does not scroll and does nothing.
How can it be?
UPDATE
To reproduce the problem.

*

*Open this page in Chrome: http://test.beyondmap.com/properties?view=map

*Open Chrome developer tools.

*Go to console.

*Enter the following command in console
$(window).scrollTop(100)

*Nothing will happen.

*Expected: scroll down by 100 pixels.
UPDATE 2
I wrote the following HTML, opened it in separate window, reduced it's size so that scrollbars appear and it works:
<!DOCTYPE html>

My First Heading

<input type="button" value="scroll" onclick="document.getElementsByTagName('body')[0].scrollTop+=10">

My paragraph 0.

My paragraph 1.

My paragraph 2.

My paragraph 3.

My paragraph 4.

My paragraph 5.

My paragraph 6.

My paragraph 7.

My paragraph 8.

My paragraph 9.

My paragraph 10.

My paragraph 11.

A: You have CSS rule html, body { height: 100%; }, change it to html, body { height: auto; } and all scroll functions come available for use.
For smooth scrolling effect you can use;
$('html,body').animate({scrollTop: 100}, 2000);

Targeting both html and body brings you great browser support.
UPDATE
Now after spending some time looking into this issue more closely, there are two bugs causing issues here;
"scrollTop of BODY always 0 when HTML element has overflow: hidden"
https://bugs.chromium.org/p/chromium/issues/detail?id=633573
"scrollTop property breaks with body height 100% overflow auto"
https://bugs.chromium.org/p/chromium/issues/detail?id=423935
Other way to fix the issue, is to remove the overflow-x: hidden; css rule from the html selector.
Broken version of your simple demo
<!DOCTYPE html>

My First Heading

<input type="button" value="scroll" onclick="document.getElementsByTagName('body')[0].scrollTop+=10">

My paragraph 0.

My paragraph 1.

My paragraph 2.

My paragraph 3.

My paragraph 4.

My paragraph 5.

My paragraph 6.

My paragraph 7.

My paragraph 8.

My paragraph 9.

My paragraph 10.

My paragraph 11.


text:
Q: Coalesce Function with JOIN I have been trying to use Coalesce function in SQL Server for the qualifications corresponding to employees(i.e. One qualification entry corresponding one emp code and Qual. Code combination) there might be multiple entries corresponding to one emp code.
I have been trying
UPDATE @emp_mis
SET qualification = COALESCE(@Names + ', ', ' ') + dtl.u_qualification_description,
    specialization = dbo.cmn40_quickcode_desc(@hrou, 'GEN', 'SPLZ', quvw.specialization_code, 1)
FROM hrcmn_epin_qualfn_vw qual (NOLOCK),
     hrgm_qual_lang_dtl dtl (NOLOCK),
     @emp_mis mis,
     hrcmn_qualification_vw quvw (NOLOCK)
--epin_primary_achievement pach (NOLOCK)
WHERE qual.employee_code = mis.emp_code
    AND dtl.qualification_code = qual.achievement_code
    AND dtl.language_code = 1
    AND qual.achievement_code = quvw.qualification_code

but this query is only displaying last qualification.
But I want in for of Q1,Q2,Q3,Q4 corresponding to employee code.


text:
Q: How to destroy inline CKEditor with jQuery Let's say that this is code I have:

// This is working for me
$('.editor').click(function(){
   $(this).ckeditor();
});

// This is the problem
$('.editor').on('focusout', function(){
   $(this).ckeditorDestroy(); // What will destroy ckeditor?
});

I know that this function doesn't exists, but I didn't found nothing what was working?

A: HTML

Editor 1!

Editor 2!

JS
CKEDITOR.disableAutoInline = true;

$( '.editor' ).click( function(){
    $( this ).ckeditor( function() {
        console.log( 'Instance ' + this.name + ' created' );
    }, {
        on: {
            blur: function( evt ) {
                console.log( 'Instance ' + this.name + ' destroyed' );
                this.destroy();
            }
        }
    } );
} );

Use editor#blur event rather than focusout or similar because i.e opening editor dialog does not mean that editor is blurred, while focusout may be fired in such case. It's much safer. More about jQuery adapter.

A: Try doing this:
$('.editor').on('focusout', function(){
   $(this).ckeditor(function(){
        this.destroy();
    });
});

A: I did it like this with ES6. For ES5, swap instance.attr("title").includes(name) with instance.attr("title").indexOf(name) !== -1;
function disableCKEDITORInstance(instance) {
    var instance = $(instance);
    instance.removeClass("selected");
    instance.attr("contenteditable", "false");
    for(name in CKEDITOR.instances) {
        if (instance.attr("title").includes(name)){
            CKEDITOR.instances[name].destroy(true);
        }
    }
}


text:
Q: %TYPE issue in copying datatype in Postgres Functions When I declare a function in postgres as the following
CREATE OR REPLACE FUNCTION "Test_schema".FN_SI_FLOWS ( in_FLOW_ID "Test_schema".FLOWS.FLOW_ID%TYPE)
---
--
END;
$$ LANGUAGE plpgsql;

Its throwing me the following error:

ERROR:  column "flow_id" of relation "flows" does not exist SQL state:
  42703

Although we have a table called FLOWS in which we have FlOW_ID as column.


text:
Q: Alternative for svn_buildbot.py that does not require twisted? I am running some Continuous Integration servers. Source repository is hosted on Subversion, and buildbot does the job of compiling and testing after every commit. My trouble is that I had recently to migrate the SVN server to a RedHat5 system. RedHat5 does not distribute twisted, nor zope (essential components of buildbot). Thus, the post-commit hook script of SVN cannot run svn_buildbot.py, the script that triggers the buildbot after each commit.
Does anyone knows about an alternative to the svn_builbot.py script that could trigger the buildbot, but that does not require twisted and zope?

A: If you're using buildbot >0.8.2, you can enable the change_hook feature in WebStatus and use post_build_request.py in your SVN post_commit script to trigger the build via an HTTP request.
If you're stuck with an older version of buildbot or cannot enable change_hook for security reasons, then I'd say your options are:

*

*Using SVNpoller to have the buildbot master poll your SVN server for changes

*Have your post-commit hook send emails to your buildbot master host, then use SVNCommitEmailMailDirSource.

*Compile Twisted from source. I've deployed several buildbot installations on RHEL4 and RHEL5 servers this way without any issues.

A: Rather than compiling directly from source, I'd suggest using something like virtualenv and pip.


text:
Q: Display 2 fields in a cell in SonataAdminBundle I cannot find the answer to this anywhere on the web. How do I configure the ListMapper in SonataAdminBundle to show 2 fields in one cell?
I have an entity User with fields firstname and lastname. This code displayes them in separate cell
$listMapper
->addIdentifier('firstname')
->add('lastname')
->add('enabled');

How can I configure it to show both firstname and lastname in same cell?

A: One hacky solution is to add a method to your entity (or its variation):
public function getFullName() {
    return $this->getFirstName() . ' ' . $this->getLastName();
}

and then use:
->add('fullName')


text:
Q: How to execute some commands on non zero exit code? I am running the following command:
OLDIFS=$IFS
IFS=$'\n'
for i in $(find $HOME/test -maxdepth 1 -type f); do
    if [ $? -eq 0 ]; then
        telegram-upload --to 12345 --directories recursive --large-files split --caption '{file_name}' $i &&
            rm $i
    fi
done
IFS=$OLDIFS

If the telegram upload command exits with a non zero code I intend to do the following:
rm somefile && wget someurl && rerun the whole command
How do I go about doing something like this?

A: It's straightforward: Do an endless loop, which you break out once you succeed:
for i in $(find $HOME/test -maxdepth 1 -type f)
do
  while true
  do
    if telegram-upload --to 12345 --directories recursive --large-files split --caption '{file_name}' $i
    then
      break
    else
      rm somefile && wget someurl
    fi
  done
done

UPDATE : For completeness, I added the loop over the files as well. Note that your approach of looping over the files will fail, if you have files where the name contains white space. However this is already a problem in your own approach and not part of the question, so I don't discuss this here.

A: I believe you can capture the exit code as follows:
exit_code=$(telegram-upload --to 12345 ...)

From here, you can use the variable $exit_code as a regular variable,
like if [ $exit_code -eq 0 ]; then).