If you don't like to add lodash
or any other package:
import React, { useState, useRef } from "react";
function DebouncedInput() {
const [isRefetching, setIsRefetching] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const previousSearchTermRef = useRef("");
function setDebouncedSearchTerm(value) {
setIsRefetching(true);
setSearchTerm(value);
previousSearchTermRef.current = value;
setTimeout(async () => {
if (previousSearchTermRef.current === value) {
try {
// await refetch();
} finally {
setIsRefetching(false);
}
}
}, 500);
}
return (
<input
value={searchTerm}
onChange={(event) => setDebouncedSearchTerm(event.target.value)}
/>
);
}
You might also want to set the editor.detectIndentation
to false, in addition to Elliot-J's answer.
VSCode will overwrite your editor.tabSize
and editor.insertSpaces
settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.
The ES6 way:
let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
console.log(name);
}
also at: https://jsfiddle.net/52dpucey/
According to the Apple Human Interface Guidelines:
@1x : about 25 x 25 (max: 48 x 32)
@2x : about 50 x 50 (max: 96 x 64)
@3x : about 75 x 75 (max: 144 x 96)
In C# 6 you can use string interpolation:
string name = "John";
string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
Git Fetch
Helps you to get known about the latest updates from a git repository
. Let's say you working in a team using GitFlow
, where team working on multiple branches
( features ). With git fetch --all
command
you can get known about all new branches
within repository
.
Mostly git fetch
is used with git reset
. For example you want to revert all your local changes to the current repository state.
git fetch --all // get known about latest updates
git reset --hard origin/[branch] // revert to current branch state
Git pull
This command update your branch
with current repository
branch
state. Let's continue with GitFlow
. Multiple feature branches
was merged
to develop
branch and when you want to develop new features for the project you must go to the develop branch
and do a git pull
to get the current state of develop
branch
Documentation for GitFlow https://gist.github.com/peterdeweese/4251497
This error also occurs if you create a sub or function in a 'Microsoft Excel Object' (like Sheet1, Sheet2, ...) instead to create it in a Module.
For example:
you create with VBA a button and set .OnAction = 'btn_action'
. And Sub btn_action
you placed into the Sheet object instead into a Module.
Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.
This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.
A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.
A VBA 'Array to Range' function
Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)
' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.
' This subroutine saves repetitive coding for a common VBA and Excel task.
' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.
On Error Resume Next
'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code
Dim rngOutput As Excel.Range
Dim iRowCount As Long
Dim iColCount As Long
Dim iRow As Long
Dim iCol As Long
Dim arrTemp As Variant
Dim iDimensions As Integer
Dim iRowOffset As Long
Dim iColOffset As Long
Dim iStart As Long
Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
rngTarget.ClearContents
End If
Application.EnableEvents = True
If IsEmpty(InputArray) Then
Exit Sub
End If
If TypeName(InputArray) = "Range" Then
InputArray = InputArray.Value
End If
' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
rngTarget.Cells(1, 1).Value2 = InputArray
Exit Sub
End If
iDimensions = ArrayDimensions(InputArray)
If iDimensions < 1 Then
rngTarget.Value = CStr(InputArray)
ElseIf iDimensions = 1 Then
iRowCount = UBound(InputArray) - LBound(InputArray)
iStart = LBound(InputArray)
iColCount = 1
If iRowCount > (655354 - rngTarget.Row) Then
iRowCount = 655354 + iStart - rngTarget.Row
ReDim Preserve InputArray(iStart To iRowCount)
End If
iRowCount = UBound(InputArray) - LBound(InputArray)
iColCount = 1
' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
arrTemp(iRow, 1) = InputArray(iRow)
Next
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
rngOutput.Value2 = arrTemp
Set rngTarget = rngOutput
End With
Erase arrTemp
ElseIf iDimensions = 2 Then
iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)
iStart = LBound(InputArray, 1)
If iRowCount > (65534 - rngTarget.Row) Then
iRowCount = 65534 - rngTarget.Row
InputArray = ArrayTranspose(InputArray)
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
InputArray = ArrayTranspose(InputArray)
End If
iStart = LBound(InputArray, 2)
If iColCount > (254 - rngTarget.Column) Then
ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
End If
With rngTarget.Worksheet
Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))
Err.Clear
Application.EnableEvents = False
rngOutput.Value2 = InputArray
Application.EnableEvents = True
If Err.Number <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Formula = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
If Left(InputArray(iRow, iCol), 1) = "=" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "+" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
If Left(InputArray(iRow, iCol), 1) = "*" Then
InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Value2 = InputArray
End If 'err<>0
If Err <> 0 Then
For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
If IsObject(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
ElseIf IsArray(InputArray(iRow, iCol)) Then
InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
ElseIf IsNumeric(InputArray(iRow, iCol)) Then
' no action
Else
InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
If Len(InputArray(iRow, iCol)) > 255 Then
' Block-write operations fail on strings exceeding 255 chars. You *have*
' to go back and check, and write this masterpiece one cell at a time...
InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
End If
End If
Next iCol
Next iRow
Err.Clear
rngOutput.Text = InputArray
End If 'err<>0
If Err <> 0 Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
iRowOffset = LBound(InputArray, 1) - 1
iColOffset = LBound(InputArray, 2) - 1
For iRow = 1 To iRowCount
If iRow Mod 100 = 0 Then
Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
End If
For iCol = 1 To iColCount
rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
Next iCol
Next iRow
Application.StatusBar = False
Application.ScreenUpdating = True
End If 'err<>0
Set rngTarget = rngOutput ' resizes the range This is useful, *most* of the time
End With
End If
End Sub
You will need the source for ArrayDimensions:
This API declaration is required in the module header:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
...And here's the function itself:
Private Function ArrayDimensions(arr As Variant) As Integer
'-----------------------------------------------------------------
' will return:
' -1 if not an array
' 0 if an un-dimmed array
' 1 or more indicating the number of dimensions of a dimmed array
'-----------------------------------------------------------------
' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
' Code written by Chris Rae, 25/5/00
' Originally published by R. B. Smissaert.
' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax
Dim ptr As Long
Dim vType As Integer
Const VT_BYREF = &H4000&
'get the real VarType of the argument
'this is similar to VarType(), but returns also the VT_BYREF bit
CopyMemory vType, arr, 2
'exit if not an array
If (vType And vbArray) = 0 Then
ArrayDimensions = -1
Exit Function
End If
'get the address of the SAFEARRAY descriptor
'this is stored in the second half of the
'Variant parameter that has received the array
CopyMemory ptr, ByVal VarPtr(arr) + 8, 4
'see whether the routine was passed a Variant
'that contains an array, rather than directly an array
'in the former case ptr already points to the SA structure.
'Thanks to Monte Hansen for this fix
If (vType And VT_BYREF) Then
' ptr is a pointer to a pointer
CopyMemory ptr, ByVal ptr, 4
End If
'get the address of the SAFEARRAY structure
'this is stored in the descriptor
'get the first word of the SAFEARRAY structure
'which holds the number of dimensions
'...but first check that saAddr is non-zero, otherwise
'this routine bombs when the array is uninitialized
If ptr Then
CopyMemory ArrayDimensions, ByVal ptr, 2
End If
End Function
Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module
statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.
Try like this:
this.notifyDataSetChanged();
instead of:
adapter.notifyDataSetChanged();
You have to notifyDataSetChanged()
to the ListView
not to the adapter class.
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com")
; -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
There are two possible scenarios,
If your application runs on .net framework 4.5 or less, and you can easily deploy new code to the production then you can use of below solution.
You can add the below line of code before making the API call,
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0
If you cannot deploy new code and you want to resolve the issue with the same code which is present in the production, then you have two options.
Option 1 :
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
then create a file with extension .reg
and install.
Note : This setting will apply at registry level and is applicable to all application present on that machine and if you want to restrict to only single application then you can use Option 2
Option 2 : This can be done by changing some configuration setting in config file. You can add either in your config file.
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
</runtime>
or
<runtime>
<AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>
TryParse is usually the most elegant way to handle this type of thing:
long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
DataTO.Id = temp;
}
Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:
import cv2
def apply_mask(frame, mask):
"""Apply binary mask to frame, return in-place masked image."""
return cv2.bitwise_and(frame, frame, mask=mask)
Mask and frame must be the same size, so pixels remain as-is where mask is 1
and are set to zero where mask pixel is 0
.
And for C++
it's a little bit different:
cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask
// ...
cv::Mat outFrame; // Result output
inFrame.copyTo(outFrame, mask);
Why not use a regular expression ?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
How to build an image with custom name without using yml file:
docker build -t image_name .
How to run a container with custom name:
docker run -d --name container_name image_name
If there are NO dependencies between files... here is a recursive function to include_once ALL php files in ALL subdirs:
$paths = array();
function include_recursive( $path, $debug=false){
foreach( glob( "$path/*") as $filename){
if( strpos( $filename, '.php') !== FALSE){
# php files:
include_once $filename;
if( $debug) echo "<!-- included: $filename -->\n";
} else { # dirs
$paths[] = $filename;
}
}
# Time to process the dirs:
for( $i=count($paths)-1; $i>0; $i--){
$path = $paths[$i];
unset( $paths[$i]);
include_recursive( $path);
}
}
include_recursive( "tree_to_include");
# or... to view debug in page source:
include_recursive( "tree_to_include", 'debug');
The Win32_Process
class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.
If this is not an option for you, you can try using the taskkill
command:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000
' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True
Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows
I know I have added a lot of comments just for newbies :)
I have added an example so that you can summarize well.
$activeUsers = /** Query to get the active users */
/** Following is the Variable to store the Users data as
CSV string with newline character delimiter,
its good idea of check the delimiter based on operating system */
$userCSVData = "Name,Email,CreatedAt\n";
/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
$userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file */
$todayDate = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName = 'Active Users '.$todayDate.'.csv';
$filePath = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file
/** Just in case if I run the script multiple time
I want to remove the old file and add new file.
And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);
/** Now you can send email with attachments from the $filePath */
NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.
You have to add the following at the start of the above script.
ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');
Correct answer is simply:
SELECT a.group_id
FROM a
LEFT JOIN b ON a.group_id=b.group_id and b.user_id = 4
where b.user_id is null
and a.keyword like '%keyword%'
Here we are checking user_id = 4
(your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.
From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.
DataFrame.reset_index
is what you're looking for. If you don't want it saved as a column, then do:
df = df.reset_index(drop=True)
If you don't want to reassign:
df.reset_index(drop=True, inplace=True)
If you don't feel like importing anything, you can try:
raise SystemExit, 0
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
You can use setText(java.lang.String text,
boolean html) from MimeMessageHelper
:
MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);
But you need to:
mimeMsg.saveChanges();
Before:
javaMailSender.send(mimeMsg);
As benjymous pointed out, you can use Newtonsoft.Json with a temporary object and deserialize/serialize.
var obj = JsonConvert.DeserializeObject(jsonString);
var formatted = JsonConvert.SerializeObject(obj, Formatting.Indented);
Quite an old article on mssqlcity attempts to explain the types of locks:
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).
The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.
I deleted *.csproj.user ( resharper file) of my project, then, close all tabs and reopen it. After that I was able to compile my project and there was no resharper warnings.
Some might encounter this error either locally or on the server:
syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);
This means that their environment does not support short tags the solution is to use this instead:
<?php echo $jsonTable; ?>
And everything should work fine!
I think you can usually do what you need in a loop, which is much better than many onClick
methods if it can be done.
Check out this answer for a demonstration of how to use a loop for a similar problem. How you construct your loop will depend on the needs of your onClick
functions and how similar they are to one another. The end result is much less repetitive code that is easier to maintain.
This is how I would do it (assuming I understand the question)
SELECT * FROM pieces ORDER BY price ASC LIMIT 1
If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.
Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.
If you use findAll()
, I recommend you to use this:
$data_email = EmailArchive::model()->findAll(
array(
'condition' => 'email_id = :email_id',
'params' => array(':email_id' => $id)
)
);
Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.
If you really do just need to edit one of the info files, that's simple:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *
But if you need to edit the installable files:
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg
I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)
In Java, you can escape quotes with \
:
String value = " \"ROM\" ";
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
Use
[self dismissViewControllerAnimated:NO completion:nil];
var regex = /\d+/g;_x000D_
var string = "you can enter 30%-20% maximum 500 choices";_x000D_
var matches = string.match(regex); // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
With the xhr2 library you can globally overwrite XMLHttpRequest
from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.
global.XMLHttpRequest = require('xhr2');
Here's a simpler explanation:
You're correct that whether you use notify() or notifyAll(), the immediate result is that exactly one other thread will acquire the monitor and begin executing. (Assuming some threads were in fact blocked on wait() for this object, other unrelated threads aren't soaking up all available cores, etc.) The impact comes later.
Suppose thread A, B, and C were waiting on this object, and thread A gets the monitor. The difference lies in what happens once A releases the monitor. If you used notify(), then B and C are still blocked in wait(): they are not waiting on the monitor, they are waiting to be notified. When A releases the monitor, B and C will still be sitting there, waiting for a notify().
If you used notifyAll(), then B and C have both advanced past the "wait for notification" state and are both waiting to acquire the monitor. When A releases the monitor, either B or C will acquire it (assuming no other threads are competing for that monitor) and begin executing.
String.prototype.url = function() {
const a = $('<a />').attr('href', this)[0];
// or if you are not using jQuery
// const a = document.createElement('a'); a.setAttribute('href', this);
let origin = a.protocol + '//' + a.hostname;
if (a.port.length > 0) {
origin = `${origin}:${a.port}`;
}
const {host, hostname, pathname, port, protocol, search, hash} = a;
return {origin, host, hostname, pathname, port, protocol, search, hash};
}
Then :
'http://mysite:5050/pke45#23'.url()
//OUTPUT : {host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050", protocol: "http:",hash:"#23",origin:"http://mysite:5050"}
For your request, you need :
'http://mysite:5050/pke45#23'.url().origin
const parseUrl = (string, prop) => {
const a = document.createElement('a');
a.setAttribute('href', string);
const {host, hostname, pathname, port, protocol, search, hash} = a;
const origin = `${protocol}//${hostname}${port.length ? `:${port}`:''}`;
return prop ? eval(prop) : {origin, host, hostname, pathname, port, protocol, search, hash}
}
Then
parseUrl('http://mysite:5050/pke45#23')
// {origin: "http://mysite:5050", host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050"…}
parseUrl('http://mysite:5050/pke45#23', 'origin')
// "http://mysite:5050"
Cool!
Try this maybe :
Bootply : http://www.bootply.com/106527
Js :
$('input').on('click', function(){
var valeur = 0;
$('input:checked').each(function(){
if ( $(this).attr('value') > valeur )
{
valeur = $(this).attr('value');
}
});
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
HTML :
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<div class="row tasks">
<div class="col-md-6">
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
</div>
<div class="col-md-2">
<label>2014-01-29</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="10">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="20">
</div>
</div><!-- tasks -->
<div class="row tasks">
<div class="col-md-6">
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
</div>
<div class="col-md-2">
<label>2014-01-25</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="30">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="40">
</div>
</div><!-- tasks -->
Css
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
$(function(){_x000D_
$('input').on('click', function(){_x000D_
var valeur = 0;_x000D_
$('input:checked').each(function(){_x000D_
if ( $(this).attr('value') > valeur )_x000D_
{_x000D_
valeur = $(this).attr('value');_x000D_
}_x000D_
});_x000D_
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur); _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
background-color: #F6F8F8;_x000D_
padding: 10px;_x000D_
border-radius: 5px;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
display: block;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="progress progress-striped active">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
</div>_x000D_
</div>_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-29</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="10">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="20">_x000D_
</div>_x000D_
</div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-25</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="30">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="40">_x000D_
</div>_x000D_
</div><!-- tasks -->
_x000D_
the link to getdate: https://api.jqueryui.com/datepicker/#method-getDate
$("#datepicker").datepicker( 'getDate' );
Perhaps setOnClickListener(null)
?
kk: (01-24) will look like 01, 02..24.
HH:(00-23) will look like 00, 01..23.
hh:(01-12 in AM/PM) will look like 01, 02..12.
so the last printout (working2
) is a bit weird. It should say 12:00:00
(edit: if you were setting the working2
timezone and format, which (as kdagli pointed out) you are not)
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
The short answer
There is none. They are exactly the same.
The long answer
Both .htm and .html are exactly the same and will work in the same way. The choice is down to personal preference, provided you’re consistent with your file naming you won’t have a problem with either.
Depending on the configuration of the web server, one of the file types will take precedence over the other. This should not be an issue since it’s unlikely that you’ll have both index.htm and index.html sitting in the same folder.
We always use the shorter .htm for our file names since file extensions are typically 3 characters long.
AND MORE ON: http://www.sightspecific.com/~mosh/WWW_FAQ/ext.html or http://www.sightspecific.com/~mosh/WWW_FAQ/ext.htm
I think I should add this part here:
There is one single slight difference between .htm and .html files. Consider a path in your server like: mydomain.com/myfolder. If you create an index.htm file inside that folder and you open that like this:mydomain.com/myfolder/, it will goes crazy and spit out your files as it is in your server,
but if you create an index.html file in there and open that directory in your browser, it will load that file.
I tested this on my VPS and found this
Maybe you could somehow set your server to load index.htm files by default, but I guess the .html file is the default file type for browsers to open in each directory.
See ASP.NET Page Life Cycle Overview on MSDN for a good general introduction about what happens when a requests hits the server.
A PostBack is any request for a page that is not the first request. A PostBack will always be in response to a user action (triggered most commonly by a Button, AutoPostBack control or Ajax).
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
Add a class to the containing div, then set the following css on it:
.img-overlay {
position: relative;
max-width: 500px; //whatever your max-width should be
}
position: relative
is required on a parent element of children with position: absolute
for the children to be positioned in relation to that parent.
I confused an anonymous function with a predicate. Here's a little helper method:
WebDriverWait wait;
private void waitForById(string id)
{
if (wait == null)
wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
//wait.Until(driver);
wait.Until(d => d.FindElement(By.Id(id)));
}
Adding java.util.list
will resolve your problem because List interface which you are trying to use is part of java.util.list
package.
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
Yes, that's exactly what it's for.
This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
TL;DR
Transient objects are always different; a new instance is provided to every controller and every service.
Scoped objects are the same within a request, but different across different requests.
Singleton objects are the same for every object and every request.
For more clarification, this example from .NET documentation shows the difference:
To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, OperationId
. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:
using System;
namespace DependencyInjectionSample.Interfaces
{
public interface IOperation
{
Guid OperationId { get; }
}
public interface IOperationTransient : IOperation
{
}
public interface IOperationScoped : IOperation
{
}
public interface IOperationSingleton : IOperation
{
}
public interface IOperationSingletonInstance : IOperation
{
}
}
We implement these interfaces using a single class, Operation
, that accepts a GUID in its constructor, or uses a new GUID if none is provided:
using System;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Classes
{
public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
{
Guid _guid;
public Operation() : this(Guid.NewGuid())
{
}
public Operation(Guid guid)
{
_guid = guid;
}
public Guid OperationId => _guid;
}
}
Next, in ConfigureServices
, each type is added to the container according to its named lifetime:
services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();
Note that the IOperationSingletonInstance
service is using a specific instance with a known ID of Guid.Empty
, so it will be clear when this type is in use. We have also registered an OperationService
that depends on each of the other Operation
types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Services
{
public class OperationService
{
public IOperationTransient TransientOperation { get; }
public IOperationScoped ScopedOperation { get; }
public IOperationSingleton SingletonOperation { get; }
public IOperationSingletonInstance SingletonInstanceOperation { get; }
public OperationService(IOperationTransient transientOperation,
IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance instanceOperation)
{
TransientOperation = transientOperation;
ScopedOperation = scopedOperation;
SingletonOperation = singletonOperation;
SingletonInstanceOperation = instanceOperation;
}
}
}
To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an OperationsController
that requests each kind of IOperation
type as well as an OperationService
. The Index
action then displays all of the controller’s and service’s OperationId
values.
using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;
namespace DependencyInjectionSample.Controllers
{
public class OperationsController : Controller
{
private readonly OperationService _operationService;
private readonly IOperationTransient _transientOperation;
private readonly IOperationScoped _scopedOperation;
private readonly IOperationSingleton _singletonOperation;
private readonly IOperationSingletonInstance _singletonInstanceOperation;
public OperationsController(OperationService operationService,
IOperationTransient transientOperation,
IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance singletonInstanceOperation)
{
_operationService = operationService;
_transientOperation = transientOperation;
_scopedOperation = scopedOperation;
_singletonOperation = singletonOperation;
_singletonInstanceOperation = singletonInstanceOperation;
}
public IActionResult Index()
{
// ViewBag contains controller-requested services
ViewBag.Transient = _transientOperation;
ViewBag.Scoped = _scopedOperation;
ViewBag.Singleton = _singletonOperation;
ViewBag.SingletonInstance = _singletonInstanceOperation;
// Operation service has its own requested services
ViewBag.Service = _operationService;
return View();
}
}
}
Now two separate requests are made to this controller action:
Observe which of the OperationId
values varies within a request, and between requests.
Transient objects are always different; a new instance is provided to every controller and every service.
Scoped objects are the same within a request, but different across different requests
Singleton objects are the same for every object and every request (regardless of whether an instance is provided in ConfigureServices
)
The configuration file is called applicationhost.config. It's stored here:
My Documents > IIS Express > config
usually, but not always, one of these paths will work
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Update for VS2019
If you're using Visual Studio 2019+ check this path:
$(solutionDir)\.vs\{projectName}\config\applicationhost.config
Update for VS2015 (credit: @Talon)
If you're using Visual Studio 2015-2017 check this path:
$(solutionDir)\.vs\config\applicationhost.config
In Visual Studio 2015+ you can also configure which applicationhost.config file is used by altering the <UseGlobalApplicationHostFile>true|false</UseGlobalApplicationHostFile>
setting in the project file (eg: MyProject.csproj). (source: MSDN forum)
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.
The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.
This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.
in perl if you forget
print "content-type: text/html\r\n\r\n";
you will get this error
There are many reasons for it. so please first check your error log and then provide some more information.
The default error log is often in /var/log/httpd/error_log
or /var/log/apache2/error.log
.
The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.
Assumes linux and not necessarily perl
Also note, after hitting the regex icon, to actually replace \n
text with a newline, I had to use \\n
as search and \n
as replace.
To exclude the first line (header) from sorting, I split it out into two buffers.
df | awk 'BEGIN{header=""; $body=""} { if(NR==1){header=$0}else{body=body"\n"$0}} END{print header; print body|"sort -nk3"}'
In my project, once it happened that someone manually entered the records without using sequence, hence I have to reset sequence value manually, for which I wrote below sql code snippet:
declare
max_db_value number(10,0);
cur_seq_value number(10,0);
counter number(10,0);
difference number(10,0);
dummy_number number(10);
begin
-- enter table name here
select max(id) into max_db_value from persons;
-- enter sequence name here
select last_number into cur_seq_value from user_sequences where sequence_name = 'SEQ_PERSONS';
difference := max_db_value - cur_seq_value;
for counter in 1..difference
loop
-- change sequence name here as well
select SEQ_PERSONS.nextval into dummy_number from dual;
end loop;
end;
Please note, the above code will work if the sequence is lagging.
Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .
You're using the wrong method calls. A viewport is the "window" that's open on the document: how much of it you can see and where.
Using $(window).height()
will not give you the viewport size it will give you the size of the entire window, which is usually the size of the entire document though the document could be even larger.
To get the size of the actual viewport use window.innerHeight
and window.innerWidth
.
https://gist.github.com/bohman/1351439
Do not use the jQuery methods, e.g. $(window).innerHeight()
, as these give the wrong numbers. They give you the window's height, not innerHeight
.
scroll.fullScroll(View.FOCUS_DOWN)
will lead to the change of focus. That will bring some strange behavior when there are more than one focusable views, e.g two EditText. There is another way for this question.
View lastChild = scrollLayout.getChildAt(scrollLayout.getChildCount() - 1);
int bottom = lastChild.getBottom() + scrollLayout.getPaddingBottom();
int sy = scrollLayout.getScrollY();
int sh = scrollLayout.getHeight();
int delta = bottom - (sy + sh);
scrollLayout.smoothScrollBy(0, delta);
This works well.
Kotlin Extension
fun ScrollView.scrollToBottom() {
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY+ height)
smoothScrollBy(0, delta)
}
If you can't use overflow: hidden
(because you don't want overflow: hidden
) or if you dislike CSS hacks/workarounds, you could use JavaScript instead. Note that it may not work as well because it's JavaScript.
var parent = document.getElementsByClassName("lineContainer")[0];_x000D_
var left = document.getElementsByClassName("left")[0];_x000D_
var right = document.getElementsByClassName("right")[0];_x000D_
right.style.width = (parent.offsetWidth - left.offsetWidth) + "px";_x000D_
window.onresize = function() {_x000D_
right.style.width = (parent.offsetWidth - left.offsetWidth) + "px";_x000D_
}
_x000D_
.lineContainer {_x000D_
width: 100% border: 1px solid #000;_x000D_
font-size: 0px;_x000D_
/* You need to do this because inline block puts an invisible space between them and they won't fit on the same line */_x000D_
}_x000D_
_x000D_
.lineContainer div {_x000D_
height: 10px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.left {_x000D_
width: 100px;_x000D_
background: red_x000D_
}_x000D_
_x000D_
.right {_x000D_
background: blue_x000D_
}
_x000D_
<div class="lineContainer">_x000D_
<div class="left"></div>_x000D_
<div class="right"></div>_x000D_
</div>
_x000D_
The best to remove a class in jquery from all the elements is to target via element tag. e.g.,
$("div").removeClass("highlight");
The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.
HTML
<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
Nothing here
</div>
You can use CSS to style the main section of the dialog but not the title
.custom-ui-widget-header-warning {
background: #EBCCCC;
font-size: 1em;
}
You need some JS to style the title
$(function() {
$("#nonmodal1").dialog({
minWidth: 400,
minHeight: 'auto',
autoOpen: false,
dialogClass: 'custom-ui-widget-header-warning',
position: {
my: 'center',
at: 'left'
}
});
$("#dialog1").click(function() {
if ($("#nonmodal1").dialog("isOpen") === true) {
$("#nonmodal1").dialog("close");
} else {
$("#nonmodal1").dialog("open").prev().css('background','#D9534F');
}
});
});
The example only shows simple styling (background) but you can make it as complex as you wish.
You can see it in action here:
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden
, so when setting my pictures to width: 100%
the pictures would look vertically cut, and so I forced them to be visible with !important
and to avoid showing the slide animation out of the box I set overflow: hidden
to the container div of the slide. Hope it works for you.
UPDATE - New Solution:
Original problem -> http://jsfiddle.net/xMddf/1/
(Even if I use overflow-y: visible
it becomes "auto" and actually "scroll".)
#content {
height: 100px;
width: 200px;
overflow-x: hidden;
overflow-y: visible;
}
The new solution -> http://jsfiddle.net/xMddf/2/
(I found a workaround using a wrapper div to apply overflow-x
and overflow-y
to different DOM elements as James Khoury advised on the problem of combining visible
and hidden
to a single DOM element.)
#wrapper {
height: 100px;
overflow-y: visible;
}
#content {
width: 200px;
overflow-x: hidden;
}
File>Settings...>Editor>General>
then you'll find this in the menu Mouse,
"change the font size(Zoom) with Ctrl+Mouse Wheel"
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
You can pass the necessary variables from the parent scope into the closure with the use
keyword.
For example:
DB::table('users')->where(function ($query) use ($activated) {
$query->where('activated', '=', $activated);
})->get();
More on that here.
PHP 7.4 (will be released at November 28, 2019) introduces a shorter variation of the anonymous functions called arrow functions which makes this a bit less verbose.
An example using PHP 7.4 which is functionally nearly equivalent (see the 3rd bullet point below):
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
Differences compared to the regular syntax:
fn
keyword instead of function
.use
keyword in the latter example.void
return type when declaring them.return
keyword must be omitted.I know this thread is old, but this could be another solution:
var do_this = null;
function y(){
// what you wanna do
}
do_this = setInterval(y, 1000);
function y_start(){
do_this = setInterval(y, 1000);
};
function y_stop(){
do_this = clearInterval(do_this);
};
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
The other simple way, use docker-compose with the following lines:
mysql:
from: mysql:5.7
volumes:
- ./database:/tmp/database
command: mysqld --init-file="/tmp/database/install_db.sql"
Put your database schema into the ./database/install_db.sql. Every time when you build up your container, the install_db.sql will be executed.
Nesting Text components is not possible now, but you can wrap your text in a View like this:
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text>
{'Hello '}
</Text>
<Text style={{fontWeight: 'bold'}}>
{'this is a bold text '}
</Text>
<Text>
and this is not
</Text>
</View>
I used the strings inside the brackets to force the space between words, but you can also achieve it with marginRight or marginLeft. Hope it helps.
You should use PDO Prepare
From the link:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
just use:
$ sudo mysql
without the "-u root" parameter.
Use a LEFT JOIN checking the right side for nulls.
SELECT a.Id
FROM TableA a
LEFT JOIN TableB on a.Id = b.Id
WHERE b.Id IS NULL
The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.
the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html
body {
width: calc( 100% );
max-width: calc( 100vw - 1em );
}
works with default scroll bars as well. could add:
overflow-x: hidden;
to ensure horizontal scroll bars remain hidden for the parent frame. unless this is desired from your clients.
I ran into this recently and running the following fixed all the problems
mvn -fae install
I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.
DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img
tags, so this event ensure that all the img
loaded but no the images properly loaded or not. To get this event you should write following way:
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
Or using jQuery:
$(document).ready(function(){
// your code
});
After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img
tag it will ensure also all images or other relative content loaded. To get this event you should write following way:
window.addEventListener('load', function() {...})
Or using jQuery:
$(window).on('load', function() {
console.log('All assets are loaded')
})
This is a bit of an outlier and not likely to be what the OP was dealing with, but pod update <podname>
will not work in all cases if you are using a local pod on your computer.
In this situation, the only thing that will trigger pod update
to work is if there is a change in the podspec file. However, making a change will also allow for pod install
to work as well.
In this situation, you can just modify something minor such as the description or summary by one letter, and then you can run the install or update command successfully.
All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span
element to control the size. This SO Question may help you out
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:
byte[] fullyReadFileToBytes(File f) throws IOException {
int size = (int) f.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis= new FileInputStream(f);;
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e){
throw e;
} finally {
fis.close();
}
return bytes;
}
NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.
Create function fn_GetNumbersOnly(@pn varchar(100))
Returns varchar(max)
AS
BEGIN
Declare @r varchar(max) ='', @len int ,@c char(1), @x int = 0
Select @len = len(@pn)
while @x <= @len
begin
Select @c = SUBSTRING(@pn,@x,1)
if ISNUMERIC(@c) = 1 and @c <> '-'
Select @r = @r + @c
Select @x = @x +1
end
return @r
End
Another alternative solution is to use Array.prototype.reduce()
:
["Nano","Volvo","BMW","Nano","VW","Nano"].reduce(function(a, e, i) {
if (e === 'Nano')
a.push(i);
return a;
}, []); // [0, 3, 5]
N.B.: Check the browser compatibility for reduce
method and use polyfill if required.
An empty array is falsey in PHP, so you don't even need to use empty()
as others have suggested.
<?php
$playerList = array();
if (!$playerList) {
echo "No players";
} else {
echo "Explode stuff...";
}
// Output is: No players
PHP's empty()
determines if a variable doesn't exist or has a falsey value (like array()
, 0
, null
, false
, etc).
In most cases you just want to check !$emptyVar
. Use empty($emptyVar)
if the variable might not have been set AND you don't wont to trigger an E_NOTICE
; IMO this is generally a bad idea.
When you boil down to it, it's just a fancy overly-complicated proxy, but maybe Catch-All Proxies could do it?
var o = {
a: 'a',
b: 'b',
func: function() { return 'func'; }
};
var proxy = Proxy.create(handlerMaker(o), o);
(function(x){
var obj = x;
console.log(x.a);
console.log(x.b);
obj.foo = 'foo';
obj.bar = 'bar';
})(proxy);
console.log(o.foo);
function handlerMaker(obj) {
return {
getOwnPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name);
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name); // not in ES5
// a trapping proxy's properties must always be configurable
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
getOwnPropertyNames: function() {
return Object.getOwnPropertyNames(obj);
},
getPropertyNames: function() {
return Object.getPropertyNames(obj); // not in ES5
},
defineProperty: function(name, desc) {
},
delete: function(name) { return delete obj[name]; },
fix: function() {}
};
}
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
You can delete individual names with del
:
del x
or you can remove them from the globals()
object:
for name in dir():
if not name.startswith('_'):
del globals()[name]
This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.
Modules you've imported (import os
) are going to remain imported because they are referenced by sys.modules
; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn't see my issue outlined in other questions with a similar title).
Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.
Hopefully this saves someone else some time!
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
Delaying showing the route is sure to lead to an asynchronous tangle... why not simply track the loading status of your main entity and use that in the view. For example in your controller you might use both the success and error callbacks on ngResource:
$scope.httpStatus = 0; // in progress
$scope.projects = $resource.query('/projects', function() {
$scope.httpStatus = 200;
}, function(response) {
$scope.httpStatus = response.status;
});
Then in the view you could do whatever:
<div ng-show="httpStatus == 0">
Loading
</div>
<div ng-show="httpStatus == 200">
Real stuff
<div ng-repeat="project in projects">
...
</div>
</div>
<div ng-show="httpStatus >= 400">
Error, not found, etc. Could distinguish 4xx not found from
5xx server error even.
</div>
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
In MySql, you can get 10 rows starting from row 20 using:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10
Since YouTube has deprecated the showinfo parameter you can trick the player. Youtube will always try to center its video but logo, title, watch later button etc.. will always stay at the left and right side respectively.
So what you can do is put your Youtube iframe inside some div:
<div class="frame-container">
<iframe></iframe>
</div>
Then you can increase the size of frame-container to be out of browser window, while aligning it so that the iframe video comes to the center. Example:
.frame-container {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
width: 300%; /* enlarge beyond browser width */
left: -100%; /* center */
}
.frame-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Finnaly put everything inside a wrapper div to prevent page stretching due to 300% width:
<div class="wrapper">
<div class="frame-container">
<iframe></iframe>
</div>
</div>
.wrapper {
overflow: hidden;
max-width: 100%;
}
Flexbox was created for exactly these kind of problems:
#container {_x000D_
height: 150px;/*Only for the demo.*/_x000D_
background-color:green;/*Only for the demo.*/_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: flex-end;_x000D_
}
_x000D_
<div id="container">_x000D_
<span>Text align to center bottom.</span>_x000D_
</div>
_x000D_
If you don't want to mess with table displays, then you can create a <div>
inside a relatively positioned parent container, place it to the bottom with absolute positioning, then make it 100% wide, so you can text-align
it to the center:
#container {_x000D_
height: 150px;/*Only for the demo.*/_x000D_
background-color:green;/*Only for the demo.*/_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#text {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<span id="text">Text align to center bottom.</span>_x000D_
</div>
_x000D_
To get around the html
vs body
issue, I fixed this by not animating the css directly but rather calling window.scrollTo();
on each step:
$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});
This works nicely without any refresh gotchas as it's using cross-browser JavaScript.
Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.
Not possible. The background will always be as large as it can be, but you can stop it from repeating itself with background-repeat
.
background-repeat: no-repeat;
Secondly, the background does not go into margin-area of a box, so if you want to have the background only be on the actual contents of a box, you can use margin instead of padding.
Thirdly, you can control where the background image starts. By default it's the top left corner of a box, but you can control that with background-position
, like this:
background-position: center top;
or perhaps
background-position: 20px -14px;
Negative positioning is used a lot with CSS sprites.
I was looking for the solution on net and the below works for me. Ref.
And you call the function like this :
SELECT * FROM dbo.split('ram shyam hari gopal',' ')
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Split](@String VARCHAR(8000), @Delimiter CHAR(1))
RETURNS @temptable TABLE (items VARCHAR(8000))
AS
BEGIN
DECLARE @idx INT
DECLARE @slice VARCHAR(8000)
SELECT @idx = 1
IF len(@String)<1 OR @String IS NULL RETURN
WHILE @idx!= 0
BEGIN
SET @idx = charindex(@Delimiter,@String)
IF @idx!=0
SET @slice = LEFT(@String,@idx - 1)
ELSE
SET @slice = @String
IF(len(@slice)>0)
INSERT INTO @temptable(Items) VALUES(@slice)
SET @String = RIGHT(@String,len(@String) - @idx)
IF len(@String) = 0 break
END
RETURN
END
This doesn't have anything to do with jQuery. You can use the JavaScript replace
function for this:
var str = "data-123";
str = str.replace("data-", "");
You can also pass a regex to this function. In the following example, it would replace everything except numerics:
str = str.replace(/[^0-9\.]+/g, "");
The default sort is stable, so we sort twice: First by the minor key, then by the major key
rum1 <- rum[order(rum$I2, decreasing = FALSE),]
rum2 <- rum1[order(rum1$I1, decreasing = TRUE),]
I use the consolidate function, like so:
element.transform.baseVal.consolidate()
The .e and .f values correspond to the x and y coordinates
If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.
def foo():
print(self.bar)
>NameError: name 'self' is not defined
def foo(self):
print(self.bar)
Actually, the real solution is the selection of the project template itself. You MUST select Win32 Console Application in older VS, or fill in the project name first and then double click on Windows Desktop wizard and then select Win32 console application. Then select empty project at this point. This then allows for what the original questioner really wanted without adding extra stopping point and hold code. I went through this problem as well. The answer is also at MSDN site.
In PHP 5.4 the intl
extension provides a new class named Transliterator.
I believe that's the best way to remove diacritics for two reasons:
Transliterator is based on ICU, so you're using the tables of the ICU library. ICU is a great project, developed over the year to provide comprehensive tables and functionalities. Whatever table you want to write yourself, it will never be as complete as the one from ICU.
In UTF-8, characters could be represented differently. For example, the character ñ could be saved as a single (multi-byte) character, or as the combination of characters ˜
(multibyte) and n
. In addition to this, some characters in Unicode are homograph: they look the same while having different codepoints. For this reason it's also important to normalize the string.
Here's a sample code, taken from an old answer of mine:
<?php
$transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
$test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto'];
foreach($test as $e) {
$normalized = $transliterator->transliterate($e);
echo $e. ' --> '.$normalized."\n";
}
?>
Result:
abcd --> abcd
èe --> ee
€ --> €
àòùìéëü --> aouieeu
àòùìéëü --> aouieeu
tiësto --> tiesto
The first argument for the Transliterator class performs the removal of diacritics as well as the normalization of the string.
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
fromEvent<KeyboardEvent>(document.querySelector('#searcha') as HTMLInputElement , 'keyup')
.pipe(
debounceTime(500),
distinctUntilChanged(),
map(e => {
return e.target['value']; // <-- target does not exist on {}
})
).subscribe(k => console.log(k));
Maybe something like the above could help. Change it based on the real code. The issue is ........ target['value']
The solution in a more elegant way.
var myData=['237','124','255','124','366','255'];
console.log(Array.from(new Set(myData)).sort());
_x000D_
I know the question is very old, but maybe someone will come in handy
I had the same problem when parsing html
to string
. Removing the last <p></p>
(and replacing it with an alternative if desirable, like < /br>) solved it for me.
This took me a while to figure out, as the conventional window['someFunctionName']()
did not work for me at first. The names of my functions were being pulled as an AJAX response from a database. Also, for whatever reason, my functions were declared outside of the scope of the window, so in order to fix this I had to rewrite the functions I was calling from
function someFunctionName() {}
to
window.someFunctionName = function() {}
and from there I could call window['someFunctionName']()
with ease. I hope this helps someone!
You can use this jQuery function instead of plus Bootstrap tooltip
function DDLSToolTipping(ddlsArray) {
$(ddlsArray).each(function (index, ddl) {
DDLToolTipping(ddl)
});
}
function DDLToolTipping(ddlID, maxLength, allowDots) {
if (maxLength == null) { maxLength = 12 }
if (allowDots == null) { allowDots = true }
var selectedOption = $(ddlID).find('option:selected').text();
if (selectedOption.length > maxLength) {
$(ddlID).attr('data-toggle', "tooltip")
.attr('title', selectedOption);
if (allowDots) {
$(ddlID).prev('sup').remove();
$(ddlID).before(
"<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
)
}
}
else if ($(ddlID).attr('title') != null) {
$(ddlID).removeAttr('data-toggle')
.removeAttr('title');
}
}
what worked for me is just define the variable outside this function of your.
Just before main function declare i.e.
Double price;
public static void main(String []args(){
--------
--------
}
Fewer lines for 2019 searchers:
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
plt.savefig('output.png')
UPDATE NOTE: size
was changed to height
.
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
var address = zipcode;_x000D_
geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
if (status == google.maps.GeocoderStatus.OK) {_x000D_
var latitude = results[0].geometry.location.lat();_x000D_
var longitude = results[0].geometry.location.lng();_x000D_
alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
} else {_x000D_
alert("Request failed.")_x000D_
}_x000D_
});_x000D_
return [latitude, longitude];_x000D_
}
_x000D_
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
Don't forget that you can always cut and paste into the minibuffer.
So you can just copy a newline character (or any string) from your buffer, then yank it when prompted for the replacement text.
Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>
#include <breakermindsslserver.h>
using namespace std;
int main(int argc, char *argv[])
{
BreakermindSslServer boom;
boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
return 0;
}
I understand you want to trash your local changes and pull down what's on your remote?
If all else fails, and if you're (quite understandably) scared of "reset", the simplest thing is just to clone origin into a new directory and trash your old one.
I assume you're trying to tunnel into some unix box.
Make sure X11 forwarding is enabled in your PuTTY settings.
Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:
$this->session->set_userdata('language', ENGLISH);
Then you can grab it anytime like this:
$language = $this->session->userdata('language');
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
There is a system function called ISNUMERIC for SQL 2008 and up. An example:
SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;
I did a couple of quick tests and also looked further into the docs:
ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.
Which means it is fairly predictable for example
-9879210433
would pass but 987921-0433
does not.
$9879210433
would pass but 9879210$433
does not.
So using this information you can weed out based on the list of valid currency symbols and +
& -
characters.
This worked for me
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/Logo"
android:gravity="center"
android:scaleType="centerInside"
android:src="@drawable/logo" />
</LinearLayout>
You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)
As an additional note, you may also add markup language for pausing or waiting, I learned this from the iPhone iOS which allows numbers to be stored with extension numbers in the same line. A semi-colon establishes a wait, which will show as a next step upon calling the number. This helps to simplify the workflow of calling numbers with extensions in their board. You press the button shown on the bottom left of the iPhone screen when prompted, and the iPhone will dial it automatically.
<a href="tel:+50225079227;1">Call Now</a>
The pause is entered with a comma ",", allowing a short pause of time for each comma. Once the time has passed, the number after the comma will be dialed automatically
<a href="tel:+50225079227,1">Call Now, you will be automaticlaly transferred</a>
Use Fail module.
- fail: msg="The execution has failed because of errors." when: flag == "failed"
Update:
Use register to store the result of a task like you have shown in your example. Then, use a task like this:
- name: Set flag
set_fact: flag = failed
when: "'FAILED' in command_result.stderr"
This should work
// In Activity's onCreate() for instance
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
If you're already logged into the command line client try this:
mysql> select user();
It will output something similar to this:
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.41 sec)
In my example above, I was logged in as root
from localhost
.
To find port number and other interesting settings use this command:
mysql> show variables;
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
Even thought it is not resizing, another trick may help in the situation when the UIPicker is located at the bottom of the screen.
One can try moving it slightly downwards, but the central row should remain visible. This will help reveal some space above the picker since bottom rows will be offscreen.
I repeat that this is not the way of changing UIPicker view's height but some idea on what you can do if all other attempts fail.
Edit
Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Now you can call myElement.removeClass('myClass')
or chain it: myElement.removeClass("oldClass").addClass("newClass");
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
In Haskell:
filter ((==) 12345 . sum) $ subsequences [1,5,22,15,0,..]
And J:
(]#~12345=+/@>)(]<@#~[:#:@i.2^#)1 5 22 15 0 ...
As you may notice, both take the same approach and divide the problem into two parts: generate each member of the power set, and check each member's sum to the target.
There are other solutions but this is the most straightforward.
Do you need help with either one, or finding a different approach?
For my use case, I needed to access just the system properties, but provide default values in case they are undefined.
This is how you do it:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="myBean" class="path.to.my.BeanClass">
<!-- can be overridden with -Dtest.target.host=http://whatever.com -->
<constructor-arg value="${test.target.host:http://localhost:18888}"/>
</bean>
The extreme and simple cases:
A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.
An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN
or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn't "learn" anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it's dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes... whatever.
With those out of the way, let me explain that life ain't so simple any more. For instance,
In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of "understanding" the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.
As with the present java SE 8 release with it's excellent date time API with java.time
these kind of calculation can be done more easily instead of using java.util.Calendar
and java.util.Date
.
Now as a sample example for scheduling a task with your use case:
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initalDelay = duration.getSeconds();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new MyRunnableTask(),
initalDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
The initalDelay
is computed to ask the scheduler to delay the execution in TimeUnit.SECONDS
. Time difference issues with unit milliseconds and below seems to be negligible for this use case. But you can still make use of duration.toMillis()
and TimeUnit.MILLISECONDS
for handling the scheduling computaions in milliseconds.
And also TimerTask is better for this or ScheduledExecutorService?
NO: ScheduledExecutorService
seemingly better than TimerTask
. StackOverflow has already an answer for you.
From @PaddyD,
You still have the issue whereby you need to restart this twice a year if you want it to run at the right local time. scheduleAtFixedRate won't cut it unless you are happy with the same UTC time all year.
As it is true and @PaddyD already has given a workaround(+1 to him), I am providing a working example with Java8 date time API with ScheduledExecutorService
. Using daemon thread is dangerous
class MyTaskExecutor
{
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
MyTask myTask;
volatile boolean isStopIssued;
public MyTaskExecutor(MyTask myTask$)
{
myTask = myTask$;
}
public void startExecutionAt(int targetHour, int targetMin, int targetSec)
{
Runnable taskWrapper = new Runnable(){
@Override
public void run()
{
myTask.execute();
startExecutionAt(targetHour, targetMin, targetSec);
}
};
long delay = computeNextDelay(targetHour, targetMin, targetSec);
executorService.schedule(taskWrapper, delay, TimeUnit.SECONDS);
}
private long computeNextDelay(int targetHour, int targetMin, int targetSec)
{
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
if(zonedNow.compareTo(zonedNextTarget) > 0)
zonedNextTarget = zonedNextTarget.plusDays(1);
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
public void stop()
{
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) {
Logger.getLogger(MyTaskExecutor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note:
MyTask
is an interface with function execute
. ScheduledExecutorService
, Always use awaitTermination
after invoking shutdown
on it: There's always a likelihood your task is stuck / deadlocking and the user would wait forever.The previous example I gave with Calender was just an idea which I did mention, I avoided exact time calculation and Daylight saving issues. Updated the solution on per the complain of @PaddyD
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY
If PIDKEY value is empty try to look at the subfolders e.g.
...\Registration\1000.0x0000\PIDKEY
or
...\Registration\2000.0x0000\PIDKEY
Don't use exec
. Use spawn
which is an EventEmmiter
object. Then you can listen to stdout
/stderr
events (spawn.stdout.on('data',callback..)
) as they happen.
From NodeJS documentation:
var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data.toString());
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data.toString());
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code.toString());
});
exec
buffers the output and usually returns it when the command has finished executing.
I am having/had similar issues with Bootstrap 4, alpha-6, and Joakim Johanssons answer above started me in the right direction. No javascript required. Putting data-target=".navbar-collapse" and data-toggle="collapse" into the div tag inside the nav, but surrounding the links/buttons, worked for me.
<div class="navbar-nav" data-target=".navbar-collapse" data-toggle="collapse">_x000D_
<a class="nav-item nav-link" href="#">Menu Item 1</a>_x000D_
..._x000D_
</div>
_x000D_
In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"
Works for mac too.
You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
where AcceptAllCertifications
is defined as
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
To use the fastboot command you first need to put your device in fastboot mode:
$ adb reboot bootloader
Once the device is in fastboot mode, you can boot it with your own kernel, for example:
$ fastboot boot myboot.img
The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:
$ fastboot flash boot myboot.img
Hope that helps.
Another obnoxious error type I've encountered in Oracle 11: entries in tnsnames.ora that don't begin at the first column of the line (' XXX=(...)' instead of 'XXX=(...)') and are parsed together with the preceding entry, making it malformed.
Like replaced orr misplaced tnsnames.ora files, this type of problem is easy to diagnose with the tnsping
command-line utility: you pass it the name of a tnsnames.ora entry and it gives the complete text of its definition.
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
Assuming that you have a DHCP server running at your router I would use:
# /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
After changing the file issue (as root):
/etc/init.d/networking restart
shift
spaces.Restrictions:
Pseudocode:
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
You can obtain all jQuery events using $._data($('[selector]')[0],'events'); change [selector] to what you need.
There is a plugin that gather all events attached by jQuery called eventsReport.
Also i write my own plugin that do this with better formatting.
But anyway it seems we can't gather events added by addEventListener method. May be we can wrap addEventListener call to store events added after our wrap call.
It seems the best way to see events added to an element with dev tools.
But you will not see delegated events there. So there we need jQuery eventsReport.
UPDATE: NOW We CAN see events added by addEventListener method SEE RIGHT ANSWER TO THIS QUESTION.
Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See this prior answer for details and examples.
You declare the GUC in postgresql.conf
, then change its value at runtime with SET
commands and get its value with current_setting(...)
.
I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.
You can modify the id
without having to use getElementById
Example:
<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
You can see it here: http://jsbin.com/elikaj/1/
Tested with Mozilla Firefox 22 and Google Chrome 60.0
From perldoc perldata, which should be safe to quote:
The following is always true:
scalar(@whatever) == $#whatever + 1;
Just so long as you don't $#whatever++ and mysteriously increase the size or your array.
The array indices start with 0.
and
You can truncate an array down to nothing by assigning the null list () to it. The following are equivalent:
@whatever = (); $#whatever = -1;
Which brings me to what I was looking for which is how to detect the array is empty. I found it if $#empty == -1;
take look at my example
<tocheading language="EN">
<subj-group>
<subject>Editors Choice</subject>
<subject>creative common</subject>
</subj-group>
</tocheading>
now how to check if creative common
is exist
tocheading/subj-group/subject/text() = 'creative common'
hope this help you
You can just use the Paths
class:
Path path = Paths.get(textPath);
... assuming you want to use the default file system, of course.
Access your list elements directly by i. Then you can append to your list:
for i in xrange(len(myarr)):
if somecond(a[i]):
myarr.append(newObj())
I'm pretty sure you can't simply add on delete cascade
to an existing foreign key constraint. You have to drop the constraint first, then add the correct version. In standard SQL, I believe the easiest way to do this is to
on delete cascade
, and finallyRepeat for each foreign key you want to change.
But PostgreSQL has a non-standard extension that lets you use multiple constraint clauses in a single SQL statement. For example
alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
foreign key (gid)
references games(gid)
on delete cascade;
If you don't know the name of the foreign key constraint you want to drop, you can either look it up in pgAdminIII (just click the table name and look at the DDL, or expand the hierarchy until you see "Constraints"), or you can query the information schema.
select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null
Below code will hide your text with fixed width you decide. but not quite right for responsive designs.
.CropLongTexts {
width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Update
I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:
.CropLongTexts {
max-width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.
Had the same issue where I have changes in a local branch where I wanted to revert just one file. What worked for me was -
(feature/target_branch below is where I have all my changes including those I wanted to undo for a specific file)
(origin/feature/target_branch is the remote branch where I want to push my changes to)
(feature/staging is my temporary staging branch where I will be pushing from all my wanted changes excluding the change to that one file)
Create a local branch from my origin/feature/target_branch - called it feature/staging
Merged my working local branch feature/target_branch to the feature/staging branch
Checked out feature/staging then git reset --soft ORIG_HEAD (Now all changes from the feature/staging' will be staged but uncommitted.)
Unstaged the file which I have previously checked in with unnecessary changes
Changed the upstream branch for feature/staging to origin/feature/target_branch
Committed the rest of the staged changes and pushed upstream to my remote origin/feature/target_branch
You can use the curses.h
library in linux as mentioned in the other answer.
You can install it in Ubuntu by:
sudo apt-get update
sudo apt-get install ncurses-dev
I took the installation part from here.
Using the momentjs library, this can be achieved with the startOf()
and endOf()
methods on the moment's current date object, passing the string 'day'
as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today
var start = moment.utc().startOf('day');
var end = moment.utc().endOf('day');
But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?
For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.
For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.
One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.
class ThingsKeeper
def __init__(self):
self.__things = []
def things(self):
return self.__things #outside objects can now modify your state
def safer(self):
return self.__things[:] #it's copy-on-write, shouldn't hurt performance
my.df <- read.table(textConnection("
v1 v2 v3 v4
a v d c
a v d d
b n p g
b d d h
c k d c
c r p g
d v d x
d v d c
e v d b
e v d c"), header = TRUE)
my.df[which(my.df$v1 != "b" & my.df$v1 != "d" & my.df$v1 != "e" ), ]
v1 v2 v3 v4
1 a v d c
2 a v d d
5 c k d c
6 c r p g
As this is only tagged sql
(which does not indicate any specific DBMS), here is a solution for Postgres:
select d::date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):
create table calendar
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
Here are a few ways you can check if a list is empty:
a = [] #the list
1) The pretty simple pythonic way:
if not a:
print("a is empty")
In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False
. One could simply treat the list as a predicate (returning a Boolean value). And a True
value would indicate that it's non-empty.
2) A much explicit way: using the len()
to find the length and check if it equals to 0
:
if len(a) == 0:
print("a is empty")
3) Or comparing it to an anonymous empty list:
if a == []:
print("a is empty")
4) Another yet silly way to do is using exception
and iter()
:
try:
next(iter(a))
# list has elements
except StopIteration:
print("Error: a is empty")
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
You can use the JSON.parse()
for that.
Example:
var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
If you're using React Js for your website, use https://www.npmjs.com/package/react-device-detect
Turns out the problem was in the permission. I fix it with the following command
sudo chown -R $USER /var/www
Please make sure with the $USER
variable. I tested and worked on Ubuntu Distro
You can apply apply
to a subset of the original data.
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
apply(dat[,c('x','z')], 1, function(x) sum(x) )
or if your function is just sum use the vectorized version:
rowSums(dat[,c('x','z')])
[1] 6 8
If you want to use testFunc
testFunc <- function(a, b) a + b
apply(dat[,c('x','z')], 1, function(x) testFunc(x[1],x[2]))
EDIT To access columns by name and not index you can do something like this:
testFunc <- function(a, b) a + b
apply(dat[,c('x','z')], 1, function(y) testFunc(y['z'],y['x']))
You can also use: finishAffinity()
Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction
[\s-[\r\n]]
or, including Eiríkr Útlendi's solution, you get
[\s\u3000-[\r\n]]
copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)
FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8
and not just Content-Type: text/plain;
.
What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?
Take a look at What is the most appropriate way to store user settings in Android application if you're concerned about storing passwords as clear text in SharedPreferences.
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
it works fine and the output of the test:
console.log(json);
Result:
"{"a":"test","b":["item","item2","item3"]}"
First, the error you're getting is due to where you're using the COUNT
function -- you can't use an aggregate (or group) function in the WHERE
clause.
Second, instead of using a subquery, simply join the table to itself:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
Which I believe should return only rows where at least two rows exist with the same pid
but there is are at least 2 sid
s. To make sure you get back only one row per pid
I've applied a grouping clause.
I found it under /usr/share/java/maven-3.0.3/conf , 10.8.2
I know it's an old question now but i thought it might help others. I wanted something a little easier to implement for a few apps i had, so i made a class for this. You can download it here if you want: https://github.com/sdernley/iOSTextFieldHandler
It's as simple as setting all of the UITextFields to have a delegate of self
textfieldname.delegate = self;
And then adding this to your view controller with the name of your scrollView and submit button
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[iOSTextFieldHandler TextboxKeyboardMover:containingScrollView tf:textField btn:btnSubmit];
}
I bet you are retrieving data in non-utf8 encoding: try to put mysql_query('SET CHARACTER SET utf8')
before your SELECT
query.
In Windows 7 you could do the following:
Right click on your project and select "Add->Existing Item". In the dialog which appears, browse to the root of the directory you want to add. In the upper right corner you have a search box. Type *.cs
or *.cpp
, whatever the type of files you want to add. After the search finishes, select all files, click Add and wait for a while...
Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.
SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee not in ('pg_monitor','PUBLIC');
Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.
<body>
<app-root></app-root>
<script>
myTest = 1;
</script>
</body>
..near the top right after imports:
declare const myTest: any;
...later:
console.warn(myTest); // outputs '1'
cat /sys/class/net/ethX
is by far the easiest method.
The interface has to be up though, else you will get an invalid argument error.
So first:
ifconfig ethX up
Then:
cat /sys/class/net/ethX
Eclipse uses it's own internal compiler that can compile to several Java versions.
From Eclipse Help > Java development user guide > Concepts > Java Builder
The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.
For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.
When you configure a project:
[project-name] > Properties > Java Compiler > Compiler compliance level
This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.
Host environment variables, eg JAVA_HOME etc, are not used.
The Oracle/Sun JDK compiler is not used.
If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0'
to implementation 'com.google.firebase:firebase-core:10.0.0'
in your app level build.gradle file.
This would surely work.
Normal money conversions will preserve individual pennies:
SELECT convert(varchar(30), moneyfield, 1)
The last parameter decides what the output format looks like:
0 (default) No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.
If you want to truncate the pennies, and count in pounds, you can use rounding to the nearest pound, floor to the lowest whole pound, or ceiling to round up the pounds:
SELECT convert(int, round(moneyfield, 0))
SELECT convert(int, floor(moneyfield))
SELECT convert(int, ceiling(moneyfield))
"crypto/rand" is cross platform pkg for random bytes generattion
package main
import (
"crypto/rand"
"fmt"
)
// Note - NOT RFC4122 compliant
func pseudo_uuid() (uuid string) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println("Error: ", err)
return
}
uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return
}
Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.
When using nohup
and you put the task in the background, the background operator (&
) will give you the PID at the command prompt. If your plan is to manually manage the process, you can save that PID and use it later to kill the process if needed, via kill PID
or kill -9 PID
(if you need to force kill). Alternatively, you can find the PID later on by ps -ef | grep "command name"
and locate the PID from there. Note that nohup
keyword/command itself does not appear in the ps
output for the command in question.
If you use a script, you could do something like this in the script:
nohup my_command > my.log 2>&1 &
echo $! > save_pid.txt
This will run my_command
saving all output into my.log
(in a script, $!
represents the PID of the last process executed). The 2
is the file descriptor for standard error (stderr
) and 2>&1
tells the shell to route standard error output to the standard output (file descriptor 1
). It requires &1
so that the shell knows it's a file descriptor in that context instead of just a file named 1
. The 2>&1
is needed to capture any error messages that normally are written to standard error into our my.log
file (which is coming from standard output). See I/O Redirection for more details on handling I/O redirection with the shell.
If the command sends output on a regular basis, you can check the output occasionally with tail my.log
, or if you want to follow it "live" you can use tail -f my.log
. Finally, if you need to kill the process, you can do it via:
kill -9 `cat save_pid.txt`
rm save_pid.txt
If you do not want to change your HTML structure you can also do by adding text-align: center;
to the wrapper element and a display: inline-block;
to the centered element.
#container {
width:100%;
text-align:center;
}
#left {
float:left;
width:100px;
}
#center {
display: inline-block;
margin:0 auto;
width:100px;
}
#right {
float:right;
width:100px;
}
Live Demo: http://jsfiddle.net/CH9K8/
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("Path\To\File.dll")