You can download the latest Plugin Manager version PluginManager_latest_version_x64.zip.
Unzip the file.
Copy
PluginManager_latest_version_x64.zip\updater\gpup.exe
into
path-to-installed-notepad\notepad++\updater\
PluginManager_latest_version_x64.zip\plugins\PluginManager.dll
into
path-to-installed-notepad\notepad++\plugins\
Try with JSToolNpp and follow the snap like this then Plugins | JSTool | JSFormat.
View -> Show Symbol -> uncheck Show End of Line.
Here are the steps that worked for me:
C:\Program Files\Notepad++\plugins
Settings -> Import -> Import plugin
(import the plugin).Use CTRL+D
at each line and it will find the matching words and select them then you can use multiple cursors.
You can also use find to find all the occurrences and then it would be multiple cursors too.
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
You need the textFX plugin. Then, just follow these instructions:
Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.
Personally, I would use sort -i -u source >dest instead of notepad++
Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"
and format to .json
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
If we need to check Edge please go head with this
if(navigator.userAgent.indexOf("Edge") > 1 ){
//do something
}
Go to the Preferences tab (menu File → Settings), and then search as “word wrap”. The following animated image is helpful too.
Another option is using command line:
code -d left.txt right.txt
Note: You may need to add code
to your path first. See: How to call VS Code Editor from command line
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CsvFile {
public static void main(String[]args){
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("NewData.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder builder = new StringBuilder();
String columnNamesList = "Id,Name";
// No need give the headers Like: id, Name on builder.append
builder.append(columnNamesList +"\n");
builder.append("1"+",");
builder.append("Chola");
builder.append('\n');
pw.write(builder.toString());
pw.close();
System.out.println("done!");
}
}
One click solution simply install open-in-browser Extensions from the Visual Studio marketplace.
Just want to add these back slashes to previous answers, I am on Windows 10 CMD, and it doesn't work without back slashes before the spaces.
git config --global core.editor "C:\\Users\\your_user_name\\AppData\\Local\\Programs\\Microsoft\ VS\ Code\\Code.exe"
Per the docs:
Mac OS X
- Download Visual Studio Code for Mac OS X.
- Double-click on VSCode-osx.zip to expand the contents.
- Drag Visual Studio Code.app to the Applications folder, making it available in the Launchpad.
- Add VS Code to your Dock by right-clicking on the icon and choosing Options, Keep in Dock.
Tip: If you want to run VS Code from the terminal, append the following to your ~/.bash_profile file (~/.zshrc in case you use zsh).
code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}
Now, you can simply type code . in any folder to start editing files in that folder.
Tip: You can also add it to VS Code Insiders build by changing "com.microsoft.VSCodeInsiders". Also if you don't to type the whole word code, just change it to c.
Linux
- Download Visual Studio Code for Linux.
- Make a new folder and extract VSCode-linux-x64.zip inside that folder.
- Double click on Code to run Visual Studio Code.
Tip: If you want to run VS Code from the terminal, create the following link substituting /path/to/vscode/Code with the absolute path to the Code executable
sudo ln -s /path/to/vscode/Code /usr/local/bin/code
Now, you can simply type code . in any folder to start editing files in that folder.
There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.
Alternatively you can install a specialized file compare software like WinMerge.
I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.
Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.
You can do using a simple notepad and save as FILENAME.json
That's all.
For me it helped to stop the installation service forcefully using task manager. If Visual Studio was installed in Features & Programs then uninstall it, restart computer and try to install it again.
When starting the installation make sure to be have reliable internet connection
Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!
@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call
:: help
if '%1' =='-h' (
echo.
echo %~n0
echo.
echo Runs a command on one or many remote machines. If no input parameters
echo are given you will be asked for a target remote machine.
echo.
echo You will be prompted for remote credentials with elevated privileges.
echo.
echo UNC paths and local paths can be supplied.
echo Commands will be executed on the remote side just the way you typed
echo them, so be sure to mind extensions and the path variable!
echo.
echo Please note that PsExec.exe must be allowed on remote machines, i.e.
echo not blocked by firewall or antivirus solutions.
echo.
echo Syntax: %~n0 [^<inputfile^>]
echo.
echo inputfile = a plain text file ^(one hostname or ip address per line^)
echo.
echo.
echo Example:
echo %~n0 mylist.txt
exit /b 0
)
:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
cls
echo ERROR: This script requires elevated privileges!
echo.
echo Launch by Right-Click / Run as Administrator ...
pause
exit /b 1
) else (
rd /s /q "%ADMINTESTDIR%"
echo Running with elevated privileges...
)
echo.
:checkRequirements
if not exist "%~dp0PsExec.exe" (
echo PsExec.exe from Sysinternals/Microsoft not found
echo in %~dp0
echo.
echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
echo.
pause
exit /B
)
:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory: %cd%\
echo Script directory: %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator :
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password :
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1
:inputMultipleTargets
if not exist %REMOTE_LIST% (
echo File %REMOTE_LIST% not found
goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
echo Access denied %REMOTE_LIST%
goto menu
)
set batchProcessing=true
echo Batch processing: %REMOTE_LIST% ...
ping -n 2 127.0.0.1 >nul
goto runOnce
:menu
if exist "%~dp0last.computer" set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing" set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command" set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo (1) select target computer [default]
echo (2) select multiple computers
echo -----------------------------------
echo last target : %LAST_COMPUTER%
echo last listing: %LAST_LISTING%
echo last path : %LAST_DIRECTORY%
echo last command: %LAST_COMMAND%
echo last run : %LAST_TIMESTAMP%
echo -----------------------------------
echo (0) exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...):
if NOT DEFINED mychoice goto promptSingleTarget
if "%mychoice%"=="1" goto promptSingleTarget
if "%mychoice%"=="2" goto promptMultipleTargets
if "%mychoice%"=="0" goto end
goto mychoice
:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename :
goto inputMultipleTargets
:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer :
goto runOnce
:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder :
SET /P REMOTE_CMD=Command with params:
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle
:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart
:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart
:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu
:end
SET REMOTE_USER=
SET REMOTE_PASS=
Building on Constantin's answer, here's the essence of what I learned while transitioning to Notepad++ as my primary HTML editor.
Install Notepad++ 32-bit
There's no 64-bit version of Tidy2 and some other popular plugins. The 32-bit version of NPP has few practical downsides, so axe the 64-bit version.
Install the Plugin Manager
Plugin Manager isn't strictly necessary for plugin usage. It does make things much easier, though.
Plugin Manager was eliminated from the core package apparently because the developer didn't like some included attribution linking.
You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.
It's a manual install, but it's not difficult.
C:\Program Files (x86)\Notepad++
. Now you'll see a new entry under Plugins for Plugin Manager.
Install Tidy2 (or your preferred alternative)
In Plugin Manager, check the box for Tidy2. Click Install. Restart when prompted.
To use Tidy2, select one of the preconfigured profiles in its Plugins submenu item, or create your own.
You are mixing tabs and spaces. Don't do that. Specifically, the __init__
function body is indented with tabs while your on_data
method is not.
Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:
You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.
Run your code with:
python -tt scriptname.py
and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.
If you are using the free software R, you can open the matlab files in Rstudio. Very easy!
You may need admin access to do it on your system.
C:\Program Files (x86)\Notepad++
themes
folder.
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
Local Windows 10 ActiveMQ server :
@echo off
start /min "" "C:\Install\apache-activemq\5.15.10\bin\win64\activemq.bat" start
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
Use scp priv_key.pem source user@host:target
if you need to connect using a private key.
or if using pscp then use pscp -i priv_key.ppk source user@host:target
The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
This expression will search for non-ASCII values:
[^\x00-\x7F]+
Tick off 'Search Mode = Regular expression', and click Find Next.
Source: Regex any ASCII character
I had the same issue and it was to do with my file name. If you set the file location using CD in CMD, and then type DIR it will list the files in that directory. Check that the file name appears and check that the spelling and filename ending is correct.
It should be .java but mine was .java.txt. The instructions on the Java tutorials website state that you should select "Save as Type Text Documents" but for me that always adds .txt onto the end of the file name. If I change it to "Save as Type All Documents" it correctly saved the file name.
This solution is not an apt one, but serves purpose in some occasions.
First create a folder and add it to your system path. Go to the executable of whatever program you want to create alias for. Right click and send to Desktop( Create Shortcut). Rename the shortcut to whatever alias name is comfortable. Now, take the shortcut and place in your folder.
From run prompt you can type the shortcut name directly and you can have the program opened for you. But from command prompt, you need to append .lnk and hit enter, the program will be opened.
Replace (.*")\d+(")
With $1x$2
Where x
is your "value inside scopes".
In C/C++ sizeof
. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof
a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof
does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
EDIT: as others have pointed out, std::array
is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof
is failing the way it is, so I still think this is the better answer.
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message)
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
The pipe, |
, is a special-character in regex (meaning "or") and you'll have to escape it with a \
.
Using your current regex:
\|.*$
I've tried this in Notepad++, as you've mentioned, and it appears to work well.
I was having same problem. The above put me on the right track but was not quite correct in my case. What did work was closely related:
\x00
I've had this same problem for a while as I generate a fair number of ad-hoc reports from SQL Server and copy/paste them into Excel. I would also welcome a proper solution but my temporary workaround was to create a default macro in Excel which converts highlighted cells to Excel's datetime format, and assigned it to a hotkey (Shift-Ctrl-D in my case). So I open Excel, copy/paste from SSMS into a new Excel worksheet, highlight the column to convert and press Shift-Ctrl-D. Job done.
I use UltraEdit to edit large files. The maximum size I open with UltraEdit was about 2.5 GB. Also UltraEdit has a good hex editor in comparison to Notepad++.
if you got one of these error while compiling and running:
* NoClassDefFoundError
* Error: Could not find or load main class hello
* Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello
(wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- SOLUTIION -----------------------
the problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On Compiling process use this command:
javac -d . [FileName.java]
To Run the class please use this command:
java [Package].[ClassName]
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
Ctrl+A , Ctrl+Shift+U
should do the trick!
Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)
If you have bash (e.g. git bash), you can use the following script to convert from unix2dos:
ex filename.ext <<EOF
:set fileformat=dos
:wq
EOF
similarly, to convert from dos2unix:
ex filename.ext <<EOF
:set fileformat=unix
:wq
EOF
You can use the Environment class's static NewLine property to get the proper newline:
$errorMsg = "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
Just to note,
MixEdit is not completely free.
"This software is currently not licensed to any user and is running in evaluation mode. MIXEDIT may be downloaded and evaluated for free, however a license must be purchased for continued use."
Upon installation and use, a popup redirects to webpage - similar to SublimeText's unlicensed software pop-up message.
That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r
and, using c/c++ to parse text is not a good idea. try awk:
$awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
ID=0 Name=Filipe Age=19 Gender=M
ID=1 Name=Maria Age=20 Gender=F
ID=2 Name=Walter Age=60 Gender=M
For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.
Example of your code then becomes;
function AddtoCart() {
var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;
$row = $("#Items td:first").clone(true);
$cells = $row.find("td");
$cells.get(0).html( len );
$inp1 = $cells.get(1).find("input:first");
$inp1.attr("id", $inp1.attr("id") + len).val("");
$inp2 = $cells.get(2).find("input:first");
$inp2.attr("id", $inp2.attr("id") + len).val("");
$("#Items").append($row);
}
I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.
I would use the libraries already created specifically for js shopping carts if I were you though.
To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?
That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".
screenshot of the option for even quicker finding (or different language versions)
You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.
Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.
EDIT: my answer makes me think of the classic old man saying "when I was your age..."
To save and load an arraylist of public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
An alternative is to use StreamReader.
public void FunctionName(HttpPostedFileBase file)
{
string result = new StreamReader(file.InputStream).ReadToEnd();
}
You can use the command line cc.rnl ', '
of ConyEdit (a plugin) to replace new lines with the contents you want.
TASKLIST
does not set errorlevel.
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
should do the job, since ":" should appear in TASKLIST
output only if the task is NOT found, hence FIND
will set the errorlevel to 0
for not found
and 1
for found
Nevertheless,
taskkill /f /im "notepad.exe"
will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit
which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
Although keeping this in mind http://xkcd.com/1179/
In the end I decided to use the format YYYYMMDD
in all CSV files, which doesn't convert to date in Excel, but can be read by all our applications correctly.
Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.
I used to use the Notepad++ plugin, but not anymore.
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
Usually the problem is not closing brackets (}) or missing semicolon (;)
For Python2.7(windows32) I installed only pywin32-223. And I wrote simple python`s code:
import win32api
import time
import win32con
# simulate the pressing-DOWN "ARROW key" of 200 times
for i in range(200):
time.sleep(0.5)
win32api.keybd_event(0x28, 0,0,0)
time.sleep(.05)
win32api.keybd_event(0x28,0 ,win32con.KEYEVENTF_KEYUP ,0)
It can be checked if you run the code and immediately go to the notepad window (where the text already exists) and place the cursor on the top line.
This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.
In the end, piping the command through more did the trick.
setup.exe {arguments} | more
It seems your question is very much older. But I just saw it. I searched(not in google) and found My Answer.
So I am writing its solution so that others may get help from it.
Here is my solution.
Unlike the other answers, you don't need to setup environments.
all you need is just to write php index.php
if index.php
is your file name.
then you will see that, the file compiled and showing it's desired output.
For 32 bit Notepad++ only
Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.
It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.
For others facing this issue in Eclipse even with path set to JDK correctly, you need to remove the other JREs from Installed JREs.
Go to Window -> Preferences -> Java -> Installed JREs
Select unused JREs individually and Remove
It worked for me.
No. I don't see any advantage. Second one is more straitforward.
btw: Second style is found in every corners of JDK source.
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
Notepad++ has a very powerful editing capability. (Today I'm searching for the similar function in Sublime Text), but for Notepad++, just hold Alt when you drag the mouse. What you type will then replace the selected column on every line. To insert without replacing existing text, use Alt-Shift.
Include android:singleLine="true"
I hade a csv file named FAR_T_SNSA.csv that i wanted to import in oracle database directly. For this i have done the following steps and it worked absolutely fine. Here are the steps that u vand follow out:
HOW TO IMPORT CSV FILE IN ORACLE DATABASE ?
Create a table in sql with same column name as there were in .csv file. create table Billing ( iocl_id char(10), iocl_consumer_id char(10));
Create a Control file that contains sql*loder script. In notepad type the script as below and save this with .ctl extension, in selecting file type as All Types(*). Here control file is named as Billing. And the Script is as Follows:
LOAD DATA
INFILE 'D:FAR_T_SNSA.csv'
INSERT INTO TABLE Billing
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(
iocl_id,
iocl_consumer_id
)
Now in Command prompt run command:
Sqlldr UserId/Password
Control = “ControlFileName”
--------------------------------
Here ControlFileName is Billing.
If the text contains \r\n that need to be converted into new lines use the 'Extended' or 'Regular expression' modes and escape the backslash character in 'Find what':
Find what: \\r\\n
Replace with: \r\n
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
This is occurring due to how PHP treats overloaded properties in that they are not modifiable or passed by reference.
See the manual for more information regarding overloading.
To work around this problem you can either use a __set
function or create a createObject
method.
Below is a __get
and __set
that provides a workaround to a similar situation to yours, you can simply modify the __set
to suite your needs.
Note the __get
never actually returns a variable. and rather once you have set a variable in your object it no longer is overloaded.
/**
* Get a variable in the event.
*
* @param mixed $key Variable name.
*
* @return mixed|null
*/
public function __get($key)
{
throw new \LogicException(sprintf(
"Call to undefined event property %s",
$key
));
}
/**
* Set a variable in the event.
*
* @param string $key Name of variable
*
* @param mixed $value Value to variable
*
* @return boolean True
*/
public function __set($key, $value)
{
if (stripos($key, '_') === 0 && isset($this->$key)) {
throw new \LogicException(sprintf(
"%s is a read-only event property",
$key
));
}
$this->$key = $value;
return true;
}
Which will allow for:
$object = new obj();
$object->a = array();
$object->a[] = "b";
$object->v = new obj();
$object->v->a = "b";
Many answers refer to IDE's like Eclipse. However, the question relates to native development with Notepad++.
The core reason of the named error is a mismatch of the used Java Runtime Environment and used classes respectively libraries. The goal of the following descriptions is to compile without any additional installation.
1)
Check the definition in the PATH
variable. If there is defined:
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
and/or
C:\ProgramData\Oracle\Java\javapath
These paths link to java/javac with a fixed java version. You can check this versions in this folder with javac -version
. Result can be:
java version "1.8.0_231"
This means, Java version 8 is in use.
Replace this entries with %JAVA_HOME%\bin
.
If the JDK's was installed manually, check whether JAVA_HOME
is set in the environment. If not, add it, here e.g. with:
JAVA_HOME="C:\Program Files\Java\jdk1.7.0_80"
2)
I have build the project on command-line with gradle. In build.gradle
was defined:
android {
buildToolsVersion "24.0.1"
dependencies {
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:support-v4:23.0.1'
...
}
...
}
The used build-tools
dx-files are newer then other components. Therefore a modification is required:
buildToolsVersion "23.0.1"
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
In example 3 you don't modify the array. In all other examples you modify either the contents or the internal array pointer. This is important when it comes to PHP arrays because of the semantics of the assignment operator.
The assignment operator for the arrays in PHP works more like a lazy clone. Assigning one variable to another that contains an array will clone the array, unlike most languages. However, the actual cloning will not be done unless it is needed. This means that the clone will take place only when either of the variables is modified (copy-on-write).
Here is an example:
$a = array(1,2,3);
$b = $a; // This is lazy cloning of $a. For the time
// being $a and $b point to the same internal
// data structure.
$a[] = 3; // Here $a changes, which triggers the actual
// cloning. From now on, $a and $b are two
// different data structures. The same would
// happen if there were a change in $b.
Coming back to your test cases, you can easily imagine that foreach
creates some kind of iterator with a reference to the array. This reference works exactly like the variable $b
in my example. However, the iterator along with the reference live only during the loop and then, they are both discarded. Now you can see that, in all cases but 3, the array is modified during the loop, while this extra reference is alive. This triggers a clone, and that explains what's going on here!
Here is an excellent article for another side effect of this copy-on-write behaviour: The PHP Ternary Operator: Fast or not?
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search → Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:
Find What = (cat|town)
Filters = *.txt
Directory = enter the path of the directory you want to search in. You can check Follow current doc.
to have the path of the current file to be filled.
Search mode = Regular Expression
Run below 2 commands in PowerShell window
Set-ExecutionPolicy unrestricted
Unblock-File -Path D:\PowerShell\Script.ps1
Could you use online services like this ?
Update: (as per request)
Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html
In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...
So this solution helped me a lot:
/**
* getting CSV array with UTF-8 encoding
*
* @param resource &$handle
* @param integer $length
* @param string $separator
*
* @return array|false
*/
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
if (($buffer = fgets($handle, $length)) !== false)
{
$buffer = $this->autoUTF($buffer);
return str_getcsv($buffer, $separator);
}
return false;
}
/**
* automatic convertion windows-1250 and iso-8859-2 info utf-8 string
*
* @param string $s
*
* @return string
*/
private function autoUTF($s)
{
// detect UTF-8
if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
return $s;
// detect WINDOWS-1250
if (preg_match('#[\x7F-\x9F\xBC]#', $s))
return iconv('WINDOWS-1250', 'UTF-8', $s);
// assume ISO-8859-2
return iconv('ISO-8859-2', 'UTF-8', $s);
}
Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:
some;nice;value;"and;here;comes;combinated;value";and;some;others
explode will explode string into parts:
some
nice
value
"and
here
comes
combinated
value"
and
some
others
but str_getcsv will explode string into parts:
some
nice
value
and;here;comes;combinated;value
and
some
others
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n with ","
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
If your text contains blank lines in between you can use regular expression \n+ instead of \n
example:
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Beige
Replcae \n+ with "," (in regex mode)
AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
Now append "(double-quote) at the start and end
"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
for large numbers that display with scientific notation set format to just '#'
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate
In my Notepad++ 7.2.2
, the Preferences
section it's a bit different.
The option is located at: Settings
/ Preferences
/ Language
/ Replace by space
as in the Screenshot.
"Edit -> EOL Conversion". You can convert to Windows/Linux/Mac EOL there. The current format is displayed in the status bar.
This works and is even simpler. If you remove ECHO-s, it will be even smaller:
REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM
@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE
Since there are limited real answers I'll share this workaround. For really simple cases like your example you do it backwards...
From this
1
2
3
4
5
Replace \r\n
with " />\r\n<row id="
and you'll get 90% of the way there
1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5
Or is a similar fashion you can hack about data with excel/spreadsheet. Just split your original data into columns and manipulate values as you require.
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
| <row id=" | 1 | " /> |
Obvious stuff but it may help someone doing the odd one-off hack job to save a few key strokes.
I am doing it as below. This creates a 100x100 size image in the button independent of the input image.
drawable.bounds = Rect(0,0,100,100)
button.setCompoundDrawables(drawable, null, null, null)
Not using ScaleDrawable
either. Not using button.setCompoundDrawablesRelativeWithIntrinsicBounds()
solved my problem, as that seems to use intrinsic bounds (source image size) instead of the bounds you just set.
Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.
I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.
Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).
convertToUTF8.py
import os
import sys
from Npp import notepad # import it first!
filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
for fn in files:
if fn[-4:] == '.xml': # Specify type of the files
notepad.open(root + "\\" + fn)
notepad.runMenuCommand("Encoding", "Convert to UTF-8")
# notepad.save()
# if you try to save/replace the file, an annoying confirmation window would popup.
notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml'))
notepad.close()
After all, run the script
I met the issue before when using a fullscreen dialogFragment: there is always a padding while having set fullscreen. try this code in dialogFragment's onActivityCreated() method:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
Window window = getDialog().getWindow();
LayoutParams attributes = window.getAttributes();
//must setBackgroundDrawable(TRANSPARENT) in onActivityCreated()
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (needFullScreen)
{
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
}
Not exactly a solution but a workaround.
Notepad ++ doesn't provide any such feature by default. But you can use some online tools to autoformat text like https://www.freeformatter.com/xml-formatter.html.
It helps. :)
This will remove any number of blank lines
CTRL + H to replace
Select Extended search mode
replace all \r\n
with (space)
then switch to regular expression and replace all \s+
with \n
Simply, add following lines to your ~/.bash_profile
:
branch_show() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(branch_show)\[\033[00m\] $ "
In this way, you can have the current branch name in Terminal
Courtesy of Coderwall.com
Use start notepad.exe
.
More info with start /?
.
Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:
Ctrl + h to bring up the find replace dialog.
In the Find what:
text box include your regex: .*help.*\r?\n
(where the \r
is optional in case the file doesn't have Windows line endings).
Leave the Replace with:
text box empty.
Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All
and voila! All lines containing your search term help
have been removed.
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
Copy the project into your workspace, create new Android Application Project with the same name from eclipse file->new->project and voila.
You can find the shortcuts.xml
in AppData\Roaming\Notepad++\
path only when using the default settings. If you have backup configured, you can find and set the path in Preferences -> Backup -> Backup path
.
When these settings are applied, files in AppData directory won't be used.
As others have noted, in Notepad++ 6.0 and later, it is possible to use the "Replace" feature to delete all lines that begin with ";" or "#".
Tao provides a regular expression that serves as a starting point, but it does not account for white-space that may exist before the ";" or "#" character on a given line. For example, lines that begin with ";" or "#" but are "tabbed-in" will not be deleted when using Tao's regular expression, ^(#|;).*\r\n
.
Tao's regular expression does not account for the caveat mentioned in BoltClock's answer, either: variances in newline characters across systems.
An improvement is to use ^(\s)*(#|;).*(\r\n|\r|\n)?
, which accounts for leading white-space and the newline character variances. Also, the trailing ?
handles cases in which the last line of the file begins with #
or ;
, but does not end with a newline.
For the curious, it is possible to discern which type of newline character is used in a given document (and more than one type may be used): View -> Show Symbol -> Show End of Line.
Donning asbestos longjohns...
Yesterday my title with Packt Publications, Reactive Programming with JavaScript. It isn't really a Node.js-centric title; early chapters are intended to cover theory, and later code-heavy chapters cover practice. Because I didn't really think it would be appropriate to fail to give readers a webserver, Node.js seemed by far the obvious choice. The case was closed before it was even opened.
I could have given a very rosy view of my experience with Node.js. Instead I was honest about good points and bad points I encountered.
Let me include a few quotes that are relevant here:
Warning: Node.js and its ecosystem are hot--hot enough to burn you badly!
When I was a teacher’s assistant in math, one of the non-obvious suggestions I was told was not to tell a student that something was “easy.” The reason was somewhat obvious in retrospect: if you tell people something is easy, someone who doesn’t see a solution may end up feeling (even more) stupid, because not only do they not get how to solve the problem, but the problem they are too stupid to understand is an easy one!
There are gotchas that don’t just annoy people coming from Python / Django, which immediately reloads the source if you change anything. With Node.js, the default behavior is that if you make one change, the old version continues to be active until the end of time or until you manually stop and restart the server. This inappropriate behavior doesn’t just annoy Pythonistas; it also irritates native Node.js users who provide various workarounds. The StackOverflow question “Auto-reload of files in Node.js” has, at the time of this writing, over 200 upvotes and 19 answers; an edit directs the user to a nanny script, node-supervisor, with homepage at http://tinyurl.com/reactjs-node-supervisor. This problem affords new users with great opportunity to feel stupid because they thought they had fixed the problem, but the old, buggy behavior is completely unchanged. And it is easy to forget to bounce the server; I have done so multiple times. And the message I would like to give is, “No, you’re not stupid because this behavior of Node.js bit your back; it’s just that the designers of Node.js saw no reason to provide appropriate behavior here. Do try to cope with it, perhaps taking a little help from node-supervisor or another solution, but please don’t walk away feeling that you’re stupid. You’re not the one with the problem; the problem is in Node.js’s default behavior.”
This section, after some debate, was left in, precisely because I don't want to give an impression of “It’s easy.” I cut my hands repeatedly while getting things to work, and I don’t want to smooth over difficulties and set you up to believe that getting Node.js and its ecosystem to function well is a straightforward matter and if it’s not straightforward for you too, you don’t know what you’re doing. If you don’t run into obnoxious difficulties using Node.js, that’s wonderful. If you do, I would hope that you don’t walk away feeling, “I’m stupid—there must be something wrong with me.” You’re not stupid if you experience nasty surprises dealing with Node.js. It’s not you! It’s Node.js and its ecosystem!
The Appendix, which I did not really want after the rising crescendo in the last chapters and the conclusion, talks about what I was able to find in the ecosystem, and provided a workaround for moronic literalism:
Another database that seemed like a perfect fit, and may yet be redeemable, is a server-side implementation of the HTML5 key-value store. This approach has the cardinal advantage of an API that most good front-end developers understand well enough. For that matter, it’s also an API that most not-so-good front-end developers understand well enough. But with the node-localstorage package, while dictionary-syntax access is not offered (you want to use localStorage.setItem(key, value) or localStorage.getItem(key), not localStorage[key]), the full localStorage semantics are implemented, including a default 5MB quota—WHY? Do server-side JavaScript developers need to be protected from themselves?
For client-side database capabilities, a 5MB quota per website is really a generous and useful amount of breathing room to let developers work with it. You could set a much lower quota and still offer developers an immeasurable improvement over limping along with cookie management. A 5MB limit doesn’t lend itself very quickly to Big Data client-side processing, but there is a really quite generous allowance that resourceful developers can use to do a lot. But on the other hand, 5MB is not a particularly large portion of most disks purchased any time recently, meaning that if you and a website disagree about what is reasonable use of disk space, or some site is simply hoggish, it does not really cost you much and you are in no danger of a swamped hard drive unless your hard drive was already too full. Maybe we would be better off if the balance were a little less or a little more, but overall it’s a decent solution to address the intrinsic tension for a client-side context.
However, it might gently be pointed out that when you are the one writing code for your server, you don’t need any additional protection from making your database more than a tolerable 5MB in size. Most developers will neither need nor want tools acting as a nanny and protecting them from storing more than 5MB of server-side data. And the 5MB quota that is a golden balancing act on the client-side is rather a bit silly on a Node.js server. (And, for a database for multiple users such as is covered in this Appendix, it might be pointed out, slightly painfully, that that’s not 5MB per user account unless you create a separate database on disk for each user account; that’s 5MB shared between all user accounts together. That could get painful if you go viral!) The documentation states that the quota is customizable, but an email a week ago to the developer asking how to change the quota is unanswered, as was the StackOverflow question asking the same. The only answer I have been able to find is in the Github CoffeeScript source, where it is listed as an optional second integer argument to a constructor. So that’s easy enough, and you could specify a quota equal to a disk or partition size. But besides porting a feature that does not make sense, the tool’s author has failed completely to follow a very standard convention of interpreting 0 as meaning “unlimited” for a variable or function where an integer is to specify a maximum limit for some resource use. The best thing to do with this misfeature is probably to specify that the quota is Infinity:
if (typeof localStorage === 'undefined' || localStorage === null)
{
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage(__dirname + '/localStorage',
Infinity);
}
Swapping two comments in order:
People needlessly shot themselves in the foot constantly using JavaScript as a whole, and part of JavaScript being made respectable language was a Douglas Crockford saying in essence, “JavaScript as a language has some really good parts and some really bad parts. Here are the good parts. Just forget that anything else is there.” Perhaps the hot Node.js ecosystem will grow its own “Douglas Crockford,” who will say, “The Node.js ecosystem is a coding Wild West, but there are some real gems to be found. Here’s a roadmap. Here are the areas to avoid at almost any cost. Here are the areas with some of the richest paydirt to be found in ANY language or environment.”
Perhaps someone else can take those words as a challenge, and follow Crockford’s lead and write up “the good parts” and / or “the better parts” for Node.js and its ecosystem. I’d buy a copy!
And given the degree of enthusiasm and sheer work-hours on all projects, it may be warranted in a year, or two, or three, to sharply temper any remarks about an immature ecosystem made at the time of this writing. It really may make sense in five years to say, “The 2015 Node.js ecosystem had several minefields. The 2020 Node.js ecosystem has multiple paradises.”
Go to:
Settings -> Preferences You will see a dialog box. There click the Backup / Auto-completion tab where you can set the auto complete option :)
I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:
string.Empty.PadRight(totalLength, (char)32);
An alternative approach: Create all spaces manually within a custom method and call it:
private static string GetSpaces(int totalLength)
{
string result = string.Empty;
for (int i = 0; i < totalLength; i++)
{
result += " ";
}
return result;
}
And call it in your code to create white spaces: GetSpaces(14);
My problem was that Notepad++ was crashing on a file I had previously opened; I was unable to open the application at all. This blog post discusses how to delete the data from the "Sessions" file so that Notepad++ will open without having any prior files open:
From the blog post:
Method 1 - edit session.xml
- Open file session.xml in C:\Users\Username\AppData\Roaming\Notepad++ or %APPDATA%\Notepad++
- Delete its contents and save it
- Run Notepad++ , session.xml will get new content automatically
Method 2 - add the -nosession parameter to Notepad++ shortcut
- Create a desktop shortcut referring to your Notepad++ program, e.g. C:\Program Files\Notepad++\notepad++.exe
- Right click on this shortcut
- In the "Target" field add the -nosession parameter so the target field looks exaxtly like (apostrophes included too): "C:\Program Files\Notepad++\notepad++.exe" -nosession
- Save and run Notepad++ from this shortcut icon with no recent files
Note: This is not a permanent setting, this simply deletes the prior session's information / opened files and starts over.
Alternatively, if you know the file which is causing notepad++ to hang, you can simply rename the file and open notepad++. This will solve the problem.
I hadn't seen this solution listed when I was googling my problem so I wanted to add it here!
I spent 8 hours to do that. It is simple...
You shoud have a code like that:
private const int GENERIC_WRITE = 0x40000000;
//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;
Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.
I've had no issues committing a few files like this:
svn commit fileDir1/ fileDir2/ -m "updated!"
Use the predefined PHP_EOL
constant:
echo $clientid, ' ', $lastname, PHP_EOL;
The constant value will be set according to the line endings of the operating system where PHP is executing. On Linux, it will be "\n"
; on Windows, it will be "\r\n"
.
i also have same problem and solve it. Please go through the link
add your site to trusted zone and change following options in ie Tools Menu -> Internet Options -> Security -> Custom level -> "Initialize and script ActiveX controls not marked as safe for scripting"
CTRL+SHIFT+C in Eclipse + StatET and Rstudio.
now you have imported android.R
instead of your own R... Try to take a look on your "problems" view if you have errors in one of your xml files... get rid of the import android.R
and comment out all usages of R.*
Cleaning should help when your project has no other errors, so check your xml files or file naming in your res folders
Use System.Diagnostics.Process to launch an instance of Notepad.exe.
UniversalIndentGUI did the job for me, once configured properly as described above.
TextFX would not install and run correctly on an old PC I have running Windows XP. There are instructions above for manual installation of various DLL files, but I'd rather avoid any manual installation.
UniversalIndentGUI formatted some lines like this:
<ClockStatus>1
</ClockStatus>
And I would have preferred:
<ClockStatus>1</ClockStatus>
But the output is still much better than one long line!
If you don't care about row order (which I don't think you do), then you can use a Linux/FreeBSD/Mac OS X/Cygwin box and do:
$ cat yourfile | sort | uniq > yourfile_nodups
Then open the file again in Notepad++.
Well I'm not sure about the regex or your situation..
How about CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines and viola all blank line gone.
A side note - if the line is blank i.e. does not contain spaces, this will work
Look here for c#
https://msdn.microsoft.com/en-us/library/system.io.streamreader.currentencoding%28v=vs.110%29.aspx
string path = @"path\to\your\file.ext";
using (StreamReader sr = new StreamReader(path, true))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
//Test for the encoding after reading, or at least
//after the first read.
Console.WriteLine("The encoding used was {0}.", sr.CurrentEncoding);
Console.ReadLine();
Console.WriteLine();
}
This isn't quite the answer you were looking for, but it's the solution I came to when I had the same question.
I'm a pretty serious Notepad++ user, so don't take this the wrong way. I have started using NetBeans 8
to develop websites in addition to Notepad++ because you can set it to autoformat on save for all your languages, and there are a ton of configuration options for how the formatting looks, down to the most minute detail. You might look into it and find it is a worthy tool to use in conjunction with notepad++. It's also open source, completely free, and has a bunch of plugins and other useful things like automatically compiling Sass if you use that too. It's definitely not as quick as NP++ so it's not great for small edits, but it can be nice for a long coding session.
Taken from here:
You can use Notepad++ to accomplish this in three ways. Just so you know, Notepad++ is a more advanced version of Notepad, which supports syntax highlighting of different code files "out of the box" - PHP included!
Download & install it, fire it up, and load up your PHP file. You should automatically see it beautifully coloured (if not, because the file extension is something other than .php, go to Language -> PHP or Language -> P -> PHP).
If you need to change any of the colours, you can easily do so - just go to Settings -> Styler Configurator. From that menu, you can change the various highlighting and font options, to suit your needs - although the default usually suffices for most.
Then, go to Plugins -> NppExport. From there, you have three options you can consider:
Export to RTF Export to HTML Copy all formats to clipboard Start with the last one - "Copy all formats to clipboard" - which will copy the entire file with the highlighted syntax to the clipboard. Once you click it, then open Microsoft Word, and just hit paste! You should see the beautifully syntax-highlighted code. If something goes wrong, then you can try one of the other options (export to RTF/HTML), although I've never had a problem with the clipboard method.
Yes: simply press and hold the Alt key, click and drag to select the lines whose columns you wish to edit, and begin typing.
You can also go to Settings > Preferences..., and in the Editing tab, turn on multi-editing, to enable selection of multiple separate regions or columns of text to edit at once.
It's much more intuitive, as you can see your edits live as you type.
the simplest way, type in normal mode *
I also have these mappings to enable and disable
"highligh search enabled by default
set hlsearch
"now you can toggle it
nnoremap <S-F11> <ESC>:set hls! hls?<cr>
inoremap <S-F11> <C-o>:set hls! hls?<cr>
vnoremap <S-F11> <ESC>:set hls! hls?<cr> <bar> gv
Select word by clickin on it
set mouse=a "Enables mouse click
nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>
Bonus: CountWordFunction
fun! CountWordFunction()
try
let l:win_view = winsaveview()
let l:old_query = getreg('/')
let var = expand("<cword>")
exec "%s/" . var . "//gn"
finally
call winrestview(l:win_view)
call setreg('/', l:old_query)
endtry
endfun
" Bellow we set a command "CountWord" and a mapping to count word
" change as you like it
command! -nargs=0 CountWord :call CountWordFunction()
nnoremap <f3> :CountWord<CR>
Selecting word with mouse and counting occurrences at once: OBS: Notice that in this version we have "CountWord" command at the end
nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
Assuming you have a Z:
drive mapped:
Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++
You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".
The reasonable way how to launch apps from HTML is through url schemes. So you can launch email via mailto:
links and irc through irc:
links. Individual apps can implement these schemes, but I'm not sure WinMerge does this.
I recently came across Python 3 interpreter at CompileOnline.
You can also use you own computer built-in functions:
tree /a /f >tree.txt
any_name_you_want.BAT
tree.txt
that contains you directory TREE.Try the HTML5 editor written in HTML5 itself
I've made a single powerfull script that will:
-Compile and run multi language code like C
, C++
, Java
, Python
and C#
.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.
I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.
npp_console 1 //open console
NPP_CONSOLE - //disable output of commands
npe_console m- //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5 //set console colors
npp_save //save the file
cd $(CURRENT_DIRECTORY) //follow current directory
NPP_CONSOLE + //enable output
IF $(EXT_PART)==.c GOTO C //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C# //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT // else treat it as a text file and goto EXITSCRIPT
//C label
:C
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART) //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY: //print message on console
$(NAME_PART) //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT //finally exits
:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT
:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT
:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT
:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD: //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT
:EXITSCRIPT
// that's all, folks!
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
It would be a great feature to have in Notepad++. I use the following technique to extract all the matches out of a file:
powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]*" -AllMatches | % { $_.Matches } | select-object Value > output.txt
And if you'd like only the distinct matches in a sorted list:
powershell
select-string -Path input.txt -Pattern "[0-9a-zA-Z ]" -AllMatches | % { $_.Matches } | select-object Value -unique | sort-object Value > output.txt
As I can't use Macros in my Visual Studio 2013 I found a Visual Studio Plugin (I use it in 2012 and 2013). Duplicate Selection duplicates selections and whole Lines - they only need to be partial selected. The standard shortcut is ALT + D.
Ideone is the best site for the online code running, debugging and it provides extra performance stats also.
Without Sign Up, you can run code upto of maximum 5 sec, and for signup, upto a max of 15 sec. And for Signup, the code management and history is also too good.
However, it has some maximum amount of submissions per month for registered users.
www.ideone.com
It supports more than 40 languages, and is integrated with SPOJ and RecruitCoders.
I had exact same error message with IIS10 and Windows 10. I tried everything listed here (and other internet pages as well) but it did not fixed it. What solved the issue was to install .NET Core Hosting a second time (I choose "Repair" button).
I'm 100% confident this is what fixed it because I had to deploy the same website to other laptops as well (different brands but all Windows 10). The same error message (500.19) occurred and reinstalling bundle fixed it again.
jEdit:
With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.
Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.
I also wanted to run python files directly from Notepad++.
Most common option found online is using builtin option Run
. Then you have two options:
Run python file in console (in Windows it is Command Prompt) with code something like this (links: ):
C:\Path\to\Python\python.exe "$(FULL_CURRENT_PATH)"
(If your console window immediately closes after running then you can add cmd /k
to your code. Links: ) This works fine, and you can even run files in interactive mode by adding -i
to your code (links: ).
Run python program in IDLE with code something like this (links: , in these links C:\Path\to\Python\Lib\idlelib\idle.py
is used, but I am using C:\Path\to\Python\Lib\idlelib\idle.bat
instead, because idle.bat
sets the right current working directory automatically):
C:\Path\to\Python\Lib\idlelib\idle.bat "$(FULL_CURRENT_PATH)"
Actually, this doesn't run your program in IDLE Shell, but instead it opens your python file in IDLE Editor and then you need to click Run Module
(or click F5) to run the program. So it opens your file in IDLE Editor and then you need run it from there, which defeats the purpose of running python files from Notepad++.
But, searching online, I found option which adds '-r' to your code (links: ):
C:\Path\to\Python\Lib\idlelib\idle.bat -r "$(FULL_CURRENT_PATH)"
This will run your python program in IDLE Shell and because it is in IDLE it is by default in interactive mode.
Problem with running your python files via builtin Run
option is that
each time you run your python file, you open new console or IDLE window and lose all output from previous executions. This might not be important to some, but when I started to program in python, I used Python IDLE, so I got used to running python file multiple times in same IDLE Shell window. Also problem with running python programs from Notepad++ is that you need to manually save your file and then click Run
(or press F5). To solve these problems (AFAIK*) you need to use Notepad++ Plugins. The best plugin for running python files from Notepad++ is
NppExec. (I also tried PyNPP and Python Script. PyNPP runs python files in console, it works, but you can do that without plugin via builtin Run
option and Python Script is used for running scripts that interact with Notepad++ so you can't run your python files.) To run your python file with NppExec plugin you need to go to Plugins -> NppExec -> Execute
and then type in something like this (links: ):
C:\Path\to\Python\python.exe "$(FULL_CURRENT_PATH)"
With NppExec you can also save your python file before run with npp_save
command, set working directory with cd "$(CURRENT_DIRECTORY)"
command or run python program in interactive mode with -i
command. I found many links ( ) online that mention these options, but best use of NppExec to run python programs I found at NppExec's Manual which has chapter 4.6.4. Running Python & wxPython
with this code:
npp_console - // disable any output to the Console
npp_save // save current file (a .py file is expected)
cd "$(CURRENT_DIRECTORY)" // use the current file's dir
set local @exit_cmd_silent = exit() // allows to exit Python automatically
set local PATH_0 = $(SYS.PATH) // current value of %PATH%
env_set PATH = $(SYS.PATH);C:\Python27 // use Python 2.7
npp_setfocus con // set the focus to the Console
npp_console + // enable output to the Console
python -i -u "$(FILE_NAME)" // run Python's program interactively
npp_console - // disable any output to the Console
env_set PATH = $(PATH_0) // restore the value of %PATH%
npp_console + // enable output to the Console
All you need to do is copy this code and change your python directory if you use some other python version (e.g.* I am using python 3.4 so my directory is C:\Python34
). This code works perfectly, but there is one line I added to this code so I can run python program multiple times without loosing previous output:
npe_console m- a+
a+
is to enable the "append" mode which keeps the previous Console's text and does not clear it.
m-
turns off console's internal messages (those are in green color)
The final code that I use in NppExec's Execute window is:
npp_console - // disable any output to the Console
npp_save // save current file (a .py file is expected)
cd "$(CURRENT_DIRECTORY)" // use the current file's dir
set local @exit_cmd_silent = exit() // allows to exit Python automatically
set local PATH_0 = $(SYS.PATH) // current value of %PATH%
env_set PATH = $(SYS.PATH);C:\Python34 // use Python 3.4
npp_setfocus con // set the focus to the Console
npe_console m- a+
npp_console + // enable output to the Console
python -i -u "$(FILE_NAME)" // run Python's program interactively
npp_console - // disable any output to the Console
env_set PATH = $(PATH_0) // restore the value of %PATH%
npp_console + // enable output to the Console
You can save your NppExec's code, and assign a shortcut key to this NppExec's script. (You need to open Advanced options of NppExec's plugin, select your script in the Associated script
drop-down list, press the Add/Modify
, restart Notepad++ , go to Notepad++'es Settings
-> Shortcut Mapper
-> Plugin commands
, select your script, click Modify
and assign a shortcut key. I wanted to put F5
as my shortcut key, to do that you need to change shortcut key for builtin option Run
to something else first.) Links to chapters from NppExec's Manual that explain how to save you NppExec's code and assign a shortcut key: NppExec's "Execute..."
, NppExec's script
.
P.S.*: With NppExec plugin you can add Highlight Filters
(found in Console Output Filters...
) that highlight certain lines. I use it to highlight error lines in red, to do that you need to add Highlight masks
: *File "%FILE%", line %LINE%, in <*>
and Traceback (most recent call last):
like this.
Unlike proposed by Nicolas, the meta
tag isn’t actually ignored by the browsers. However, the Content-Type
HTTP header always has precedence over the presence of a meta
tag in the document.
So make sure that you either send the correct encoding via the HTTP header, or don’t send this HTTP header at all (not recommended). The meta
tag is mainly a fallback option for local documents which aren’t sent via HTTP traffic.
Using HTML entities should also be considered a workaround – that’s tiptoeing around the real problem. Configuring the web server properly prevents a lot of nuisance.
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Or, for 64-bit Windows and a 32-bit install of Notepad++:
git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Or, the following can be issued on the command line on either 32-bit or 64-bit Windows. It will pull the location of notepad++.exe from the registry and configure git to use it automatically:
FOR /F "usebackq tokens=2*" %A IN (`REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\notepad++.exe" /ve`) DO git config --global core.editor "'%B' -multiInst -notabbar -nosession -noPlugin"
If you wish to place the above from a .BAT or .CMD file, you must replace %A with %%A and %B with %%B
I'm using the JSON Viewer plug-in with NPP 5.9 and it seems to work well.
The problem with the new version of QuickText seems to be that it is set to react to the TAB key. Previously it was set to use CTRL-ENTER. If you change the key combination in the shortcut mapper then your TAB key should start working again, and QuickText should also work (with whatever new key you've assigned).
If you have double-encoded UTF8 characters (various smart quotes, dashes, apostrophe ’, quotation mark “, etc), in mysql you can dump the data, then read it back in to fix the broken encoding.
Like this:
mysqldump -h DB_HOST -u DB_USER -p DB_PASSWORD --opt --quote-names \
--skip-set-charset --default-character-set=latin1 DB_NAME > DB_NAME-dump.sql
mysql -h DB_HOST -u DB_USER -p DB_PASSWORD \
--default-character-set=utf8 DB_NAME < DB_NAME-dump.sql
This was a 100% fix for my double encoded UTF-8.
Source: http://blog.hno3.org/2010/04/22/fixing-double-encoded-utf-8-data-in-mysql/
>>> unicode_string = u"hello aåbäcö"
>>> unicode_string.encode("ascii", "ignore")
'hello abc'
Use Environment.NewLine for line breaks.
There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash
:
You can run Bash script like bash ./script.sh
, but keep in mind that C drive is located at /mnt/c
, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.
Also, even as root
, you can still get permission denied when moving files around in /mnt
, but you have your full root
power in the /
file system.
Also make sure your shell script is formatted with Unix style, or there can be errors.
First, given that you have a complex data retrieval scenario, are you sure even SQLite is overkill?
You'll end up having an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLite, paraphrasing Greenspun's Tenth Rule.
That said, you are very right in saying that choosing a single data structure will impact one or more of searching, sorting or counting, so if performance is paramount and your data is constant, you could consider having more than one structure for different purposes.
Above all, measure what operations will be more common and decide which structure will end up costing less.
This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.
You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.
This is the most common feature of Notepad++ that I use to update my code.
All you need to do is:
You can refer to this link for pictorial explanation.
http://www.downloadorinstall.com/best-notepad-tips-and-tricks-for-faster-work-and-development/
As part of the solution that Larry K suggested, registering your own protocol might be a possible solution. The web page could contain a simple link to download and install the application - which would then register its own protocol in the Windows registry.
The web page would then contain links with parameters that would result in the registerd program being opened and any parameters specified in the link being passed to it. There's a good description of how to do this on MSDN
Lots of people have suggested POSIX sleep
, Windows Sleep
, Windows system("pause")
, C++ cin.get()
… there's even a DOS getch()
in there, from roughly the late 1920s.
Please don't do any of these.
None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)
Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.
Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.
An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram>
or <myprogram>
, to cmd.exe /K <myprogram>
. The /K
switch to cmd.exe
makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit
or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.
I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.
System.Windows.Forms.Clipboard.SetText
(Windows Forms) or System.Windows.Clipboard.SetText
(WPF)
Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion
Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");
props.load(new InputStreamReader(resource.openStream(), "UTF8"));
this works well in java 1.6. How can i do this in 1.5, Since Properties class does not have a method to pars InputStreamReader
.
use EmEditor, it's pretty good, i used it to open a file with more than 500mb
echo "text to echo" > file.txt
Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:
Menu View ? Show Symbol ? *Show All Characters`
or
Menu View ? Show Symbol ? Show White Space and TAB
(Thanks to bers' comment and bkaid's answers below for these updated locations.)
On older versions you can look for:
Menu View ? Show all characters
or
Menu View ? Show White Space and TAB
Another interesting solution to luch an exeternal application with a WinForm container is the follow:
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private void Form1_Load(object sender, EventArgs e)
{
ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
psi.WindowStyle = ProcessWindowStyle.Minimized;
Process p = Process.Start(psi);
Thread.Sleep(500);
SetParent(p.MainWindowHandle, panel1.Handle);
CenterToScreen();
psi.WindowStyle = ProcessWindowStyle.Normal;
}
The step to ProcessWindowStyle.Minimized
from ProcessWindowStyle.Normal remove the annoying delay.
In command mode position the cursor on the line you want to move down, and then
ddp
Explanation: dd deletes the current line to the general buffer p puts it back AFTER the cursor position, or in case of entire lines, one line below.
There is some confusion regarding commands p and P in many docs. In reality p pastes AFTER cursor, and P AT cursor.
You may also try the Default encoding, which uses the current system's ANSI codepage.
StreamReader reader = new StreamReader(inputFilePath, Encoding.Default, true)
When you try using the Notepad "Save As" menu with the original file, look at the encoding combo box. It will tell you which encoding notepad guessed is used by the file.
Also, if it is an ANSI file, the detectEncodingFromByteOrderMarks parameter will probably not help much.
We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).
We chose it for the following reasons:
I should mention, this is speaking from an ASP.NET development point of view
I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail
from what I can tell.
So we have a library which wraps log4net and within our code we just need stuff like this:
Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());
try {
var i = int.Parse("Hello World");
} catch(FormatException, ex) {
Logger.Instance.Error(ex);
}
Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:
Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
This will become:
if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
(Save a bit of execusion time)
By default we log at two locations:
Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.
I find Notepad works just fine for reading logs.
You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".
For String.Format, which is similar, if you had something like
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
you'd create a string "This is a test. The value is 42".
You can also use expressions, and print values out multiple times:
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
yielding "Fib: 1, 1, 2, 3"
See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.
I just posted a Notepad++ plugin to convert tabs to spaces. Yes, it converts tabs in the middle of a line. Yes, it takes into account other characters within the tabbed field. Check it out.
In the latest version (at least), you can find it through:
[EDIT] Though, I don't think it's had the best implementation of Auto-indent. So, check to make sure you have version 5.1 -- auto-indent got an overhaul recently, so it auto-corrects your indenting.
Do also note that you're missing the block for the 2nd if
:
void main(){
if(){
if() { } # here
}
}
This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!
Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.
To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).
My personal experience is that shortcuts.xml is overwritten with the initially loaded + later recorded macros and settings when Notepad++ exits. So you can't use Notepad++ itself for editing this file.
Close Notepad++, edit shortcuts.xml by another tool, save it and restart Notepad++.
open up the AssemblyInfo.cs file and change
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
to
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
you can do this in IDE by going to project -> properties -> assembly information
This however will only allow you to auto increment the Assembly version and will give you the
Assembly File Version: A wildcard ("*") is not allowed in this field
message box if you try place a * in the file version field.
So just open up the assemblyinfo.cs and do it manually.
You can use html2text method in the stripogram library also.
from stripogram import html2text
text = html2text(your_html_string)
To install stripogram run sudo easy_install stripogram
There are two problems with your original solution. Firstly, your example text:
<option value value='1' >A
has two occurences of the "value" word. Your regex does not. Also, you need to escape the opening brace in the quantifier of your regex or Vim will interpret it as a literal brace. This regex works:
:%s/<option value value='.\{1,}' >//g
Why don't you use the Notepad++ multiline editing capabilities?
Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.
You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.
Also defragment your disk. Netbeans is very aggressive about creating caches of one form or another. Most of them get persisted to disk at some point or another which can affect startup time. Virus scanners (Symantec in particular), Desktop search engines, and any other intrusive I/O product can drastically reduce performance.
I have noticed that Netbeans can be tempermental at times and its performance can vary greatly between two machines with nearly identical specs. My work machine has terrible performance and is unusable at times, but it's lightning fast when I use it on my home machine (with bigger projects in many cases).
I suspect it's the same problem as when you use shortcuts in Windows... Try this:
import os;
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");
Another method to reindent XML in Notepad++:
From menu select Plugins -> XML Tools -> Pretty print (XML only – with line breaks)
or press Ctrl+Alt+Shift+B.
Use the advanced search option (Ctrl + R) and use the keyboard shortcut for CRLF (Ctrl + M) to insert a carriage return.
If you are using MS Word then try ALT+E, S, U, Enter (Uses the Paste Special)
For PHP in particular, PHPEdit is the best, and I tried and worked in some of them including, Dreamweaver, Elipse, Emacs, Notepad++, NetBeans, UltraEdit ...
I've done something similar in Python. Basically, you need lots of sample data from various encodings, which are broken down by a sliding two-byte window and stored in a dictionary (hash), keyed on byte-pairs providing values of lists of encodings.
Given that dictionary (hash), you take your input text and:
If you've also sampled UTF encoded texts that do not start with any BOM, the second step will cover those that slipped from the first step.
So far, it works for me (the sample data and subsequent input data are subtitles in various languages) with diminishing error rates.
Um, that's because Visual Studio is the best IDE. Come back to the darkside.
jd-gui is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.
This seems to do what you want (I found it on http://huddledmasses.org/powershell-find-path/):
Function Find-Path($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
## You could comment out the function stuff and use it as a script instead, with this line:
#param($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
if($(Test-Path $Path -Type $type)) {
return $path
} else {
[string[]]$paths = @($pwd);
$paths += "$pwd;$env:path".split(";")
$paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
if($paths.Length -gt 0) {
if($All) {
return $paths;
} else {
return $paths[0]
}
}
}
throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path
I managed to get the environment version working by setting the EDITOR variable using quotes and /
:
EDITOR="c:/Program Files (x86)/Notepad++/notepad++.exe"
In ~/.subversion/auth/svn.simple/
you should find a file with a long hexadecimal name. The password is in there in plaintext.
If there is more than one file you'll need to find that one that references the server you need the password for.
<!--Customize button -->
<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
<GradientStop Color="#5e5e5e" Offset="1" />
<GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush>
<Style x:Key="hhh" TargetType="{x:Type Button}">
<Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
<Border.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
</Border.Effect>
<Grid>
<Path Width="9" Height="16.5" Stretch="Fill" Fill="#000" HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">
</Path>
<Path x:Name="PathIcon" Width="8" Height="15" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
<Path.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
</Path.Effect>
</Path>
<Line HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#E59400" />
<Setter Property="Foreground" Value="White" />
<Setter TargetName="PathIcon" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I. Plain XSLT 1.0 solution:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()" name="split">
<xsl:param name="pText" select="."/>
<xsl:if test="string-length($pText)">
<xsl:if test="not($pText=.)">
<br />
</xsl:if>
<xsl:value-of select=
"substring-before(concat($pText,';'),';')"/>
<xsl:call-template name="split">
<xsl:with-param name="pText" select=
"substring-after($pText, ';')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
produces the wanted, corrected result:
123 Elm Street<br />PO Box 222<br />c/o James Jones
II. FXSL 1 (for XSLT 1.0):
Here we just use the FXSL template str-map
(and do not have to write recursive template for the 999th time):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
<xsl:import href="str-dvc-map.xsl"/>
<testmap:testmap/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
<xsl:call-template name="str-map">
<xsl:with-param name="pFun" select="$vTestMap"/>
<xsl:with-param name="pStr" select=
"'123 Elm Street;PO Box 222;c/o James Jones'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="replace" mode="f:FXSL"
match="*[namespace-uri() = 'testmap']">
<xsl:param name="arg1"/>
<xsl:choose>
<xsl:when test="not($arg1=';')">
<xsl:value-of select="$arg1"/>
</xsl:when>
<xsl:otherwise><br /></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:
123 Elm Street<br/>PO Box 222<br/>c/o James Jones
III. Using XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()">
<xsl:for-each select="tokenize(.,';')">
<xsl:sequence select="."/>
<xsl:if test="not(position() eq last())"><br /></xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
the wanted, correct result is produced:
123 Elm Street<br />PO Box 222<br />c/o James Jones
Specify POST method in form
<form name="registrationform" action="register.php" method="post">
your form code
</form>
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';
$array = array_values($array);
through this function you can reset your array
$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Templates (<template>
, or <ng-template>
since 4.x) are added as embedded views and get passed a context.
With let-col
the context property $implicit
is made available as col
within the template for bindings.
With let-foo="bar"
the context property bar
is made available as foo
.
For example if you add a template
<ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
See also this answer and ViewContainerRef#createEmbeddedView.
*ngFor
also works this way. The canonical syntax makes this more obvious
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
where NgFor
adds the template as embedded view to the DOM for each item
of items
and adds a few values (item
, index
, odd
) to the context.
The best way to do this in my opinion is to use python's itertools
package.
>>>import itertools
>>>l1 = [1,2,3]
>>>l2 = [10,20,30]
>>>[l*2 for l in itertools.chain(*[l1,l2])]
[2, 4, 6, 20, 40, 60]
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
Unless you actually need a copy it's still reasonable to take const &
. For example:
bool isprint(std::string const &s) {
return all_of(begin(s),end(s),(bool(*)(char))isprint);
}
If you change this to take the string by value then you'll end up moving or copying the parameter, and there's no need for that. Not only is copy/move likely more expensive, but it also introduces a new potential failure; the copy/move could throw an exception (e.g., allocation during copy could fail) whereas taking a reference to an existing value can't.
If you do need a copy then passing and returning by value is usually (always?) the best option. In fact I generally wouldn't worry about it in C++03 unless you find that extra copies actually causes a performance problem. Copy elision seems pretty reliable on modern compilers. I think people's skepticism and insistence that you have to check your table of compiler support for RVO is mostly obsolete nowadays.
In short, C++11 doesn't really change anything in this regard except for people that didn't trust copy elision.
var noHtml = Regex.Replace(inputHTML, @"<[^>]*(>|$)| |‌|»|«", string.Empty).Trim();
I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.
Try to hit the below URL in any browser. It will return 501
http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom
Please try with https. It will download a pom.xml file:
https://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom
Please add it (https://repo.maven.apache.org/maven2) in the setting.xml file:
<repositories>
<repository>
<id>Central Maven repository</id>
<name>Central Maven repository https</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$
I have created the above regex starting from this solution
I use the readonly
attribute instead of disabled
attribute - as this will still submit the value when the field is readonly.
Note: Any presence of the readonly attribute will make the field readonly
even if set to false, so hence why I branch the editor for code like below.
@if (disabled)
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control", @readonly = "" } })
}
else
{
@Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
}
For Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
You've got to override your Canvas's paint(Graphics g)
method and perform your drawing there. See the paint() documentation.
As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.
I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone
rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that "bottom-up is memoization" ("assume the subproblems"), it may be the inverse (that is, "top-down" may be "assume the subproblems" and "bottom-up" may be "compose the subproblems"). Previously, I have read on memoization being a different kind of dynamic programming as opposed to a subtype of dynamic programming. I was quoting that viewpoint despite not subscribing to it. I have rewritten this answer to be agnostic of the terminology until proper references can be found in the literature. I have also converted this answer to a community wiki. Please prefer academic sources. List of references: {Web: 1,2} {Literature: 5}
Dynamic programming is all about ordering your computations in a way that avoids recalculating duplicate work. You have a main problem (the root of your tree of subproblems), and subproblems (subtrees). The subproblems typically repeat and overlap.
For example, consider your favorite example of Fibonnaci. This is the full tree of subproblems, if we did a naive recursive call:
TOP of the tree
fib(4)
fib(3)...................... + fib(2)
fib(2)......... + fib(1) fib(1)........... + fib(0)
fib(1) + fib(0) fib(1) fib(1) fib(0)
fib(1) fib(0)
BOTTOM of the tree
(In some other rare problems, this tree could be infinite in some branches, representing non-termination, and thus the bottom of the tree may be infinitely large. Furthermore, in some problems you might not know what the full tree looks like ahead of time. Thus, you might need a strategy/algorithm to decide which subproblems to reveal.)
There are at least two main techniques of dynamic programming which are not mutually exclusive:
Memoization - This is a laissez-faire approach: You assume that you have already computed all subproblems and that you have no idea what the optimal evaluation order is. Typically, you would perform a recursive call (or some iterative equivalent) from the root, and either hope you will get close to the optimal evaluation order, or obtain a proof that you will help you arrive at the optimal evaluation order. You would ensure that the recursive call never recomputes a subproblem because you cache the results, and thus duplicate sub-trees are not recomputed.
fib(100)
, you would just call this, and it would call fib(100)=fib(99)+fib(98)
, which would call fib(99)=fib(98)+fib(97)
, ...etc..., which would call fib(2)=fib(1)+fib(0)=1+0=1
. Then it would finally resolve fib(3)=fib(2)+fib(1)
, but it doesn't need to recalculate fib(2)
, because we cached it.Tabulation - You can also think of dynamic programming as a "table-filling" algorithm (though usually multidimensional, this 'table' may have non-Euclidean geometry in very rare cases*). This is like memoization but more active, and involves one additional step: You must pick, ahead of time, the exact order in which you will do your computations. This should not imply that the order must be static, but that you have much more flexibility than memoization.
fib(2)
,fib(3)
,fib(4)
... caching every value so you can compute the next ones more easily. You can also think of it as filling up a table (another form of caching).(At it's most general, in a "dynamic programming" paradigm, I would say the programmer considers the whole tree, then writes an algorithm that implements a strategy for evaluating subproblems which can optimize whatever properties you want (usually a combination of time-complexity and space-complexity). Your strategy must start somewhere, with some particular subproblem, and perhaps may adapt itself based on the results of those evaluations. In the general sense of "dynamic programming", you might try to cache these subproblems, and more generally, try avoid revisiting subproblems with a subtle distinction perhaps being the case of graphs in various data structures. Very often, these data structures are at their core like arrays or tables. Solutions to subproblems can be thrown away if we don't need them anymore.)
[Previously, this answer made a statement about the top-down vs bottom-up terminology; there are clearly two main approaches called Memoization and Tabulation that may be in bijection with those terms (though not entirely). The general term most people use is still "Dynamic Programming" and some people say "Memoization" to refer to that particular subtype of "Dynamic Programming." This answer declines to say which is top-down and bottom-up until the community can find proper references in academic papers. Ultimately, it is important to understand the distinction rather than the terminology.]
Memoization is very easy to code (you can generally* write a "memoizer" annotation or wrapper function that automatically does it for you), and should be your first line of approach. The downside of tabulation is that you have to come up with an ordering.
*(this is actually only easy if you are writing the function yourself, and/or coding in an impure/non-functional programming language... for example if someone already wrote a precompiled fib
function, it necessarily makes recursive calls to itself, and you can't magically memoize the function without ensuring those recursive calls call your new memoized function (and not the original unmemoized function))
Note that both top-down and bottom-up can be implemented with recursion or iterative table-filling, though it may not be natural.
With memoization, if the tree is very deep (e.g. fib(10^6)
), you will run out of stack space, because each delayed computation must be put on the stack, and you will have 10^6 of them.
Either approach may not be time-optimal if the order you happen (or try to) visit subproblems is not optimal, specifically if there is more than one way to calculate a subproblem (normally caching would resolve this, but it's theoretically possible that caching might not in some exotic cases). Memoization will usually add on your time-complexity to your space-complexity (e.g. with tabulation you have more liberty to throw away calculations, like using tabulation with Fib lets you use O(1) space, but memoization with Fib uses O(N) stack space).
If you are also doing a extremely complicated problems, you might have no choice but to do tabulation (or at least take a more active role in steering the memoization where you want it to go). Also if you are in a situation where optimization is absolutely critical and you must optimize, tabulation will allow you to do optimizations which memoization would not otherwise let you do in a sane way. In my humble opinion, in normal software engineering, neither of these two cases ever come up, so I would just use memoization ("a function which caches its answers") unless something (such as stack space) makes tabulation necessary... though technically to avoid a stack blowout you can 1) increase the stack size limit in languages which allow it, or 2) eat a constant factor of extra work to virtualize your stack (ick), or 3) program in continuation-passing style, which in effect also virtualizes your stack (not sure the complexity of this, but basically you will effectively take the deferred call chain from the stack of size N and de-facto stick it in N successively nested thunk functions... though in some languages without tail-call optimization you may have to trampoline things to avoid a stack blowout).
Here we list examples of particular interest, that are not just general DP problems, but interestingly distinguish memoization and tabulation. For example, one formulation might be much easier than the other, or there may be an optimization which basically requires tabulation:
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
The easiest solution for your case - change the first line, let it do just the opposite thing:
String lower = Name.toUpperCase ();
Of course, it's worth to change its name too.
From the git documentation:
Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:
$ git rm --cached readme.txt
So maybe don't include the "-r"?
Just use order by column number (don't use column name). Every query returns some columns, so you can order by any desired column using it's number.
Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.
swift 3
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
NSForegroundColorAttributeName : UIColor.white], for: .normal)
self.navigationItem.leftBarButtonItem = cancelBarButton
func cancelPressed(_ sender: UIBarButtonItem ) {
self.dismiss(animated: true, completion: nil)
}
for more extendability for large scale apps use oop style with encapsulated fields.
Simple way :-
class Fruit implements JsonSerializable {
private $type = 'Apple', $lastEaten = null;
public function __construct() {
$this->lastEaten = new DateTime();
}
public function jsonSerialize() {
return [
'category' => $this->type,
'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
];
}
}
echo json_encode(new Fruit()); //which outputs:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Real Gson on PHP :-
I'm going to expand your question a bit and also include the compile function.
compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link'
attribute is ignored if the 'compile'
attribute is defined.)
link function - normally use for registering listener callbacks (i.e., $watch
expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>
, the link function is executed after the <li>
template (tElement) has been cloned (into an iElement) for that particular <li>
element. A $watch
allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.
controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.
For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this
(rather than on $scope
), please see 'this' vs $scope in AngularJS controllers.
In general, you can put methods, $watches
, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.
#include<stdio.h>
int main ( ) {
printf( "hello " );
fprintf( stderr, "HELP!" );
printf( " world\n" );
return 0;
}
$ ./a.exe
HELP!hello world
$ ./a.exe 2> tmp1
hello world
$ ./a.exe 1> tmp1
HELP!$
stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.
Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.
run postgres -D /usr/local/var/postgres
and you should see something like:
FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?
Then run kill -9 PID
in HINT
And you should be good to go.
Just change the class container to container-fullwidth like this :
<div class="container-fullwidth">
The problem with your conditional is in this part sshkey_result.rc == 1
, because sshkey_result
does not contain rc
attribute and entire conditional fails.
If you want to check if file exists check exists
attribute.
Here you can read more about stat module and how to use it.
Please remove e.preventDefault()
, because event.cancelable
of touchmove is false
.
So you can't call this method.
Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', (function(marker) {
return function() {
var content = address;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker));
Just multiply the number by -1 and check if the result is positive.
import pandas as pd
dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])
>>> values[0]
'item_0'
edit:
actually, you can just index the dataset like any old array.
import pandas as pd
dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]
>>> print(first_value)
'item_0'
There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat()
, but that's way slower than just +
Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.
Simply put: +
is the fastest.
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
HttpPost req = new HttpPost(composeTargetUrl());
MultipartEntity entity = new MultipartEntity();
entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
try {
entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
req.setEntity(entity);
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
You can emulate the disabled attribute on a <a>
tag.
<a href="link.html" disabled="">Link</a>
a[disabled] {
pointer-events: none;
cursor: default;
}
Use this command to create debug.keystore
keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
if you need to call a controller from a view, maybe to load a partial view, you thinking as modular programming, and you should implement HMVC structure in lieu of plane MVC. CodeIgniter didnt implement HMVC natively, but you can use this useful library in order to implement HMVC. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup remember:that all your controllers should extends from MX_Controller in order to using this feature.
We can download a specified branch by using following magical command:
git clone -b < branch name > <remote_repo url>
select a.id, a.object
from table_A a
inner join table_B b on a.id=b.id
where b.tag = 'chair';
Method One:
Using the strtotime()
to time is the best format to change the date to the given format.
strtotime()
- Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format()
- Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
This worked for me:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
This is due to the mismatch of the data type of your java Entity and the database table column. Please review if all the column is exact same data type as your entity. This mismatch happens when we update our model attribute's data-type.
Build a hybrid app. Anyways Java is not enough for a software engineer , you need to learn JS,HTML5,CSS as well for becoming a full stack mobile/app developer. Build the complete backend using Java & frontend using Cordova/Phonegap.
I'm assuming you dont need the last drop of juice from the hardware even hybind app should suffice your needs.
Build a responsive webapp using Bootstrap 4 + React JS. Use https://github.com/ipselon/structor to quickly build up the frontend. Now the web app becomes an app in the browser.
You could also take the same app and build it using cordova to publish a app on ios/android platform.
const int*
- pointer to constant int
object.You can change the value of the pointer; you can not change the value of the int
object, the pointer points to.
const int * const
- constant pointer to constant int
object.You can not change the value of the pointer nor the value of the int
object the pointer points to.
int const *
- pointer to constant int
object.This statement is equivalent to 1. const int*
- You can change the value of the pointer but you can not change the value of the int
object, the pointer points to.
Actually, there is a 4th option:
int * const
- constant pointer to int
object.You can change the value of the object the pointer points to but you can not change the value of the pointer itself. The pointer will always point to the same int
object but this value of this int
object can be changed.
If you want to determine a certain type of C or C++ construct you can use the Clockwise/Spiral Rule made by David Anderson; but not to confuse with Anderson`s Rule made by Ross J. Anderson, which is something quite distinct.
You can add a .env
file in all your projects containing COMPOSE_PROJECT_NAME=somename
.
COMPOSE_PROJECT_NAME overrides the prefix used to name resources, as such all your projects will use somename_default
as their network, making it possible for services to communicate with each other as they were in the same project.
NB: You'll get warnings for "orphaned" containers created from other projects.
To set an invisible redirect from root to subfolder, You can use the following RewriteRule in /root/.htaccess :
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/subfolder
RewriteRule ^(.*)$ /subfolder/$1 [NC,L]
The rule above will internally redirect the browser from :
to
And
to
while the browser will stay on the root folder.
If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
I've solved my problem by this way: Edit the php.ini file:
The above is my solution,Hope it will work for u.
Code: https://github.com/uxsolutions/bootstrap-datepicker
(Docs: https://bootstrap-datepicker.readthedocs.io/en/latest/)
Here's a bug report:
https://github.com/uxsolutions/bootstrap-datepicker/issues/1957
If anyone has a solution/workaround for this one, would be great if you'd include it.
Also another difference is taking into consideration a situation where there is a skew join and you have to coalesce on top of it. A repartition will solve the skew join in most cases, then you can do the coalesce.
Another situation is, suppose you have saved a medium/large volume of data in a data frame and you have to produce to Kafka in batches. A repartition helps to collectasList before producing to Kafka in certain cases. But, when the volume is really high, the repartition will likely cause serious performance impact. In that case, producing to Kafka directly from dataframe would help.
side notes: Coalesce does not avoid data movement as in full data movement between workers. It does reduce the number of shuffles happening though. I think that's what the book means.
$ git clone $URL
$ cd $PROJECT_NAME
$ git reset --hard $SHA1
To again go back to the most recent commit
$ git pull
Check this code :
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Folder1\"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "pdf" Then
Wscript.Echo objFile.Name
End If
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
for each Files in colFiles
if LCase(InStr(1,Files, ".pdf")) > 1 then Wscript.Echo Files
next
ShowSubFolders Subfolder
Next
End Sub
If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.
You can also pass the function of a struct, like:
package main
// define struct
type Apple struct {}
// return apple's color
func (Apple) GetColor() string {
return "Red"
}
func main () {
// instantiate
myApple := Apple{}
// put the func in a variable
theFunc := myApple.GetColor
// execute the variable as a function
color := theFunc()
print(color)
}
output will be "Red", check on the playground
One could install Git for Windows and subsequently run ssh-add
:
Step 3: Add your key to the ssh-agent
To configure the ssh-agent program to use your SSH key:
If you have GitHub for Windows installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.
Ensure ssh-agent is enabled:
If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background ssh-agent -s # Agent pid 59566
If you are using another terminal prompt, such as msysgit, turn on ssh-agent:
# start the ssh-agent in the background eval $(ssh-agent -s) # Agent pid 59566
Add your SSH key to the ssh-agent:
ssh-add ~/.ssh/id_rsa
I have an Entity Framework web application that works on my local machine, but this error appears when pushed to another environment. There are other non-Entity Framework applications that work, and I'm able to connect with sqlplus.
Using sysinternals Process Monitor shows that tns names file is not being loaded correctly:
Following the documentation I tried to add a section giving the location of the tnsnames file like so:
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</configSections>
<oracle.manageddataaccess.client>
<version number="*">
<settings>
<setting name="TNS_ADMIN" value="C:\Oracle\product\12.1.0\client_1\Network\Admin"/>
</settings>
</version>
</oracle.manageddataaccess.client>
<configuration>
However, this resulted in an immediate 500 server error.
Further investigation showed that the dll I was packaging with the web application was version 4.122.1.0, while the Oracle client environment installed on the machine was 4.121.2.0. As explained in the Oracle EntityFramework package documentation
Note: If your application is a web application and the above entry was added to a web.config and the same config section handler for "oracle.manageddataaccess.client" also exists in machine.config but the "Version" attribute values are different, an error message of "There is a duplicate 'oracle.manageddataaccess.client' section defined." may be observed at runtime. If so, the config section handler entry in the machine.config for "oracle.manageddataaccess.client" has to be removed from the machine.config for the web application to not encounter this error. But given that there may be other applications on the machine that depended on this entry in the machine.config, this config section handler entry may need to be moved to all of the application's .NET config file on that machine that depend on it.
I attempted to add a separate version section in the .NET machine.config without success (there existed a section for version 4.121.2.0 and I added a section for version 4.122.1.0). After I removed the "oracle.manageddataaccess.client" section from the machine.config, the above addition to the web.config resolved ORA-12154.
While researching this problem I found that the TNS_ADMIN environmental variable was not set. I created a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin". I removed the web.config changes, and removed the "oracle.manageddataaccess.client" section from .NET machine.config, but still received ORA-12154. Only after I restarted the machine did this resolve the issue.
I added an entry for the correct version in the registry and this resolved the issue:
HKLM\Software\Wow6432Node\Oracle\ODP.NET.Managed\4.121.2.0
The name of the key is TNS_ADMIN
and this points to the folder containing the tnsnames file:
C:\Oracle\product\12.1.0\client_1\network
Not the C:\Oracle\product\12.1.0\client_1\network\admin
folder.
You must first import the functions:
import org.apache.spark.sql.functions._
Then you can use them like this:
val df = CSV.load(args(0))
val sumSteps = df.agg(sum("steps")).first.get(0)
You can also cast the result if needed:
val sumSteps: Long = df.agg(sum("steps").cast("long")).first.getLong(0)
Edit:
For multiple columns (e.g. "col1", "col2", ...), you could get all aggregations at once:
val sums = df.agg(sum("col1").as("sum_col1"), sum("col2").as("sum_col2"), ...).first
Edit2:
For dynamically applying the aggregations, the following options are available:
df.groupBy().sum()
val columnNames = List("col1", "col2")
df.groupBy().sum(columnNames: _*)
val cols = List("col1", "col2")
val sums = cols.map(colName => sum(colName).cast("double").as("sum_" + colName))
df.groupBy().agg(sums.head, sums.tail:_*).show()
For even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var frame_win = getIframeWindow( frames['nameOfMyIframe'] );
if (frame_win) {
$(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
...
}
...
I did a similar solution. I've created a snippet to replace 'vardump' with this:
foreach ($variable as $key => $reg) {
echo "<pre>{$key} => '{$reg}'</pre>";
}
var_dump($variable);die;
Ps: I'm repeating the data with the last var_dump to get the filename and line
Let me know if this will help you.
This works for me:
<body>
<form>
[...]
<div style="position:absolute; top:60px; left:10px; width:500px; height:500px;">
<canvas id="cv_values"></canvas>
<script type="text/javascript">
var indicatedValueData = {
labels: ["1", "2", "3"],
datasets: [
{
[...]
};
var cv_values = document.getElementById("cv_values").getContext("2d");
var myChart = new Chart(cv_values, { type: "line", data: indicatedValueData });
</script>
</div>
</form>
</body>
The essential fact is that we have to set the size of the canvas in the div-tag.
My solution was to add a space between the $ and the {.
For example:
@Value("${project.ftp.adresse}")
becomes
@Value("$ {project.ftp.adresse}")
For Custom Dialog:
just call super(context,R.style.<dialog style>)
instead of super(context)
in dialog constructor
public class MyDialog extends Dialog
{
public MyDialog(Context context)
{
super(context, R.style.Theme_AppCompat_Light_Dialog_Alert)
}
}
For AlertDialog:
Just create alertDialog with this constructor:
new AlertDialog.Builder(
new ContextThemeWrapper(context, android.R.style.Theme_Dialog))
Was having a very similar issue to this while using a CMS but it was not resolving with the above solution. What I did to solve it is put the following in the applicable css:
background-size: cover
and for placement purposes in case you are using bootstrap, I used:
background-position: center center /* or whatever position you wanted */
I was having problem installing the latest v4.1.2 as it was having issue after I start it it shows my old blank project, so things I did were,
Caution: Please move your sdk and projects to a separate location before following steps if you haven't. So it might save your time downloading sdks and stuff.
1- Uninstall old Android Studio Completely (from Contorl panel -> Programs).
2- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Local\Google
3- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Roaming\Google
4- Delete these folders(.android ,.AndroidStudio*, .gradle) located at C:\Users<user_name>\
After doing all this I was managed to have fresh updated Android Studio v4.1.2
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
You have used '/0'
instead of '\0'
. This is incorrect: the '\0'
is a null character, while '/0'
is a multicharacter literal.
Moreover, in C it is OK to skip a zero in your condition:
while (*(forward++)) {
...
}
is a valid way to check character, integer, pointer, etc. for being zero.
{!a}
applies ascii()
and hence escapes non-ASCII characters like quotes and even emoticons.
Here is an example
cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))
Simply \newpage
or \pagebreak
will work, e.g.
hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```
This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">
. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.
Try to make git tag
it should be enough if not try to make git fetch
then git tag
.
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
For testing purposes:
On the original machine, find the library, copy to the same directory as the executable:
$ ldconfig -p | grep libstdc
libstdc++.so.6 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
libstdc++.so.6 (libc6) => /usr/lib32/libstdc++.so.6
$ cp /usr/lib/x86_64-linux-gnu/libstdc++.so.6 .
Then copy this same library to the target machine, and run the executable:
LD_LIBRARY_PATH=. ./myexecutable
Note: command above is temporary; it is not a system-wide change.
Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.
Docker might have lost the authentication data. So you'll have to reauthenticate with your registry provider. With AWS for example:
aws ecr get-login --region us-west-2 --no-include-email
And then copy and paste that resulting "docker login..." to authenticated docker.
Source: Amazon ECR Registeries
Basic and simple.
In your adapter simply use this.
((YourParentClass) context).functionToRun();
You can use input type="reset"
<form action="/action_page.php">
text: <input type="text" name="email" /><br />
<input type="reset" defaultValue="Reset" />
</form>
It is likely because they used a single function for escaping attributes and text nodes. &
doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?
You can prepare your own template for + operator:
template <typename T>
inline T operator+(const T & a, const T & b)
{
T res = a;
res.insert(res.end(), b.begin(), b.end());
return res;
}
Next thing - just use +:
vector<int> a{1, 2, 3, 4};
vector<int> b{5, 6, 7, 8};
for (auto x: a + b)
cout << x << " ";
cout << endl;
This example gives output:
1 2 3 4 5 6 7 8
Depending on your application, you may want to consider using System.nanoTime()
instead.
String.split uses Regular Expressions, also you don't need to allocate an extra array for your split.
The split-method will give you a list., the problem is that you try to pre-define how many occurrences you have of a tab, but how would you Really know that? Try using the Scanner or StringTokenizer and just learn how splitting strings work.
Let me explain Why \t does not work and why you need \\\\
to escape \\
.
Okay, so when you use Split, it actually takes a regex ( Regular Expression ) and in regular expression you want to define what Character to split by, and if you write \t that actually doesn't mean \t
and what you WANT to split by is \t
, right? So, by just writing \t
you tell your regex-processor that "Hey split by the character that is escaped t" NOT "Hey split by all characters looking like \t
". Notice the difference? Using \ means to escape something. And \
in regex means something Totally different than what you think.
So this is why you need to use this Solution:
\\t
To tell the regex processor to look for \t. Okay, so why would you need two of em? Well, the first \ escapes the second, which means it will look like this: \t when you are processing the text!
Now let's say that you are looking to split \
Well then you would be left with \\ but see, that doesn't Work! because \ will try to escape the previous char! That is why you want the Output to be \\ and therefore you need to have \\\\.
I really hope the examples above helps you understand why your solution doesn't work and how to conquer other ones!
Now, I've given you this answer before, maybe you should start looking at them now.
OTHER METHODS
StringTokenizer
You should look into the StringTokenizer, it's a very handy tool for this type of work.
Example
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
This will output
this
is
a
test
You use the Second Constructor for StringTokenizer to set the delimiter:
StringTokenizer(String str, String delim)
Scanner
You could also use a Scanner as one of the commentators said this could look somewhat like this
Example
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
The output would be
1
2
red
blue
Meaning that it will cut out the word "fish" and give you the rest, using "fish" as the delimiter.
This should work. No more gray areas at the top or bottom:)
<script type="text/javascript">
function blockMove() {
event.preventDefault() ;
}
</script>
<body ontouchmove="blockMove()">
But this also disables any scrollable areas. If you want to keep your scrollable areas and still remove the rubber band effect at the top and bottom, see here: https://github.com/joelambert/ScrollFix.
revenue.push_back(pair<string,double> ("String",map[i].second));
this will work.
It appears that X-Frame-Options Allow-From https://... is depreciated and was replaced (and gets ignored) if you use Content-Security-Policy header instead.
Here is the full reference: https://content-security-policy.com/
I'd use B because that in conjunction with worker process recycling means there'd only be a delay while it's recycling. This avoids the delay normally associated with initialization in response to the first request after idle. You also get to keep the benefits of recycling.
<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>
<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>
<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>
Try This
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());
this.gpsCurrentLocation();
}
You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.
You can find this module here https://github.com/isaacs/npmlog
Make sure first that your $siteLink_val isn't returning white space as a value. The <textarea> element by default has an empty value so if the variable you're echo'ing for some reason has spaces, there's your problem right off the bat.
To make the code the absolute cleanest, I would suggest you could do something like this, allowing for some more flexibility later. I've made a function that returns either a NULL if the variable isn't present (what you seem to be aiming for in the original post) and the absolute value otherwise. Once you've made sure of your variable's contents, try this:
function build_siteLink_val() {
if ( $siteLink_val ) {
return $siteLink_val;
}
else {
return "";
}
}
$output_siteLink_val = build_siteLink_val();
And the following code in your textarea would now read:
<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?=$output_siteLink_val?></textarea>
This is assuming your PHP install is configured for short-hand variable calls, as seen in the shortened "<?=?>" tags. If you cannot output this way, remember to preface your PHP code with "<?php" and close with "?>".
Avoid line breaks between <textarea>'s because it can create the potential of erroneous characters.
Also, check your CSS to make sure there isn't a padding rule pushing text inward.
Also, you specify a cols and rows value on the textarea, and then style a width and height. These rules are counter-productive, and will result in inconsistent visuals. Stick with either defining the size through style (I recommend giving the element a class) or the rows/cols.
you can using emulator terminal cmder for windows.
Follow below the steps for instalation:
Terminal cmder on Windows
Now execute command required for settings VM vagrant, for connect only execute the command vagrant ssh; Watch cmder offers ssh client embedded.
I hope this helps.
You actually have one capture group that will match multiple times. Not multiple capture groups.
javascript (js) solution:
let string = "HI,THERE,TOM";
let myRegexp = /([A-Z]+),?/g; //modify as you like
let match = myRegexp.exec(string); //js function, output described below
while(match!=null){ //loops through matches
console.log(match[1]); //do whatever you want with each match
match = myRegexp.exec(bob); //find next match
}
Output:
HI
THERE
TOM
Syntax:
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
As you can see, this will work for any number of matches.
I think what you want ist
return value.toString();
and use the return value to display.
value.floatValue();
will always return 625.3 because its mainly used to calculate something.
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
For you LINQers out there that never use a regular dictionary constructor
myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)
Your command is correct. You just need to add -l
to grep:
find / -type f -exec grep -l 'text-to-find-here' {} \;
This way you don't need to add the CSS outside of the component:
@Component({
selector: 'body',
template: 'app-element',
// prefer decorators (see below)
// host: {'[class.someClass]':'someField'}
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
// alternatively also the host parameter in the @Component()` decorator can be used
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<body>`
//this.cdRef.detectChanges();
}
}
This CSS is defined inside the component and the selector is only applied if the class someClass
is set on the host element (from outside):
:host(.someClass) {
background-color: red;
}
int arr[20] = {0};
C99 [$6.7.8/21]
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Try to use constructor procedure in your class.
Object.assign
is a key
Please take a look on this sample:
class Employee{
firstname: string;
lastname: string;
birthdate: Date;
maxWorkHours: number;
department: string;
permissions: string;
typeOfEmployee: string;
note: string;
lastUpdate: Date;
constructor(original: Object) {
Object.assign(this, original);
}
}
let e = new Employee({
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
console.log(e);
Remove the comma?
select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish'
and a.xyz = b.xyz
Have a look at FROM
SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
this error get if add decimal format. i just add
step="0.1"
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask
to schedule a task to set a stopExecution
flag, and also .interrupt()
your thread.
With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).
Maybe that is the problem with the table schema. drop the table and rerun the application.
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.
sudo apt-get install ruby-all-dev
worked for me.
Here is a version similar to Daniel's but replacing multiple matches:
public static string ReplaceGroup(string input, string pattern, RegexOptions options, string groupName, string replacement)
{
Match match;
while ((match = Regex.Match(input, pattern, options)).Success)
{
var group = match.Groups[groupName];
var sb = new StringBuilder();
// Anything before the match
if (match.Index > 0)
sb.Append(input.Substring(0, match.Index));
// The match itself
var startIndex = group.Index - match.Index;
var length = group.Length;
var original = match.Value;
var prior = original.Substring(0, startIndex);
var trailing = original.Substring(startIndex + length);
sb.Append(prior);
sb.Append(replacement);
sb.Append(trailing);
// Anything after the match
if (match.Index + match.Length < input.Length)
sb.Append(input.Substring(match.Index + match.Length));
input = sb.ToString();
}
return input;
The RSACryptoServiceProvider(CspParameters)
constructor creates a keypair which is stored in the keystore on the local machine. If you already have a keypair with the specified name, it uses the existing keypair.
It sounds as if you are not interested in having the key stored on the machine.
So use the RSACryptoServiceProvider(Int32)
constructor:
public static void AssignNewKey(){
RSA rsa = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key
string publicPrivateKeyXML = rsa.ToXmlString(true);
string publicOnlyKeyXML = rsa.ToXmlString(false);
// do stuff with keys...
}
EDIT:
Alternatively try setting the PersistKeyInCsp to false:
public static void AssignNewKey(){
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "KeyContainer";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
rsa = new RSACryptoServiceProvider(cspParams);
rsa.PersistKeyInCsp = false;
string publicPrivateKeyXML = rsa.ToXmlString(true);
string publicOnlyKeyXML = rsa.ToXmlString(false);
// do stuff with keys...
}
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Try
apt-get -d install <packages>
It is documented in man apt-get
.
Just for clarification; the downloaded packages are located in the apt package cache at
/var/cache/apt/archives
You need to be careful with inheritance:
>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
Check types more strictly, like this:
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
Besides that, your approach will work fine, that's what special methods are there for.
You could try
try{
if(webDriver.switchTo().alert() != null){
Alert alert = webDriver.switchTo().alert();
alert.getText();
//etc.
}
}catch(Exception e){}
If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.
for(String s: webDriver.getWindowHandles()){
//see if alert exists here.
}
Tip of the hat to @gniourf_gniourf for his input.
Note: This answer does not answer the original question, but complements the existing, helpful answers by comparing performance.
Solutions are compared in terms of execution speed only - memory requirements are not taken into account (they vary across solutions and may matter with large repeat counts).
Summary:
${var// /=}
), as it is prohibitively slow.The following are timings taken on a late-2012 iMac with a 3.2 GHz Intel Core i5 CPU and a Fusion Drive, running OSX 10.10.4 and bash 3.2.57, and are the average of 1000 runs.
The entries are:
M
... a potentially multi-character solutionS
... a single-character-only solutionP
... a POSIX-compliant solution[M, P] printf %.s= [dogbane]: 0.0002
[M ] printf + bash global substr. replacement [Tim]: 0.0005
[M ] echo -n - brace expansion loop [eugene y]: 0.0007
[M ] echo -n - arithmetic loop [Eliah Kagan]: 0.0013
[M ] seq -f [Sam Salisbury]: 0.0016
[M ] jot -b [Stefan Ludwig]: 0.0016
[M ] awk - $(count+1)="=" [Steven Penny (variant)]: 0.0019
[M, P] awk - while loop [Steven Penny]: 0.0019
[S ] printf + tr [user332325]: 0.0021
[S ] head + tr [eugene y]: 0.0021
[S, P] dd + tr [mklement0]: 0.0021
[M ] printf + sed [user332325 (comment)]: 0.0021
[M ] mawk - $(count+1)="=" [Steven Penny (variant)]: 0.0025
[M, P] mawk - while loop [Steven Penny]: 0.0026
[M ] gawk - $(count+1)="=" [Steven Penny (variant)]: 0.0028
[M, P] gawk - while loop [Steven Penny]: 0.0028
[M ] yes + head + tr [Digital Trauma]: 0.0029
[M ] Perl [sid_com]: 0.0059
awk
, and perl
solutions.[M ] Perl [sid_com]: 0.0067
[M ] mawk - $(count+1)="=" [Steven Penny (variant)]: 0.0254
[M ] gawk - $(count+1)="=" [Steven Penny (variant)]: 0.0599
[S ] head + tr [eugene y]: 0.1143
[S, P] dd + tr [mklement0]: 0.1144
[S ] printf + tr [user332325]: 0.1164
[M, P] mawk - while loop [Steven Penny]: 0.1434
[M ] seq -f [Sam Salisbury]: 0.1452
[M ] jot -b [Stefan Ludwig]: 0.1690
[M ] printf + sed [user332325 (comment)]: 0.1735
[M ] yes + head + tr [Digital Trauma]: 0.1883
[M, P] gawk - while loop [Steven Penny]: 0.2493
[M ] awk - $(count+1)="=" [Steven Penny (variant)]: 0.2614
[M, P] awk - while loop [Steven Penny]: 0.3211
[M, P] printf %.s= [dogbane]: 2.4565
[M ] echo -n - brace expansion loop [eugene y]: 7.5877
[M ] echo -n - arithmetic loop [Eliah Kagan]: 13.5426
[M ] printf + bash global substr. replacement [Tim]: n/a
${foo// /=}
) is inexplicably excruciatingly slow with large strings, and has been taken out of the running (took around 50 minutes(!) in Bash 4.3.30, and even longer in Bash 3.2.57 - I never waited for it to finish).(( i= 0; ... ))
) are slower than brace-expanded ones ({1..n}
) - though arithmetic loops are more memory-efficient.awk
refers to BSD awk
(as also found on OSX) - it's noticeably slower than gawk
(GNU Awk) and especially mawk
.Here's the Bash script (testrepeat
) that produced the above.
It takes 2 arguments:
In other words: the timings above were obtained with testrepeat 100 1000
and testrepeat 1000000 1000
#!/usr/bin/env bash
title() { printf '%s:\t' "$1"; }
TIMEFORMAT=$'%6Rs'
# The number of repetitions of the input chars. to produce
COUNT_REPETITIONS=${1?Arguments: <charRepeatCount> [<testRunCount>]}
# The number of test runs to perform to derive the average timing from.
COUNT_RUNS=${2:-1}
# Discard the (stdout) output generated by default.
# If you want to check the results, replace '/dev/null' on the following
# line with a prefix path to which a running index starting with 1 will
# be appended for each test run; e.g., outFilePrefix='outfile', which
# will produce outfile1, outfile2, ...
outFilePrefix=/dev/null
{
outFile=$outFilePrefix
ndx=0
title '[M, P] printf %.s= [dogbane]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In order to use brace expansion with a variable, we must use `eval`.
eval "
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf '%.s=' {1..$COUNT_REPETITIONS} >"$outFile"
done"
title '[M ] echo -n - arithmetic loop [Eliah Kagan]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
for ((i=0; i<COUNT_REPETITIONS; ++i)); do echo -n =; done >"$outFile"
done
title '[M ] echo -n - brace expansion loop [eugene y]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In order to use brace expansion with a variable, we must use `eval`.
eval "
time for (( n = 0; n < COUNT_RUNS; n++ )); do
for i in {1..$COUNT_REPETITIONS}; do echo -n =; done >"$outFile"
done
"
title '[M ] printf + sed [user332325 (comment)]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf "%${COUNT_REPETITIONS}s" | sed 's/ /=/g' >"$outFile"
done
title '[S ] printf + tr [user332325]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
printf "%${COUNT_REPETITIONS}s" | tr ' ' '=' >"$outFile"
done
title '[S ] head + tr [eugene y]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
head -c $COUNT_REPETITIONS < /dev/zero | tr '\0' '=' >"$outFile"
done
title '[M ] seq -f [Sam Salisbury]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
seq -f '=' -s '' $COUNT_REPETITIONS >"$outFile"
done
title '[M ] jot -b [Stefan Ludwig]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
jot -s '' -b '=' $COUNT_REPETITIONS >"$outFile"
done
title '[M ] yes + head + tr [Digital Trauma]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
yes = | head -$COUNT_REPETITIONS | tr -d '\n' >"$outFile"
done
title '[M ] Perl [sid_com]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
perl -e "print \"=\" x $COUNT_REPETITIONS" >"$outFile"
done
title '[S, P] dd + tr [mklement0]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
dd if=/dev/zero bs=$COUNT_REPETITIONS count=1 2>/dev/null | tr '\0' "=" >"$outFile"
done
# !! On OSX, awk is BSD awk, and mawk and gawk were installed later.
# !! On Linux systems, awk may refer to either mawk or gawk.
for awkBin in awk mawk gawk; do
if [[ -x $(command -v $awkBin) ]]; then
title "[M ] $awkBin"' - $(count+1)="=" [Steven Penny (variant)]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
$awkBin -v count=$COUNT_REPETITIONS 'BEGIN { OFS="="; $(count+1)=""; print }' >"$outFile"
done
title "[M, P] $awkBin"' - while loop [Steven Penny]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
time for (( n = 0; n < COUNT_RUNS; n++ )); do
$awkBin -v count=$COUNT_REPETITIONS 'BEGIN { while (i++ < count) printf "=" }' >"$outFile"
done
fi
done
title '[M ] printf + bash global substr. replacement [Tim]'
[[ $outFile != '/dev/null' ]] && outFile="$outFilePrefix$((++ndx))"
# !! In Bash 4.3.30 a single run with repeat count of 1 million took almost
# !! 50 *minutes*(!) to complete; n Bash 3.2.57 it's seemingly even slower -
# !! didn't wait for it to finish.
# !! Thus, this test is skipped for counts that are likely to be much slower
# !! than the other tests.
skip=0
[[ $BASH_VERSINFO -le 3 && COUNT_REPETITIONS -gt 1000 ]] && skip=1
[[ $BASH_VERSINFO -eq 4 && COUNT_REPETITIONS -gt 10000 ]] && skip=1
if (( skip )); then
echo 'n/a' >&2
else
time for (( n = 0; n < COUNT_RUNS; n++ )); do
{ printf -v t "%${COUNT_REPETITIONS}s" '='; printf %s "${t// /=}"; } >"$outFile"
done
fi
} 2>&1 |
sort -t$'\t' -k2,2n |
awk -F $'\t' -v count=$COUNT_RUNS '{
printf "%s\t", $1;
if ($2 ~ "^n/a") { print $2 } else { printf "%.4f\n", $2 / count }}' |
column -s$'\t' -t
I recently got into same problem, the disk space was full on the server. Clearing some space has resolved the issue.
In order for Bootstrap Beta to function properly, you must place the scripts in the following order.
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
Using the keep
function from the gdata
package is quite convenient.
> ls()
[1] "a" "b" "c"
library(gdata)
> keep(a) #shows you which variables will be removed
[1] "b" "c"
> keep(a, sure = TRUE) # setting sure to TRUE removes variables b and c
> ls()
[1] "a"
Be careful, -
has a special meaning with regexp. In a []
, you can put it without problem if it is placed at the end. In your case, ,-:
is taken as from ,
to :
.
You can manually call the method invoked by PostBack from the Page_Load
event:
public void Page_Load(object sender, EventArgs e)
{
MyPostBackMethod(sender, e);
}
But if you mean if you can have the Page.IsPostBack
property set to true
without real post back, then the answer is no.
When you use Date()
to calculate the difference in hours is necessary configure the SimpleDateFormat()
in UTC otherwise you get one hour error due to Daylight SavingTime.
You could do:
Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components
generateNumbers()
expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is /etc/launchd.conf
.
Please note that environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here.
Open a terminal prompt
Type sudo vi /etc/launchd.conf
(note: this file might not yet exist)
Put contents like the following into the file
# Set environment variables here so they are available globally to all apps
# (and Terminal), including those launched via Spotlight.
#
# After editing this file run the following command from the terminal to update
# environment variables globally without needing to reboot.
# NOTE: You will still need to restart the relevant application (including
# Terminal) to pick up the changes!
# grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
#
# See http://www.digitaledgesw.com/node/31
# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/
#
# Note that you must hardcode the paths below, don't use environment variables.
# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.
#
setenv JAVA_VERSION 1.6
setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
setenv GROOVY_HOME /Applications/Dev/groovy
setenv GRAILS_HOME /Applications/Dev/grails
setenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp
setenv JRUBY_HOME /Applications/Dev/jruby
setenv ANT_HOME /Applications/Dev/apache-ant
setenv ANT_OPTS -Xmx512M
setenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"
setenv M2_HOME /Applications/Dev/apache-maven
setenv JMETER_HOME /Applications/Dev/jakarta-jmeter
Save your changes in vi and reboot your Mac. Or use the grep
/xargs
command which is shown in the code comment above.
Prove that your variables are working by opening a Terminal window and typing export
and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight.
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.
pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.
You can do something like this:
#container {_x000D_
background-color: red;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background-color: blue;_x000D_
width: 150px;_x000D_
height: 50px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="inner">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>_x000D_
</div>
_x000D_
You can try this FLAG_ACTIVITY_REORDER_TO_FRONT
(the document describes exactly what you want to)
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.
See Runtime.exec javadocs
Specifically,
public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException
where dir
is the working directory to run the subprocess in
$(document).keydown(function(e) {_x000D_
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))_x000D_
{_x000D_
e.preventDefault();_x000D_
alert("Ctrl-s pressed");_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Try pressing ctrl+s somewhere.
_x000D_
This is an up-to-date version of @AlanBellows's answer, replacing which
with key
. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
Maven version 3.2.1 added this feature, you can use the -pl
switch (shortcut for --projects
list) with !
or -
(source) to exclude certain submodules.
mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install
Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.
The syntax to exclude multiple module is the same as the inclusion
mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install
EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)
mvn -pl "!submodule1,!submodule2" install
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
Override ui-page class in your css:
.ui-page {
background: url("image.gif");
background-repeat: repeat;
}
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
Unfortunatelly, to remove one backlash as mentioned in first comment (newbiedoodle) don't lead to good result. Most (if not all) IDE issues syntax error. The reason is in this, that Java Escaped Unicode format expects syntax "\uXXXX", where XXXX are 4 hexadecimal digits, which are mandatory. Attempts to fold this string from pieces fails. Of course, "\u" is not the same as "\\u". The first syntax means escaped 'u', second means escaped backlash (which is backlash) followed by 'u'. It is strange, that on the Apache pages is presented utility, which doing exactly this behavior. But in reality, it is Escape mimic utility. Apache has some its own utilities (i didn't testet them), which do this work for you. May be, it is still not that, what you want to have. Apache Escape Unicode utilities But this utility 1 have good approach to the solution. With combination described above (MeraNaamJoker). My solution is create this Escaped mimic string and then convert it back to unicode (to avoid real Escaped Unicode restriction). I used it for copying text, so it is possible, that in uencode method will be better to use '\\u' except '\\\\u'. Try it.
/**
* Converts character to the mimic unicode format i.e. '\\u0020'.
*
* This format is the Java source code format.
*
* CharUtils.unicodeEscaped(' ') = "\\u0020"
* CharUtils.unicodeEscaped('A') = "\\u0041"
*
* @param ch the character to convert
* @return is in the mimic of escaped unicode string,
*/
public static String unicodeEscaped(char ch) {
String returnStr;
//String uniTemplate = "\u0000";
final static String charEsc = "\\u";
if (ch < 0x10) {
returnStr = "000" + Integer.toHexString(ch);
}
else if (ch < 0x100) {
returnStr = "00" + Integer.toHexString(ch);
}
else if (ch < 0x1000) {
returnStr = "0" + Integer.toHexString(ch);
}
else
returnStr = "" + Integer.toHexString(ch);
return charEsc + returnStr;
}
/**
* Converts the string from UTF8 to mimic unicode format i.e. '\\u0020'.
* notice: i cannot use real unicode format, because this is immediately translated
* to the character in time of compiling and editor (i.e. netbeans) checking it
* instead reaal unicode format i.e. '\u0020' i using mimic unicode format '\\u0020'
* as a string, but it doesn't gives the same results, of course
*
* This format is the Java source code format.
*
* CharUtils.unicodeEscaped(' ') = "\\u0020"
* CharUtils.unicodeEscaped('A') = "\\u0041"
*
* @param String - nationalString in the UTF8 string to convert
* @return is the string in JAVA unicode mimic escaped
*/
public String encodeStr(String nationalString) throws UnsupportedEncodingException {
String convertedString = "";
for (int i = 0; i < nationalString.length(); i++) {
Character chs = nationalString.charAt(i);
convertedString += unicodeEscaped(chs);
}
return convertedString;
}
/**
* Converts the string from mimic unicode format i.e. '\\u0020' back to UTF8.
*
* This format is the Java source code format.
*
* CharUtils.unicodeEscaped(' ') = "\\u0020"
* CharUtils.unicodeEscaped('A') = "\\u0041"
*
* @param String - nationalString in the JAVA unicode mimic escaped
* @return is the string in UTF8 string
*/
public String uencodeStr(String escapedString) throws UnsupportedEncodingException {
String convertedString = "";
String[] arrStr = escapedString.split("\\\\u");
String str, istr;
for (int i = 1; i < arrStr.length; i++) {
str = arrStr[i];
if (!str.isEmpty()) {
Integer iI = Integer.parseInt(str, 16);
char[] chaCha = Character.toChars(iI);
convertedString += String.valueOf(chaCha);
}
}
return convertedString;
}
i think you should do:
var myInterval
on.onclick = function() {
myInterval=setInterval(fontChange, 500);
};
off.onclick = function() {
clearInterval(myInterval);
};
instead of:
android:drawable="@color/transparent"
write
android:drawable="@android:color/transparent"
You need to install NUnitTestAdapter. The latest version of NUnit is 3.x.y (3.6.1) and you should install NUnit3TestAdapter along with NUnit 3.x.y
To install NUnit3TestAdapter in Visual Studio 2017, follow the steps below:
You can simply add this to Gradle dependencies:
compile "org.apache.httpcomponents:httpcore:4.3.2"
Simply add outline:0;
css to elements.
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;
As per this PPI calculation tool, Google Nexus 10 has a display density of about 300 DPI...
However, Android documentation states that:
ldpi : ~120dpi mdpi : ~160dpi hdpi : ~240dpi xhdpi : ~320dpi xxhdpi is not specified.
I think we just let Android OS scale up xhdpi resources...
df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')
I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder
public static class Webdriver
{
public static void ExecuteJavaScript(string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(scripts);
}
public static T ExecuteJavaScript<T>(string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
return (T)js.ExecuteScript(scripts);
}
}
In your code you can then do
string test = Webdriver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = Webdriver.ExecuteJavaScript<int>(" return 3; ");
We needed to version our SQL database after we migrated to an x64 platform and our old version broke with the migration. We wrote a C# application which used SQLDMO to map out all of the SQL objects to a folder:
Root ServerName DatabaseName Schema Objects Database Triggers* .ddltrigger.sql Functions ..function.sql Security Roles Application Roles .approle.sql Database Roles .role.sql Schemas* .schema.sql Users .user.sql Storage Full Text Catalogs* .fulltext.sql Stored Procedures ..proc.sql Synonyms* .synonym.sql Tables ..table.sql Constraints ...chkconst.sql ...defconst.sql Indexes ...index.sql Keys ...fkey.sql ...pkey.sql ...ukey.sql Triggers ...trigger.sql Types User-defined Data Types ..uddt.sql XML Schema Collections* ..xmlschema.sql Views ..view.sql Indexes ...index.sql Triggers ...trigger.sql
The application would then compare the newly written version with the version stored in SVN, and if there were differences it would update SVN. We determined that running the process once a night was sufficient since we did not make that many changes to SQL. It allows us to track changes to all the objects we care about plus it allows us to rebuild our full schema in the event of a serious problem.
Since the display-messages
which are sent from Firebase Notification UI only works if your app is in foreground. For data-messages
, there is a need to make a POST call to FCM
Steps
Add the following headers
Key: Content-Type, Value: application/json
Add the body
If using topics :
{
"to" : "/topics/topic_name",
"data": {
"key1" : "value1",
"key2" : "value2",
}
}
If using registration id :
{
"registration_ids" : "[{"id"},{id1}]",
"data": {
"key1" : "value1",
"key2" : "value2",
}
}
Thats it!. Now listen to onMessageReceived
callback as usual.
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String value1 = data.get("key1");
String value2 = data.get("key2");
}
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.
use this..
$(".content_box a:not('.button')")
You should pass @item.email
in quotes then it will be treated as string argument
<td><a href ="#" onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a> </td>
Otherwise, it is treated as variable thus error is generated.
you should use bootstrap v.4
<div class="form-group row">
<div class="col-md-6">
<input type="button" class="btn form-control" id="btn1">
</div>
<div class="col-md-6">
<input type="button" class="btn form-control" id="btn2">
</div>
</div>
USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL
DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL
DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition
SELECT id FROM t6;
--IDs empty.
SELECT id FROM t7;
--ID is empty.
--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/
SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/
SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/
SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/
-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action
up to this point in this session.*/
SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/
SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/
Most basic regex is following:
(^([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$)
or you could paste it here.
Hope this saves you some time.
The answer to "Given a class, see if instance has method (Ruby)" is better. Apparently Ruby has this built-in, and I somehow missed it. My answer is left for reference, regardless.
Ruby classes respond to the methods instance_methods
and public_instance_methods
. In Ruby 1.8, the first lists all instance method names in an array of strings, and the second restricts it to public methods. The second behavior is what you'd most likely want, since respond_to?
restricts itself to public methods by default, as well.
Foo.public_instance_methods.include?('bar')
In Ruby 1.9, though, those methods return arrays of symbols.
Foo.public_instance_methods.include?(:bar)
If you're planning on doing this often, you might want to extend Module
to include a shortcut method. (It may seem odd to assign this to Module
instead of Class
, but since that's where the instance_methods
methods live, it's best to keep in line with that pattern.)
class Module
def instance_respond_to?(method_name)
public_instance_methods.include?(method_name)
end
end
If you want to support both Ruby 1.8 and Ruby 1.9, that would be a convenient place to add the logic to search for both strings and symbols, as well.
Use String.Format()
or TextWriter.Format()
(depending on how you actually write to the file) and specify the width of a field.
String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");
You can specify the width of a field within interpolated strings as well:
$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"
And just so you know, you can create a string of repeated characters using the appropriate string contructor.
new String(' ', 20); // string of 20 spaces
You need upper case property names in your structs in order to be used by the json packages.
Upper case property names are exported properties
. Lower case property names are not exported.
You also need to pass the your data object by reference (&data
).
package main
import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type tracks struct {
Toptracks []toptracks_info
}
type toptracks_info struct {
Track []track_info
Attr []attr_info
}
type track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []streamable_info
Artist []artist_info
Attr []track_attr_info
}
type attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type streamable_info struct {
Text string
Fulltrack string
}
type artist_info struct {
Name string
Mbid string
Url string
}
type track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data tracks
json.Unmarshal(body, &data)
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
You can use the function revalue
from the package plyr
to replace values in a factor vector.
In your example to replace the factor virginica
by setosa
:
data(iris)
library(plyr)
revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species
Here we have 1000.000 words list. 1000.000 words
namespace WindowsFormsApplication2
{
public class WordDef
{
public string Word { get; set; }
public int WordSum { get; set; }
public int Length { get; set; }
public string AnagramWord { get; set; }
public string Ordered { get; set; }
public int GetAsciiSum(string word)
{
int sum = 0;
foreach (char c in word)
{
sum += (int)c;
}
return sum;
}
}
}
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class AngramTestForm : Form
{
private ConcurrentBag<string> m_Words;
private ConcurrentBag<string> m_CacheWords;
private ConcurrentBag<WordDef> m_Anagramlist;
public AngramTestForm()
{
InitializeComponent();
m_CacheWords = new ConcurrentBag<string>();
}
private void button1_Click(object sender, EventArgs e)
{
m_Words = null;
m_Anagramlist = null;
m_Words = new ConcurrentBag<string>();
m_Anagramlist = new ConcurrentBag<WordDef>();
if (m_CacheWords.Count == 0)
{
foreach (var s in GetWords())
{
m_CacheWords.Add(s);
}
}
m_Words = m_CacheWords;
Stopwatch sw = new Stopwatch();
sw.Start();
//DirectCalculation();
AsciiCalculation();
sw.Stop();
Console.WriteLine("The End! {0}", sw.ElapsedMilliseconds);
this.Invoke((MethodInvoker)delegate
{
lbResult.Text = string.Concat(sw.ElapsedMilliseconds.ToString(), " Miliseconds");
});
StringBuilder sb = new StringBuilder();
foreach (var w in m_Anagramlist)
{
if (w != null)
{
sb.Append(string.Concat(w.Word, " - ", w.AnagramWord, Environment.NewLine));
}
}
txResult.Text = sb.ToString();
}
private void DirectCalculation()
{
List<WordDef> wordDef = new List<WordDef>();
foreach (var w in m_Words)
{
WordDef wd = new WordDef();
wd.Word = w;
wd.WordSum = wd.GetAsciiSum(w);
wd.Length = w.Length;
wd.Ordered = String.Concat(w.OrderBy(c => c));
wordDef.Add(wd);
}
foreach (var w in wordDef)
{
foreach (var t in wordDef)
{
if (w.Word != t.Word)
{
if (w.Ordered == t.Ordered)
{
t.AnagramWord = w.Word;
m_Anagramlist.Add(new WordDef() { Word = w.Word, AnagramWord = t.Word });
}
}
}
}
}
private void AsciiCalculation()
{
ConcurrentBag<WordDef> wordDef = new ConcurrentBag<WordDef>();
Parallel.ForEach(m_Words, w =>
{
WordDef wd = new WordDef();
wd.Word = w;
wd.WordSum = wd.GetAsciiSum(w);
wd.Length = w.Length;
wd.Ordered = String.Concat(w.OrderBy(c => c));
wordDef.Add(wd);
});
var tempWordByLength = from w in wordDef
group w by w.Length into newGroup
orderby newGroup.Key
select newGroup;
foreach (var wList in tempWordByLength)
{
List<WordDef> wd = wList.ToList<WordDef>();
var tempWordsBySum = from w in wd
group w by w.WordSum into newGroup
orderby newGroup.Key
select newGroup;
Parallel.ForEach(tempWordsBySum, ws =>
{
List<WordDef> we = ws.ToList<WordDef>();
if (we.Count > 1)
{
CheckCandidates(we);
}
});
}
}
private void CheckCandidates(List<WordDef> we)
{
for (int i = 0; i < we.Count; i++)
{
for (int j = i + 1; j < we.Count; j++)
{
if (we[i].Word != we[j].Word)
{
if (we[i].Ordered == we[j].Ordered)
{
we[j].AnagramWord = we[i].Word;
m_Anagramlist.Add(new WordDef() { Word = we[i].Word, AnagramWord = we[j].Word });
}
}
}
}
}
private static string[] GetWords()
{
string htmlCode = string.Empty;
using (WebClient client = new WebClient())
{
htmlCode = client.DownloadString("https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/10_million_password_list_top_1000000.txt");
}
string[] words = htmlCode.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
return words;
}
}
}
DECLARE @A nvarchar(100) = '12'
IF(ISNUMERIC(@A) = 1)
BEGIN
PRINT 'YES NUMERIC'
END
The problem with most of these is that the user can still scroll up and see the addressbar. To make a permanent solution, you need to add this as well.
//WHENEVER the user scrolls
$(window).scroll(function(){
//if you reach the top
if ($(window).scrollTop() == 0)
//scroll back down
{window.scrollTo(1,1)}
})
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
In Linux:
java -version
In Windows:
java.exe -version
If you need more info about the JVM you can call the executable with the parameter -XshowSettings:properties
. It will show a lot of System Properties. These properties can also be accessed by means of the static method System.getProperty(String)
in a Java class. As example this is an excerpt of some of the properties that can be obtained:
$ java -XshowSettings:properties -version
[...]
java.specification.version = 1.7
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.7.0_95
[...]
So if you need to access any of these properties from Java code you can use:
System.getProperty("java.specification.version");
System.getProperty("java.vendor");
System.getProperty("java.vendor.url");
System.getProperty("java.version");
Take into account that sometimes the vendor is not exposed as clear as Oracle or IBM. For example,
$ java version
"1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
HotSpot is what Oracle calls their implementation of the JVM. Check this list if the vendor does not seem to be shown with -version
.
Whenever I type this command I always seem to hose it up, or forget a flag. I created a Gist on github based off of TaylanUB's answer that does a global find replace from the current directory. This is Mac OSX specific.
https://gist.github.com/nateflink/9056302
It's nice because now I just pop open a terminal then copy in:
curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"
You can get some weird byte sequence errors, so here is the full code:
#!/bin/bash
#By Nate Flink
#Invoke on the terminal like this
#curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: ./$0 [find string] [replace string]"
exit 1
fi
FIND=$1
REPLACE=$2
#needed for byte sequence error in ascii to utf conversion on OSX
export LC_CTYPE=C;
export LANG=C;
#sed -i "" is needed by the osx version of sed (instead of sed -i)
find . -type f -exec sed -i "" "s|${FIND}|${REPLACE}|g" {} +
exit 0
You could try mixing Number()
and toFixed()
.
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;_x000D_
var multiplier = 5;_x000D_
$('#actionButton').on('click', function() {_x000D_
$('#message').text( myNumber * multiplier );_x000D_
});_x000D_
_x000D_
$('#actionButton2').on('click', function() {_x000D_
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<button id="actionButton">Weird numbers</button>_x000D_
<button id="actionButton2">Nice numbers</button>_x000D_
_x000D_
<div id="message"></div>
_x000D_
ngSanitize
module on your app
eg: var app = angular.module('myApp', ['ngSanitize']);
ng-bind-html
the original html
content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml
directive. (Read the How does it work
section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div>
would do the work.Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()
).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.
You need to define height of ul or your div and set overflow equals to auto as below:
<ul style="width: 300px; height: 200px; overflow: auto">
<li>text</li>
<li>text</li>
Here's an Omega(n log n) lower bound in comparison based model. (The only valid operation is comparing two socks.)
Suppose that you know that your 2n socks are arranged this way:
p1 p2 p3 ... pn pf(1) pf(2) ... pf(n)
where f is an unknown permutation of the set {1,2,...,n}. Knowing this cannot make the problem harder. There are n! possible outputs (matchings between first and second half), which means you need log(n!) = Omega(n log n) comparisons. This is obtainable by sorting.
Since you are interested in connections to element distinctness problem: proving the Omega(n log n) bound for element distinctness is harder, because the output is binary yes/no. Here, the output has to be a matching and the number of possible outputs suffices to get a decent bound. However, there's a variant connected to element distinctness. Suppose you are given 2n socks and wonder if they can be uniquely paired. You can get a reduction from ED by sending (a1, a2, ..., an) to (a1, a1, a2, a2, ..., an, an). (Parenthetically, the proof of hardness of ED is very interesting, via topology.)
I think that there should be an Omega(n2) bound for the original problem if you allow equality tests only. My intuition is: Consider a graph where you add an edge after a test, and argue that if the graph is not dense the output is not uniquely determined.
/Library/Java/JavaVirtualMachines/
is the correct location for the JVM to be installed. This has been the case for several years now. Many years ago, other locations were used, but no longer.
You have a choice of several vendors to obtain an installer app to install a Java implementation on your Mac. Download an installer to run locally and then discard, as you commonly do for many apps.
Your Question mentions JavaFX/OpenJFX. You might find it convenient to use a Java implementation that comes bundled with the OpenJFX libraries, such as LibericaFX from BellSoft or ZuluFX from Azul Systems.
Other answers suggesting the Homebrew package manager seem a bit extreme to me. I am sure Homebrew has some good uses. But to simply run Java, or do Java programming, installing Homebrew is a needless extra step. Installing Homebrew (package manager) for the single goal of obtaining Java is like building a landing strip to park your car instead of using your driveway. If you already have it, fine, use it. But suggesting Homebrew to those who simply need Java is poor advice.
People not already using Home-brew can simply download a Mac installer from a trusted source.
You have multiple sources to obtain an easy-to-use installer app to put Java on your Mac. Run the installer on your Mac just as you do for many other apps.
Here is a flowchart diagram for finding a source of Java 11, some of which also offer Java 8.
Download an installer from a vendor such as Adoptium(AdoptOpenJDK.net).
Run the installer.
JavaVirtualMachines
folder is now correctWhy doesn't Oracle's installer put it where it really goes? And how can I work around this problem?
Not a problem.
The folder /Library/Java/JavaVirtualMachines/
is the new home for JVMs on macOS.
To install a JVM, use an installer, discussed below.
To uninstall, simply use the Finder to delete a JVM from that folder. You will be prompted for system admin password to complete the removal.
Back in 2010, Apple joined the OpenJDK project, along with Oracle, IBM, Red Hat, Azul, and other Java vendors. Each member contributes source code, testing, and feedback to the unified OpenJDK codebase.
Apple contributed most of its Mac-specific code for its JVM. Now Apple no longer releases its own Mac-specific JVM. You now have your choice of JVM supplier, with builds coming from the OpenJDK codebase.
You will find source code at: http://openjdk.java.net
Be aware that in 2017, Oracle, the JCP, and OpenJDK have adopted a new rapid “release train” plan for regularly-scheduled versions of Java to be delivered in a predictable manner.
Read this 2018-07 Azul Systems blog post for many details, Eliminating Java Update Confusion by Simon Ritter.
Also read Java Is Still Free.
For a rather exhaustive list of past and present JVM implementations, see this page at Wikipedia.
Here is a discussion of a few vendors. See the flowchart above for more vendors
Oracle provides JDK and JRE installers for multiple platforms including macOS.
Over the years since acquiring Sun, Oracle has combined the best parts of the two JVM engines, HotSpot and JRocket, and merged them into the OpenJDK project used as the basis for their own branded implementations of Java.
Their new business plan, as of 2018, is to provide a Oracle-branded implementation of Java for a fee in production, and at no cost for use in development/testing/demo. Support for previous releases requires a paid support program. They have declared their intention for their branded release to be at feature-parity with the OpenJDK release. They have even donated their commercial add-ons such as Flight Recorder to the OpenJDK project.
Oracle also releases a build of OpenJDK with no support: http://jdk.java.net/
Oracle has produced a special purpose JDK, GraalVM.
Azul Systems provides a variety of JVM products.
Zulu
line is based directly on OpenJDK, and is available at no cost with optional paid support plans.Zing
line offers commercial JVM products enhanced with alternate technical implementations such as a specialized garbage-collector.Both of their lines offer installers for macOS.
I am currently use Zulu for Java 10.0.1 on macOS High Sierra with IntelliJ 2018.2 and Vaadin 8. I downloaded from this page. By the way, I do not find any Java-related items installed on the Apple System Preferences app.
Adoptium, formerly known as AdoptOpenJDK, is a community-led effort to build binaries of the OpenJDK source. Many of the other vendors of Java implementations support this work at Adoptium.
The OpenJ9 project is an another implementation of the JVM engine, an alternative to HotSpot.
Now sponsored at the Eclipse Foundation, with technology and backing donated by IBM in 2017.
For prebuilt binaries, they refer you to the AdoptOpenJDK project mentioned above.
The installers provided by Oracle or by Azul are both utterly simple to operate. Just run the installer app on your Mac. A window appears to indicate the progress of the installation.
When completed, verify your JVM installation by:
/Library/Java/JavaVirtualMachines/
folder to see an item for the new JVM.java -version
to see the brand and version number of your JVM.After verifying success, dismount the .dmg image in the Finder. Then trash the .dmg file you downloaded.
Just use the crossOrigin
attribute and pass 'anonymous'
as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
Try wrapping your dates in single quotes, like this:
'15-6-2005'
It should be able to parse the date this way.
This is an adaptable version of the amazing solution provided by @Gildas.Tambo elsewhere in this page. Simply change the values of the variables at the top to change the size of the "X".
Credit for the solution itself goes to Gildas. All I've done is given it adaptable math.
:root {
/* Width and height of the box containing the "X" */
--BUTTON_W: 40px;
/* This is the length of either of the 2 lines which form the "X", as a
percentage of the width of the button. */
--CLOSE_X_W: 95%;
/* Thickness of the lines of the "X" */
--CLOSE_X_THICKNESS: 4px;
}
body{
background:blue;
}
div{
width: var(--BUTTON_W);
height: var(--BUTTON_W);
background-color:red;
position: relative;
border-radius: 6px;
box-shadow: 2px 2px 4px 0 white;
}
/* The "X" in the button. "before" and "after" each represent one of the two lines of the "X" */
div:before,div:after{
content: '';
position: absolute;
width: var(--CLOSE_X_W);
height: var(--CLOSE_X_THICKNESS);
background-color:white;
border-radius: 2px;
top: calc(50% - var(--CLOSE_X_THICKNESS) / 2);
box-shadow: 0 0 2px 0 #ccc;
}
/* One line of the "X" */
div:before{
-webkit-transform:rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
left: calc((100% - var(--CLOSE_X_W)) / 2);
}
/* The other line of the "X" */
div:after{
-webkit-transform:rotate(-45deg);
-moz-transform: rotate(-45deg);
transform: rotate(-45deg);
right: calc((100% - var(--CLOSE_X_W)) / 2);
}
_x000D_
<div></div>
_x000D_
Swift 3/4/5 Solution
Select Row
let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath)
DeSelect Row
let deselectIndexPath = IndexPath(row: 7, section: 0)
tblView.deselectRow(at: deselectIndexPath, animated: true)
tblView.delegate?.tableView!(tblView, didDeselectRowAt: indexPath)
Presumably, you want count the number of items without iterating through, so that the iterator is not exhausted, and you use it again later. This is possible with copy
or deepcopy
import copy
def get_iter_len(iterator):
return sum(1 for _ in copy.copy(iterator))
###############################################
iterator = range(0, 10)
print(get_iter_len(iterator))
if len(tuple(iterator)) > 1:
print("Finding the length did not exhaust the iterator!")
else:
print("oh no! it's all gone")
The output is "Finding the length did not exhaust the iterator!
"
Optionally (and unadvisedly), you can shadow the built-in len
function as follows:
import copy
def len(obj, *, len=len):
try:
if hasattr(obj, "__len__"):
r = len(obj)
elif hasattr(obj, "__next__"):
r = sum(1 for _ in copy.copy(obj))
else:
r = len(obj)
finally:
pass
return r
Dictionary data type has a method called dict_name.pop(item)
and this can be used to delete a key:value pair from a dictionary.
a={9:4,2:3,4:2,1:3}
a.pop(9)
print(a)
This will give the output as:
{2: 3, 4: 2, 1: 3}
This way you can delete an item from a dictionary in one line.
Another simple solution would be ranking the rows and fetch one of them randomly and with this solution you won't need to have any 'Id' based column in the table.
SELECT d.* FROM (
SELECT t.*, @rownum := @rownum + 1 AS rank
FROM mytable AS t,
(SELECT @rownum := 0) AS r,
(SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM mytable))) AS n
) d WHERE rank >= @cnt LIMIT 10;
You can change the limit value as per your need to access as many rows as you want but that would mostly be consecutive values.
However, if you don't want consecutive random values then you can fetch a bigger sample and select randomly from it. something like ...
SELECT * FROM (
SELECT d.* FROM (
SELECT c.*, @rownum := @rownum + 1 AS rank
FROM buildbrain.`commits` AS c,
(SELECT @rownum := 0) AS r,
(SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM buildbrain.`commits`))) AS rnd
) d
WHERE rank >= @cnt LIMIT 10000
) t ORDER BY RAND() LIMIT 10;
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
I was in the same situation, wanting to .NET instead of a third party library. As another poster mentioned above, simply using the ZipPackage class (introduced in .NET 3.5) is not quite enough. There is an additional file that MUST be included in the archive in order for the ZipPackage to work. If this file is added, then the resulting ZIP package can be opened directly from Windows Explorer - no problem.
All you have to do is add the [Content_Types].xml file to the root of the archive with a "Default" node for every file extension you wish to include. Once added, I could browse the package from Windows Explorer or programmatically decompress and read its contents.
More information on the [Content_Types].xml file can be found here: http://msdn.microsoft.com/en-us/magazine/cc163372.aspx
Here is a sample of the [Content_Types].xml (must be named exactly) file:
<?xml version="1.0" encoding="utf-8" ?>
<Types xmlns=
"http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="xml" ContentType="text/xml" />
<Default Extension="htm" ContentType="text/html" />
<Default Extension="html" ContentType="text/html" />
<Default Extension="rels" ContentType=
"application/vnd.openxmlformats-package.relationships+xml" />
<Default Extension="jpg" ContentType="image/jpeg" />
<Default Extension="png" ContentType="image/png" />
<Default Extension="css" ContentType="text/css" />
</Types>
And the C# for creating a ZIP file:
var zipFilePath = "c:\\myfile.zip";
var tempFolderPath = "c:\\unzipped";
using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
{
source.CopyTo(File.OpenWrite(target));
}
}
}
Note:
In my case, I download the project from GitHub and the Gradle file was missing. So I just create a new project with success build. Then copy-paste the Gradle missing file. And re-build the project is working for me.
If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.
Given the following declarations:
int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc; // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc; // initialized to [3][5]
A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.
A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.
This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.
This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.
I've adapted the code from the answer of Mark Amery, particularly in order to get rid of isinstance
for the pros of duck-typing.
The encoding is done manually and ensure_ascii
is disabled. The python docs for json.dump
says that
If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences
Disclaimer: in the doctest I used the Hungarian language. Some notable Hungarian-related character encodings are: cp852
the IBM/OEM encoding used eg. in DOS (sometimes referred as ascii, incorrectly I think, it is dependent on the codepage setting), cp1250
used eg. in Windows (sometimes referred as ansi, dependent on the locale settings), and iso-8859-2
, sometimes used on http servers. The test text Tüskéshátú kígyóbuvölo
is attributed to Koltai László (native personal name form) and is from wikipedia.
# coding: utf-8
"""
This file should be encoded correctly with utf-8.
"""
import json
def encode_items(input, encoding='utf-8'):
u"""original from: https://stackoverflow.com/a/13101776/611007
adapted by SO/u/611007 (20150623)
>>>
>>> ## run this with `python -m doctest <this file>.py` from command line
>>>
>>> txt = u"Tüskéshátú kígyóbuvölo"
>>> txt2 = u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"
>>> txt3 = u"uúuutifu"
>>> txt4 = b'u\\xfauutifu'
>>> # txt4 shouldn't be 'u\\xc3\\xbauutifu', string content needs double backslash for doctest:
>>> assert u'\\u0102' not in b'u\\xfauutifu'.decode('cp1250')
>>> txt4u = txt4.decode('cp1250')
>>> assert txt4u == u'u\\xfauutifu', repr(txt4u)
>>> txt5 = b"u\\xc3\\xbauutifu"
>>> txt5u = txt5.decode('utf-8')
>>> txt6 = u"u\\u251c\\u2551uutifu"
>>> there_and_back_again = lambda t: encode_items(t, encoding='utf-8').decode('utf-8')
>>> assert txt == there_and_back_again(txt)
>>> assert txt == there_and_back_again(txt2)
>>> assert txt3 == there_and_back_again(txt3)
>>> assert txt3.encode('cp852') == there_and_back_again(txt4u).encode('cp852')
>>> assert txt3 == txt4u,(txt3,txt4u)
>>> assert txt3 == there_and_back_again(txt5)
>>> assert txt3 == there_and_back_again(txt5u)
>>> assert txt3 == there_and_back_again(txt4u)
>>> assert txt3.encode('cp1250') == encode_items(txt4, encoding='utf-8')
>>> assert txt3.encode('utf-8') == encode_items(txt5, encoding='utf-8')
>>> assert txt2.encode('utf-8') == encode_items(txt, encoding='utf-8')
>>> assert {'a':txt2.encode('utf-8')} == encode_items({'a':txt}, encoding='utf-8')
>>> assert [txt2.encode('utf-8')] == encode_items([txt], encoding='utf-8')
>>> assert [[txt2.encode('utf-8')]] == encode_items([[txt]], encoding='utf-8')
>>> assert [{'a':txt2.encode('utf-8')}] == encode_items([{'a':txt}], encoding='utf-8')
>>> assert {'b':{'a':txt2.encode('utf-8')}} == encode_items({'b':{'a':txt}}, encoding='utf-8')
"""
try:
input.iteritems
return {encode_items(k): encode_items(v) for (k,v) in input.iteritems()}
except AttributeError:
if isinstance(input, unicode):
return input.encode(encoding)
elif isinstance(input, str):
return input
try:
iter(input)
return [encode_items(e) for e in input]
except TypeError:
return input
def alt_dumps(obj, **kwargs):
"""
>>> alt_dumps({'a': u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"})
'{"a": "T\\xc3\\xbcsk\\xc3\\xa9sh\\xc3\\xa1t\\xc3\\xba k\\xc3\\xadgy\\xc3\\xb3b\\xc5\\xb1v\\xc3\\xb6l\\xc5\\x91"}'
"""
if 'ensure_ascii' in kwargs:
del kwargs['ensure_ascii']
return json.dumps(encode_items(obj), ensure_ascii=False, **kwargs)
I'd also like to highlight the answer of Jarret Hardie which references the JSON spec, quoting:
A string is a collection of zero or more Unicode characters
In my use-case I had files with json. They are utf-8
encoded files. ensure_ascii
results in properly escaped but not very readable json files, that is why I've adapted Mark Amery's answer to fit my needs.
The doctest is not particularly thoughtful but I share the code in the hope that it will useful for someone.
print(link_addres.contents[0])
It will print the context of the anchor tags
example:
statement_title = statement.find('h2',class_='briefing-statement__title')
statement_title_text = statement_title.a.contents[0]
I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.
class Doh {
def ln = System.getProperty('line.separator')
File file //assume it's initialized
void append(String content) {
file << "$content$ln"
}
}
Pretty neat I think :)
[]
is to select columns.When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.
So, in the question above: df[2]
searches for a column name matching the integer value 2
. This column does not exist and a KeyError
is raised.
Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.
df[2:3]
This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.
df[6:20:3]
You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.
I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc
.
Because line magics are only supported by the IPython command line not by Python cl, use: 'exec(%matplotlib inline)'
instead of %matplotlib inline
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
The dict
constructor accepts input exactly as you have it (key/value tuples).
>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}
From the documentation:
For example, these all return a dictionary equal to {"one": 1, "two": 2}:
dict(one=1, two=2) dict({'one': 1, 'two': 2}) dict(zip(('one', 'two'), (1, 2))) dict([['two', 2], ['one', 1]])
try
const MyFunctionnalComponent: React.FC = props => {_x000D_
useEffect(() => {_x000D_
// Using an IIFE_x000D_
(async function anyNameFunction() {_x000D_
await loadContent();_x000D_
})();_x000D_
}, []);_x000D_
return <div></div>;_x000D_
};
_x000D_
Some more info for Browser window : http://www.w3schools.com/js/js_window.asp?output=print
If you have 32-bit hardware, no, you cannot run a 64-bit guest OS. "VMware software does not emulate an instruction set for different hardware not physically present".
However, QEMU can emulate a 64-bit processor, so you could convert the VMWare machine and run it with this
From this 2008-era blog post (mirrored by archive.org):
$ cd /path/to/vmware/guestos $ for i in \`ls *[0-9].vmdk\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done $ cat *.raw >> guestos.img
To run it,
qemu -m 256 -hda guestos.img
The downside? Most of us runs VMware without preallocation space for the virtual disk. So, when we make a conversion from VMware to QEMU, the raw file will be the total space WITH preallocation. I am still testing with
-f qcow
format will it solve the problem or not. Such as:for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img