Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:
::-webkit-scrollbar {
width: 2em;
height: 2em
}
::-webkit-scrollbar-button {
background: #ccc
}
::-webkit-scrollbar-track-piece {
background: #888
}
::-webkit-scrollbar-thumb {
background: #eee
}?
References:
Summary:
When inheriting, you can (in some languages) change the protection type of a data member in certain direction, e.g. from protected to public.
Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml
file.
For PostgreSQL 9.1 this would be:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<name>Your project name.</name>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
</dependencies>
</project>
You can get the code for the dependency (as well as any other dependency) from maven's central repository
If you are using postgresql 9.2+:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<name>Your project name.</name>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.1</version>
</dependency>
</dependencies>
</project>
You can check the latest versions and dependency snippets from:
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
Dudes, I think there are a lot of shots in the dark here. In some cases Clean and Sync Project will help only after you fixed the problem.
Step1:
So go and look at the top of each file where the package is specified as follows pakage="YourURL.YourProject";
and insure that the correct package (Your Own Project) is specified.
You will find this in java files and AndroidManifest.xml and it is critical for the java files to reference the correct package, as that package contains the resources ("R") you are pointing to. Should they not match up the error cannot resolve Symbol R occurs.
Step2: Clean, Sync, whatever. Done
So why does this occur randomly or what did I do wrong??
If you copy and paste code, you should pay close attention to the "package=" as explained above. More importantly, when you paste code, it immediately runs through a sort of debugger (Excuse my bad tech term) to show you "presumed errors", which immediately takes in consideration the "Wrong Package", and you get all the errors. Therefore, even though you immediately corrected the notation after pasting, the debugger has already refreshed. Which is why "Clean, Sync, Whatever" works SOMETIMES
Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args
parameter), is to compile normally, and use r arg1 arg2 arg3
directly from within gdb
, like so:
$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3
So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.
I assume it's because it makes sure there's something to reference, but I am not entirely sure.
I tried all the above codes and none of them fixed my issues. Here is what worked for me. I used input-group-addon.
<div class = "input-group">
<span class = "input-group-addon">Go</span>
<input type = "text" class = "form-control" placeholder="you are the man!">
</div>
Based on the answers above I'm using this shorter one liner:
git remote prune origin | awk 'BEGIN{FS="origin/"};/pruned/{print $2}' | xargs -r git branch -d
Also, if you already pruned and have local dangling branches, then this will clean them up:
git branch -vv | awk '/^ .*gone/{print $1}' | xargs -r git branch -d
The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.
$(".use-address").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$("#resultas").append($item); // Outputs the answer
});
Now let's focus on some frequently asked questions in such situations.
Using .closest()
:
var $row = $(this).closest("tr");
Using .parent()
:
You can also move up the DOM tree using .parent()
method. This is just an alternative that is sometimes used together with .prev()
and .next()
.
var $row = $(this).parent() // Moves up from <button> to <td>
.parent(); // Moves up from <td> to <tr>
<td>
valuesSo we have our $row
and we would like to output table cell text:
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
<td>
valueSimilar to the previous one, however we can specify the index of the child <td>
element.
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});
.closest()
- get the first element that matches the selector.parent()
- get the parent of each element in the current set of matched elements.parents()
- get the ancestors of each element in the current set of matched elements.children()
- get the children of each element in the set of matched elements.siblings()
- get the siblings of each element in the set of matched elements.find()
- get the descendants of each element in the current set of matched elements.next()
- get the immediately following sibling of each element in the set of matched elements.prev()
- get the immediately preceding sibling of each element in the set of matched elementsWeird error.
Can you test this?
const char* const S = "ABCD";
char t[] = { S[0], S[1], S[2], S[3] };
char u[] = { S[3], S[2], S[1], S[0] };
The default figure size (in inches) is controlled by
matplotlib.rcParams['figure.figsize'] = [width, height]
For example:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]
creates a figure with 10 (width) x 5 (height) inches
The decimal operator might be more in line with what you are looking for:
>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434
Adjusting the background-size
is permitted. You still need to specify width and height of the block, however.
.pdflink:after {
background-image: url('/images/pdf.png');
background-size: 10px 20px;
display: inline-block;
width: 10px;
height: 20px;
content:"";
}
Classic case for a recursive solution. Here's mine:
class JsonFormatter {
public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
$inString = $escaped = false;
$result = $indent;
if(is_string($j)) {
$bak = $j;
$j = str_split(trim($j, '"'));
}
while(count($j)) {
$c = array_shift($j);
if(false !== strpos("{[,]}", $c)) {
if($inString) {
$result .= $c;
} else if($c == '{' || $c == '[') {
$result .= $c."\n";
$result .= self::prettyPrint($j, $indentor, $indentor.$indent);
$result .= $indent.array_shift($j);
} else if($c == '}' || $c == ']') {
array_unshift($j, $c);
$result .= "\n";
return $result;
} else {
$result .= $c."\n".$indent;
}
} else {
$result .= $c;
$c == '"' && !$escaped && $inString = !$inString;
$escaped = $c == '\\' ? !$escaped : false;
}
}
$j = $bak;
return $result;
}
}
Usage:
php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
[foo] => 1
[bar] => This "is" bar
[baz] => Array
(
[a] => 1
[b] => 2
[c] => "3"
)
)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
"foo":1,
"bar":"This \"is\" bar",
"baz":{
"a":1,
"b":2,
"c":"\"3\""
}
}
Cheers
The "{{ ... }}"-delimiter can also be used within strings:
"http://{{ app.request.host }}"
I will just make things clear. TCP/UDP are two cars are that being driven on the road. suppose that traffic signs & obstacles are Errors TCP cares for traffic signs, respects everything around. Slow driving because something may happen to the car. While UDP just drives off, full speed no respect to street signs. Nothing, a mad driver. UDP doesn't have error recovery, If there's an obstacle, it will just collide with it then continue. While TCP makes sure that all packets are sent & received perfectly, No errors , so , the car just passes obstacles without colliding. I hope this is a good example for you to understand, Why UDP is preferred in gaming. Gaming needs speed. TCP is preffered in downloads, or downloaded files may be corrupted.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
Direct link to awk version : http://www.shelldorado.com/scripts/cmds/urlencode
I used it for years and it works like a charm
:
##########################################################################
# Title : urlencode - encode URL data
# Author : Heiner Steven ([email protected])
# Date : 2000-03-15
# Requires : awk
# Categories : File Conversion, WWW, CGI
# SCCS-Id. : @(#) urlencode 1.4 06/10/29
##########################################################################
# Description
# Encode data according to
# RFC 1738: "Uniform Resource Locators (URL)" and
# RFC 1866: "Hypertext Markup Language - 2.0" (HTML)
#
# This encoding is used i.e. for the MIME type
# "application/x-www-form-urlencoded"
#
# Notes
# o The default behaviour is not to encode the line endings. This
# may not be what was intended, because the result will be
# multiple lines of output (which cannot be used in an URL or a
# HTTP "POST" request). If the desired output should be one
# line, use the "-l" option.
#
# o The "-l" option assumes, that the end-of-line is denoted by
# the character LF (ASCII 10). This is not true for Windows or
# Mac systems, where the end of a line is denoted by the two
# characters CR LF (ASCII 13 10).
# We use this for symmetry; data processed in the following way:
# cat | urlencode -l | urldecode -l
# should (and will) result in the original data
#
# o Large lines (or binary files) will break many AWK
# implementations. If you get the message
# awk: record `...' too long
# record number xxx
# consider using GNU AWK (gawk).
#
# o urlencode will always terminate it's output with an EOL
# character
#
# Thanks to Stefan Brozinski for pointing out a bug related to non-standard
# locales.
#
# See also
# urldecode
##########################################################################
PN=`basename "$0"` # Program name
VER='1.4'
: ${AWK=awk}
Usage () {
echo >&2 "$PN - encode URL data, $VER
usage: $PN [-l] [file ...]
-l: encode line endings (result will be one line of output)
The default is to encode each input line on its own."
exit 1
}
Msg () {
for MsgLine
do echo "$PN: $MsgLine" >&2
done
}
Fatal () { Msg "$@"; exit 1; }
set -- `getopt hl "$@" 2>/dev/null` || Usage
[ $# -lt 1 ] && Usage # "getopt" detected an error
EncodeEOL=no
while [ $# -gt 0 ]
do
case "$1" in
-l) EncodeEOL=yes;;
--) shift; break;;
-h) Usage;;
-*) Usage;;
*) break;; # First file name
esac
shift
done
LANG=C export LANG
$AWK '
BEGIN {
# We assume an awk implementation that is just plain dumb.
# We will convert an character to its ASCII value with the
# table ord[], and produce two-digit hexadecimal output
# without the printf("%02X") feature.
EOL = "%0A" # "end of line" string (encoded)
split ("1 2 3 4 5 6 7 8 9 A B C D E F", hextab, " ")
hextab [0] = 0
for ( i=1; i<=255; ++i ) ord [ sprintf ("%c", i) "" ] = i + 0
if ("'"$EncodeEOL"'" == "yes") EncodeEOL = 1; else EncodeEOL = 0
}
{
encoded = ""
for ( i=1; i<=length ($0); ++i ) {
c = substr ($0, i, 1)
if ( c ~ /[a-zA-Z0-9.-]/ ) {
encoded = encoded c # safe character
} else if ( c == " " ) {
encoded = encoded "+" # special handling
} else {
# unsafe character, encode it as a two-digit hex-number
lo = ord [c] % 16
hi = int (ord [c] / 16);
encoded = encoded "%" hextab [hi] hextab [lo]
}
}
if ( EncodeEOL ) {
printf ("%s", encoded EOL)
} else {
print encoded
}
}
END {
#if ( EncodeEOL ) print ""
}
' "$@"
One option is to use shelljs module
npm install shelljs
var shell = require('shelljs');
shell.mkdir('-p', fullPath);
From that page:
Available options:
p: full path (will create intermediate dirs if necessary)
As others have noted, there's other more focused modules. But, outside of mkdirp, it has tons of other useful shell operations (like which, grep etc...) and it works on windows and *nix
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
One of the main differences between surfaceview and view is that to refresh the screen for a normal view we have to call invalidate method from the same thread where the view is defined. But even if we call invalidate, the refreshing does not happen immediately. It occurs only after the next arrival of the VSYNC signal. VSYNC signal is a kernel generated signal which happens every 16.6 ms or this is also known as 60 frame per second. So if we want more control over the refreshing of the screen (for example for very fast moving animation), we should not use normal view class.
On the other hand in case of surfaceview, we can refresh the screen as fast as we want and we can do it from a background thread. So refreshing of the surfaceview really does not depend upon VSYNC, and this is very useful if we want to do high speed animation. I have few training videos and example application which explain all these things nicely. Please have a look at the following training videos.
The best way I found so far is using the Android-Debug-Database tool.
Its incredibly simple to use and setup, just add the dependence and connect to the device database's interface via web. No need to root the phone or adding activities or whatsoever. Here are the steps:
STEP 1
Add the following dependency to your app's Gradle file and run the application.
debugCompile 'com.amitshekhar.android:debug-db:1.0.0'
STEP 2
Open your browser and visit your phone's IP address on port 8080. The URL should be like: http://YOUR_PHONE_IP_ADDRESS:8080
. You will be presented with the following:
NOTE: You can also always get the debug address URL from your code by calling the method DebugDB.getAddressLog();
To get my phone's IP I currently use Ping Tools, but there are a lot of alternatives.
STEP 3
That's it!
More details in the official documentation: https://github.com/amitshekhariitbhu/Android-Debug-Database
In lines with the answer of NoToast, you would need to have multiple versions of "your_image" in your res/drawable-ldpi,mdpi, hdpi, x-hdpi (for xtra large screens), remove match_parent and keep android: adjustViewBounds="true"
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by
Locale.getDefault()
.
dayStart.bat
start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat
release.bat
call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat
Following works in Java 8..
List<String[]> addresses = new ArrayList<>();
Try SELECT CAST(field1 AS DECIMAL(10,2)) field1
and replace 10,2
with whatever precision you need.
With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:
UserService userService = Mockito.mock(UserService.class);
SearchService searchService = Mockito.mock(SearchService.class);
CounterService counterService = Mockito.mock(CounterService.class,
withSettings().useConstructor(userService, searchService));
use of bundle send data from one activity to another activity with the help of intent object; Bundle hold the data that can be any type.
Now I tell that how to create bundle passing data between two activity.
Step 1: On First activity
Bundle b=new Bundle();
b.putString("mkv",anystring);
Intent in=new Intent(getApplicationContext(),secondActivity.class);
in.putExtras(b);
startActivity(in);
Step 2: On Second Activity
Intent in=getIntent();
Bundle b=in.getExtras();
String s=b.getString("mkv");
I think this is useful for you...........
You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:
Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
cl.Value = "PHEV"
Next cl
The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.
Use this to find the location of any column in a table by its column name:
Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column
This returns the numeric position of a column in the table.
Try to use this:
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
{
//add parameters on request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("test", "test"),
new KeyValuePair<string, string>("test1", "test1")
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
//client.DefaultRequestHeaders.Add("Accept", "*/*");
client.Timeout = TimeSpan.FromMilliseconds(10000);
var res = await client.PostAsync("", new FormUrlEncodedContent(body));
if (res.IsSuccessStatusCode)
{
var exec = await res.Content.ReadAsStringAsync();
Console.WriteLine(exec);
}
}
}
If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.
Ctrl+Z
(suspend the process)
bg
(restart the process in the background
disown %1
(assuming this is job #1, use jobs
to determine)
This can be done very simple, you were pretty close already
SELECT distinct id, DENSE_RANK() OVER (ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
public static double addDoubles(double a, double b) {
BigDecimal A = new BigDecimal(a + "");
BigDecimal B = new BigDecimal(b + "");
return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
Yet another solution. With True
and False
you get a little feedback about the test at the end.
data = {True: data[:75] + '..', False: data}[len(data) > 75]
Set your PRIMARY KEY as AUTO_INCREMENT.
float
stores floating-point values, that is, values that have potential decimal placesint
only stores integral values, that is, whole numbersSo while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float
.
Dissecting them both a little further:
In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.
In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:
M × 2E
(There is more to it, but this should suffice for the purpose of this discussion)
The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.
Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float
is around 3.4 × 1038 whereas int
only allows values up to 2.1 × 109.
But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int
can store), that at the larger end of float
's numeric range the numbers are spaced wider apart (since there cannot be more unique float
numbers than there are unique int
numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float
of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float
is using there.
Similarly, you can also represent very small numbers (between 0 and 1) in a float
but regardless of whether the numbers are very large or very small, float
only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float
cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...
When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.
By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:
To fix this issue add following lines After Return and Before Begin statement:
READS SQL DATA
DETERMINISTIC
For Example :
CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN
For more detail about this issue please read Here
i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?
Do you really want to style the <div>
? Or do you want to style the <input type="button">
? You should use the correct selector if you want the latter:
input[type=button] {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
/* ... other rules ... */
cursor:pointer;
}
input[type=button]:hover {
background-color:rgba(255,204,0,0.8);
}
See also:
if you're utilizing a UINavigationController and also want to handle modal views, the following is what i use:
#import <objc/runtime.h>
UIViewController* topMostController = self.navigationController.visibleViewController;
if([[NSString stringWithFormat:@"%s", class_getName([topMostController class])] isEqualToString:@"NAME_OF_CONTROLLER_YOURE_CHECKING_IN"]) {
//is topmost visible view controller
}
This is the command for the batch file and it can run the vbscript.
C:\Windows\SysWOW64\cmd.exe /c cscript C:\Windows\SysWOW64\...\necdaily.vbs
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}
a++ is known as postfix.
add 1 to a, returns the old value.
++a is known as prefix.
add 1 to a, returns the new value.
C#:
string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
Console.WriteLine(++i);
}
Console.WriteLine("");
i = 0;
foreach (string item in items)
{
Console.WriteLine(i++);
}
Output:
1
2
3
4
0
1
2
3
foreach
and while
loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:
for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }
0 1 2 3 4
0 1 2 3 4
If the value as evaluated is used then the type of increment becomes significant:
int n = 0;
for (int i = 0; n < 5; n = i++) { }
Create a global variable in and apply the value
<script>
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>
Then you can reference it from elsewhere
For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.
For example:
loadScript("js/myscript.js").then(function(){
// Do whatever you want to do after script load
});
or when used in an async function:
await loadScript("js/myscript.js");
// Do whatever you want to do after script load
In your case you may execute this after document ready:
$(document).ready(async function() {
await loadScript("js/myscript.js");
// Do whatever you want to do after script is ready
});
Function for loadScript:
function loadScript(src) {
return new Promise(function (resolve, reject) {
if ($("script[src='" + src + "']").length === 0) {
var script = document.createElement('script');
script.onload = function () {
resolve();
};
script.onerror = function () {
reject();
};
script.src = src;
document.body.appendChild(script);
} else {
resolve();
}
});
}
Benefit of this way:
Here it is. Add this code to your web.config file:
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Redirect" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Rewrite" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
I spend days together to figure out this issue. I know its late but this might be helpful:
I resolved this issue by changing the compatible/stable version of:
Spring boot: 2.1.1
Spring Data Elastic: 2.1.4
Elastic: 6.4.0 (default)
Maven:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
You don't need to mention Elastic version. By default it is 6.4.0. But if you want to add a specific verison. Use below snippet inside properties tag and use the compatible version of Spring Boot and Spring Data(if required)
<properties>
<elasticsearch.version>6.8.0</elasticsearch.version>
</properties>
Also, I used the Rest High Level client in ElasticConfiguration :
@Value("${elasticsearch.host}")
public String host;
@Value("${elasticsearch.port}")
public int port;
@Bean(destroyMethod = "close")
public RestHighLevelClient restClient1() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
Important Note: Elastic use 9300 port to communicate between nodes and 9200 as HTTP client. In application properties:
elasticsearch.host=10.40.43.111
elasticsearch.port=9200
spring.data.elasticsearch.cluster-nodes=10.40.43.111:9300 (customized Elastic server)
spring.data.elasticsearch.cluster-name=any-cluster-name (customized cluster name)
From Postman, you can use: http://10.40.43.111:9200/[indexname]/_search
Happy coding :)
Here's an alternative answer in case the ones listed above don't work for you. You can use the following solution(s) as well, which was found here:
ip addr
OR
ip addr show
OR
ip link
All three of these will show your MAC address(es) next to link/ether
. I stumbled on this because I had just done a fresh install of Debian 9.5 from a USB stick without internet access, so I could only do a very minimal install, and received
-bash: ifconfig: command not found
when I tried some of the above solutions. I figured somebody else may come across this problem as well. Hope it helps.
EXEC sp_helptext 'your procedure name';
This avoids the problem with INFORMATION_SCHEMA approach wherein the stored procedure gets cut off if it is too long.
Update: David writes that this isn't identical to his sproc...perhaps because it returns the lines as 'records' to preserve formatting? If you want to see the results in a more 'natural' format, you can use Ctrl-T first (output as text) and it should print it out exactly as you've entered it. If you are doing this in code, it is trivial to do a foreach to put together your results in exactly the same way.
Update 2: This will provide the source with a "CREATE PROCEDURE" rather than an "ALTER PROCEDURE" but I know of no way to make it use "ALTER" instead. Kind of a trivial thing, though, isn't it?
Update 3: See the comments for some more insight on how to maintain your SQL DDL (database structure) in a source control system. That is really the key to this question.
In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?
IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.
Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as
package 7 com.example;
could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.
Judging from everything you've said, it seems like the original Odómetro
string you're dealing with is encoded with ISO 8859-1, not UTF-8.
Here's why I think so:
json_encode
produced parseable output after you ran the input string through utf8_encode
, which converts from ISO 8859-1 to UTF-8.print_r
after doing utf8_encode
, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3
in UTF-8, but that sequence is ó
in ISO 8859-1.htmlentities
hackaround solution worked. htmlentities
needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode
, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)PHP will use the \uXXXX
escaping, but as you noted, this is valid JSON.
So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8'
to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode
, but this will only support characters that are part of ISO 8859-1).
Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r
testing).
You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/
include the jStorage.js script into your html
<script src="jStorage.js"></script>
Then in your javascript place the sessiontoken into the a key like this
$.jStorage.set("YOUR_KEY",session_id);
Where "YOUR_KEY" is the key using which you can access you session_id , like this:
var id = $.jStorage.get("YOUR_KEY");
The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.
class X {
const int x;
};
Since X::x
is const
, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x
). You can get the same kind of situation with a member that's a reference:
class X {
whatever &x;
};
It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.
This is why a const
member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.
It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.
If you use docker, remove all images. They used many space....
Stop all containers
docker stop $(docker ps -a -q)
Delete all containers
docker rm $(docker ps -a -q)
Delete all images
docker rmi $(docker images -q)
Works to me
Directory.CreateDirectory
explains how to try and to create the FilePath if it does not exist.
Directory.Exists
explains how to check if a FilePath exists. However, you don't need this as CreateDirectory will check it for you.
I got the error because of a clumsy typo:
This errors:
knitr::opts_chunk$seet(echo = FALSE)
Error: attempt to apply non-function
After correcting the typo, it works:
knitr::opts_chunk$set(echo = FALSE)
All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.
Good luck.
Please see if below can help you
Class Post_Sales
Public Shared Sub Post_sales()
Dim ITM_ID As Integer
Dim SLS_QTY As Integer
Dim SLS_PRC As Double
Dim SLS_AMT As Double
Dim DSPL_RCT As String
Dim TAX_CODE As Integer
'Format the current date and send it to a textbox
Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))
'Open Connection
Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")
con.Open()
'Insert Records into the database
For Each rw As DataGridViewRow In Form1.DataGridView1.Rows
ITM_ID = rw.Cells("Column1").Value
DSPL_RCT = rw.Cells("Column2").Value
SLS_QTY = rw.Cells("Column3").Value
SLS_PRC = rw.Cells("Column4").Value
SLS_AMT = rw.Cells("Column5").Value
TAX_CODE = rw.Cells("Column6").Value
Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)
cmd.ExecuteNonQuery()
Next
con.Close()
MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")
End Sub
End Class
I find this way more readable:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";
Not that I have anything against arrays...
There are three reasons why your example fails.
The original 'template' variable is not a jQuery/DOM object and cannot be parsed, it is a string. Make it a jQuery object by wrapping it in $(), such as: template = $(template)
Once the 'template' variable is a jQuery object you need to realize that <li> is the root object. Therefore you cannot search for the LI root node and get any results. Simply apply the ID to the jQuery object.
When you assign an ID to an HTML element it cannot begin with a number character with any HTML version before HTML5. It must begin with an alphabetic character. With HTML5 this can be any non-whitespace character. For details refer to: What are valid values for the id attribute in HTML?
PS: A final issue with the sample code is an LI cannot be applied to the BODY. According to HTML requirements it must always be contained within a list, i.e. UL or OL.
This works for me.
cp -r /home/server/folder/test/. /home/server
The solution suggested from arlomedia worked for me. About his issue of extraspace I solved removing all the paddings to the switch.
EDIT
As requested, here what I have.
In the layout file, my switch is inside a linear layout and after a TextView.
<LinearLayout
android:id="@+id/myLinearLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:padding="10dp"
android:layout_marginTop="0dp"
android:background="@drawable/bkg_myLinearLayout"
android:layout_marginBottom="0dp">
<TextView
android:id="@+id/myTextForTheSwitch"
android:layout_height="wrap_content"
android:text="@string/TextForTheSwitch"
android:textSize="18sp"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:layout_width="wrap_content"
android:paddingRight="20dp"
android:textColor="@color/text_white" />
<Switch
android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="@string/On"
android:textOff="@string/Off"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_toRightOf="@id/myTextForTheSwitch"
android:layout_alignBaseline="@id/myTextForTheSwitch"
android:gravity="right" />
</LinearLayout>
Since I'm working with Xamarin / Monodroid (min. Android 4.1) my code is:
Android.Graphics.Color colorOn = Android.Graphics.Color.Green;
Android.Graphics.Color colorOff = Android.Graphics.Color.Gray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Green;
StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));
swtch_EnableEdit.ThumbDrawable = drawable;
swtch_EnableEdit is previously defined like this (Xamarin):
Switch swtch_EnableEdit = view.FindViewById<Switch>(Resource.Id.mySwitch);
I don't set at all the paddings and I don't call .setPadding(0, 0, 0, 0).
Getting a timezone-aware date in utc
timezone is enough for date subtraction to work.
But if you want a timezone-aware date in your current time zone, tzlocal
is the way to go:
from tzlocal import get_localzone # pip install tzlocal
from datetime import datetime
datetime.now(get_localzone())
PS dateutil
has a similar function (dateutil.tz.tzlocal
). But inspite of sharing the name it has a completely different code base, which as noted by J.F. Sebastian can give wrong results.
Cocoapods Installation on macOS High Sierra:
Install Homebrew https://brew.sh/
Execute following commands in terminal:
sudo gem update --system sudo gem install activesupport -v 4.2.6 sudo gem install -n /usr/local/bin cocoapods pod setup pod setup --verbose
Looks like you are hitting the limit on connections per server. I see you are loading a lot of static files and my advice is to separate them on subdomains and serve them directly with Nginx for example.
Create a subdomain called img.yoursite.com and load all your images from there.
Create a subdomain called scripts.yourdomain.com and load all your JS and CSS files from there.
Create a subdomain called sounds.yoursite.com and load all your MP3s from there... etc..
Nginx has great options for directly serving static files and managing the static files caching.
#include<iostream>
using namespace std ;
int main()
{
int A[3][4] = { {1,2,3,4} , {4,5,7,8} , {9,10,11,12} } ;
for(int rows=0 ; rows<sizeof(A)/sizeof(*A) ; rows++)
{
for(int columns=0 ; columns< sizeof(*A) / sizeof(*A[0]) ; columns++)
{
cout<<A[rows][columns] <<"\t" ;
}
cout<<endl ;
}
}
Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.
Check out this post
According to it
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
JavaScript is a prototype-based programming language (probably prototype-based scripting language is more correct definition). It employs cloning and not inheritance. A prototype-based programming language is a style of object-oriented programming without classes. While object-oriented programming languages encourages development focus on taxonomy and relationships, prototype-based programming languages encourages to focus on behavior first and then later classify.
The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean
only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. (source)
In object-oriented programming, each object is capable of receiving messages, processing data, and sending messages to other objects.
For a language to be object-oriented in may include features as encapsulation, modularity, polymorphism, and inheritance, but it is not a requirement. Object-oriented programming languages that make use of classes are often referred to as classed-based programming languages, but it is by no means a must to make use of classes to be object-oriented.
JavaScript uses prototypes to define object properties, including methods and inheritance.
Conclusion: JavaScript IS object-oriented.
First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.
If not you have some compilation errors in your java classes.
It's a feature programs cannot stay without. You can try yargs.
npm install --save-dev yargs
You can use it like this:
gulp mytask --production --test 1234
In the code, for example:
var argv = require('yargs').argv;
var isProduction = (argv.production === undefined) ? false : true;
For your understanding:
> gulp watch
console.log(argv.production === undefined); <-- true
console.log(argv.test === undefined); <-- true
> gulp watch --production
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- true
console.log(argv.test); <-- undefined
> gulp watch --production --test 1234
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- false
console.log(argv.test); <-- 1234
Hope you can take it from here.
There's another plugin that you can use, minimist. There's another post where there's good examples for both yargs and minimist: (Is it possible to pass a flag to Gulp to have it run tasks in different ways?)
By using Reflector, you can see, that Contains is implemented using IndexOf. Here's the implementation.
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
So Contains is likely a wee bit slower than calling IndexOf directly, but I doubt that it will have any significance for the actual performance.
I have a sheet that is made to used by others and I have quite a few indirect() references around, so I need to formulaically handle a changed sheet tab name.
I used the formula from JohnP2 (below) but was having trouble because it didn't update automatically when a sheet name was changed. You need to go to the actual formula, make an arbitrary change and refresh to run it again.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
I solved this by using info found in this solution on how to force a function to refresh. It may not be the most elegant solution, but it forced Sheets to pay attention to this cell and update it regularly, so that it catches an updated sheet title.
=IF(TODAY()=TODAY(), REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1"), "")
Using this, Sheets know to refresh this cell every time you make a change, which results in the address being updated whenever it gets renamed by a user.
You can first append elements to the initialized array and then for convenience, you can convert it into a numpy array.
import numpy as np
a = [] # declare null array
a.append(['aa1']) # append elements
a.append(['aa2'])
a.append(['aa3'])
print(a)
a_np = np.asarray(a) # convert to numpy array
print(a_np)
FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".
You can use markersize to specify the size of the circle in plot method
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20) # blue circle with size 10
plt.plot(x2, 'ro', ms=10,) # ms is just an alias for markersize
plt.show()
From here
user.dir
is the "User working directory" according to the Java Tutorial, System Properties
I feel the simplest way would be
from matplotlib import pyplot;
from pylab import genfromtxt;
mat0 = genfromtxt("data0.txt");
mat1 = genfromtxt("data1.txt");
pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
pyplot.legend();
pyplot.show();
you can do this with this plugin http://dev.andreaseberhard.de/jquery/superbgimage/
or
background-image:url(../IMAGES/background.jpg);
background-repeat:no-repeat;
background-size:cover;
with no need the prefixes of browsers. it's all ready suporterd in both of browers
The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...
$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
$db_res=1;
try{$sth->execute($param1,$param2);}
catch
{
print "caught $_ in insertion to hd_item_upc for upc $upc\n";
$db_res=dbi_err_handler($_);
if($db_res==0){sleep 3;}
}
}
dbi_err_handler should have at least the following:
sub dbi_err_handler
{
my($message) = @_;
if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
{
$caught=1;
$retval=0; # we'll check this value and sleep/re-execute if necessary
}
return $retval;
}
You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..
Hope this helps someone -
SELECT
, INSERT
, UPDATE
, and DELETE
commands frequently include WHERE clauses to specify filters that define the conditions each row in the source tables must meet to qualify for an SQL command. Parameters provide the filter values in the WHERE clauses.
You can use parameter markers to dynamically provide parameter values. The rules for which parameter markers and parameter names can be used in the SQL statement depend on the type of connection manager that the Execute SQL uses.
The following table lists examples of the SELECT command by connection manager type. The INSERT, UPDATE, and DELETE statements are similar. The examples use SELECT to return products from the Product table in AdventureWorks2012 that have a ProductID greater than and less than the values specified by two parameters.
EXCEL, ODBC, and OLEDB
SELECT* FROM Production.Product WHERE ProductId > ? AND ProductID < ?
ADO
SELECT * FROM Production.Product WHERE ProductId > ? AND ProductID < ?
ADO.NET
SELECT* FROM Production.Product WHERE ProductId > @parmMinProductID
AND ProductID < @parmMaxProductID
The examples would require parameters that have the following names: The EXCEL and OLED DB connection managers use the parameter names 0 and 1. The ODBC connection type uses 1 and 2. The ADO connection type could use any two parameter names, such as Param1 and Param2, but the parameters must be mapped by their ordinal position in the parameter list. The ADO.NET connection type uses the parameter names @parmMinProductID and @parmMaxProductID.
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
Steps:
Tip:
Changing the info
to error
in simplelogging.properties
file will help in achieving your requirement.
Just change the value of the below line
org.slf4j.simpleLogger.defaultLogLevel=info
to
org.slf4j.simpleLogger.defaultLogLevel=error
Use this Remove title and image from top.
Before:
setContentView(R.layout.actii);
Write this code:
requestWindowFeature(Window.FEATURE_NO_TITLE);
You can also replace complicated condition with single method call to make it less evil in maintain.
Alternatively...
var rowCount = $('table#myTable tr:last').index() + 1;
This will ensure that any nested table-rows are not also counted.
Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
display: inline-block; _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
margin-left:9px;_x000D_
width : 320px;_x000D_
visibility: hidden;_x000D_
background-color: #FFF;_x000D_
border-radius:4px;_x000D_
border: 1px solid #aeaeae;_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
padding: 5px;_x000D_
margin-top : -15px; _x000D_
opacity: 0;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
top: 5%;_x000D_
right: 100%; _x000D_
margin-top: -5px;_x000D_
border-width: 5px;_x000D_
border-style: solid;_x000D_
border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
<input type="text" />_x000D_
<span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </span>_x000D_
</div>
_x000D_
Try to run xcrun simctl delete unavailable
in your terminal.
Original answer: Xcode - free to clear devices folder?
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
The package "tictoc" gives you a very simple way of measuring execution time. The documentation is in: https://cran.fhcrc.org/web/packages/tictoc/tictoc.pdf.
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
toc()
To save the elapsed time into a variable you can do:
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
exectime <- toc()
exectime <- exectime$toc - exectime$tic
Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!
Right way
<table>
<tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
<td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">
<b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
<small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>
</td>
</tr>
</table>
This question has a lot of explanations provided, but no clear examples of how to solve the problem that this behavior causes. In most cases, you'll probably want the following code in your pass by reference foreach
.
foreach ($array as &$row) {
// Do stuff
}
// Unset to remove the reference
unset($row);
This isn't really possible in HTML unless you use absolute positioning or javascript. So one solution would be to give this CSS to #bottom_link:
#bottom_link {
position:absolute;
bottom:0;
}
Otherwise you'd have to use some javascript. Here's a jQuery block that should do the trick, depending on the simplicity of the page.
$('#bottom_link').css({
position: 'relative',
top: $(this).parent().height() - $(this).height()
});
Swift 3:
If you want to go back to the previous view controller
_ = navigationController?.popViewController(animated: true)
If you want to go back to the root view controller
_ = navigationController?.popToRootViewController(animated: true)
woocommerce_get_product_terms()
is now deprecated.
Use wc_get_product_terms()
instead.
Example:
global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );
you have to check your linked project, in the new version of RN, don't need to link if you linked it cause a problem, I Fixed the problem by unlinked manually the dependency that I linked and re-run.
Use STATS option: http://msdn.microsoft.com/en-us/library/ms186865.aspx
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
First give your form an id
attribute, then use code like this:
$(document).ready( function() {
var form = $('#my_awesome_form');
form.find('select:first').change( function() {
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );
} );
So this code uses .serialize()
to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.
For future reference, the jQuery docs are very, very good.
Steps to get sources of a jar file as a zip :
Download JD-GUI from http://java-decompiler.github.io/ and save it at any location on your system.
Drag and drop the jar or open .jar file for which you want the sources on the JD.
Java Decompiler will open with all the package structure in a tree format.
Click on File menu and select save jar sources. It will save the sources as a zip with the same name as the jar.
Example:-
We can use Eclipse IDE for Java EE Developers as well for update/extract code if require.
From eclipse chose Import Jar and then select jar which you need. Follow instruction as per image below
This means the type of result the function returns, but it can be None
.
It is widespread in modern libraries oriented on Python 3.x.
For example, it there is in code of library pandas-profiling in many places for example:
def get_description(self) -> dict:
def get_rejected_variables(self, threshold: float = 0.9) -> list:
def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.
You can solve it by adding simply: df['C'] = df['A'] + df['B']
Dir.pwd
seems to do the trick.
I would also check the mysql configuration. I was running into this problem with my own server but I was a bit too hasty and misconfigured the innodb_buffer_pool_size for my machine.
innodb_buffer_pool_size = 4096M
It usually runs fine up to 2048 but I guess I don't have the memory necessary to support 4 gigs.
I imagine this could also happen with other mysql configuration settings.
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
Another possible way to do that:
from django.core.files import File
with open('path_to_file', 'r') as f: # use 'rb' mode for python3
data = File(f)
model.image.save('filename', data, True)
First, give permission for execution:-
chmod +x script_name
sh script_name
bash script_name
./script_name
NOTE:-you can check if the file is executable or not by using 'ls -a'
In Laravel 5.1, I used: File: app\Providers\AppServiceProvider.php
public function boot()
{
if ($this->isSecure()) {
\URL::forceSchema('https');
}
}
public function isSecure()
{
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$isSecure = true;
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
return $isSecure;
}
NOTE: use forceSchema
, NOT forceScheme
It is mainly a performance issue.
Having strings behave LIKE value type helps when writing code, but having it BE a value type would make a huge performance hit.
For an in-depth look, take a peek at a nice article on strings in the .net framework.
if you are trying DB first then be sure that your table has primary key
I'd like to thank the answer by Apostolos for bringing this to my attention. Here's a much more detailed example for Python 3 in the year 2019, with a clearer description and example code.
destroy()
(or not having a custom window closing handler at all) will destroy the window and all of its running callbacks instantly when the user closes it.This can be bad for you, depending on your current Tkinter activity, and especially when using tkinter.after
(periodic callbacks). You might be using a callback which processes some data and writes to disk... in that case, you obviously want the data writing to finish without being abruptly killed.
The best solution for that is to use a flag. So when the user requests window closing, you mark that as a flag, and then react to it.
(Note: I normally design GUIs as nicely encapsulated classes and separate worker threads, and I definitely don't use "global" (I use class instance variables instead), but this is meant to be a simple, stripped-down example to demonstrate how Tk abruptly kills your periodic callbacks when the user closes the window...)
from tkinter import *
import time
# Try setting this to False and look at the printed numbers (1 to 10)
# during the work-loop, if you close the window while the periodic_call
# worker is busy working (printing). It will abruptly end the numbers,
# and kill the periodic callback! That's why you should design most
# applications with a safe closing callback as described in this demo.
safe_closing = True
# ---------
busy_processing = False
close_requested = False
def close_window():
global close_requested
close_requested = True
print("User requested close at:", time.time(), "Was busy processing:", busy_processing)
root = Tk()
if safe_closing:
root.protocol("WM_DELETE_WINDOW", close_window)
lbl = Label(root)
lbl.pack()
def periodic_call():
global busy_processing
if not close_requested:
busy_processing = True
for i in range(10):
print((i+1), "of 10")
time.sleep(0.2)
lbl["text"] = str(time.time()) # Will error if force-closed.
root.update() # Force redrawing since we change label multiple times in a row.
busy_processing = False
root.after(500, periodic_call)
else:
print("Destroying GUI at:", time.time())
try: # "destroy()" can throw, so you should wrap it like this.
root.destroy()
except:
# NOTE: In most code, you'll wanna force a close here via
# "exit" if the window failed to destroy. Just ensure that
# you have no code after your `mainloop()` call (at the
# bottom of this file), since the exit call will cause the
# process to terminate immediately without running any more
# code. Of course, you should NEVER have code after your
# `mainloop()` call in well-designed code anyway...
# exit(0)
pass
root.after_idle(periodic_call)
root.mainloop()
This code will show you that the WM_DELETE_WINDOW
handler runs even while our custom periodic_call()
is busy in the middle of work/loops!
We use some pretty exaggerated .after()
values: 500 milliseconds. This is just meant to make it very easy for you to see the difference between closing while the periodic call is busy, or not... If you close while the numbers are updating, you will see that the WM_DELETE_WINDOW
happened while your periodic call "was busy processing: True". If you close while the numbers are paused (meaning that the periodic callback isn't processing at that moment), you see that the close happened while it's "not busy".
In real-world usage, your .after()
would use something like 30-100 milliseconds, to have a responsive GUI. This is just a demonstration to help you understand how to protect yourself against Tk's default "instantly interrupt all work when closing" behavior.
In summary: Make the WM_DELETE_WINDOW
handler set a flag, and then check that flag periodically and manually .destroy()
the window when it's safe (when your app is done with all work).
PS: You can also use WM_DELETE_WINDOW
to ask the user if they REALLY want to close the window; and if they answer no, you don't set the flag. It's very simple. You just show a messagebox in your WM_DELETE_WINDOW
and set the flag based on the user's answer.
You can use the nth-child
CSS selector to hide a whole column:
#myTable tr > *:nth-child(2) {
display: none;
}
This works under assumption that a cell of column N (be it a th
or td
) is always the Nth child element of its row.
?
If you want the column number to be dynamic, you could do that using querySelectorAll
or any framework presenting similar functionality, like jQuery
here:
$('#myTable tr > *:nth-child(2)').hide();
(The jQuery solution also works on legacy browsers that don't support nth-child
).
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
In Python 2, raw_input()
returns a string, and input()
tries to run the input as a Python expression.
Since getting a string was almost always what you wanted, Python 3 does that with input()
. As Sven says, if you ever want the old behaviour, eval(input())
works.
In this context, I suppose it could be interpreted as
do
...
while cmd != 'e'
Update: As @Soham Shetty comments, getSegmentsAtEvent(event)
only works for 1.x and for 2.x getElementsAtEvent
should be used.
.getElementsAtEvent(e)
Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.
Calling
getElementsAtEvent(event)
on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.canvas.onclick = function(evt){ var activePoints = myLineChart.getElementsAtEvent(evt); // => activePoints is an array of points on the canvas that are at the same position as the click event. };
Example: https://jsfiddle.net/u1szh96g/208/
Original answer (valid for Chart.js 1.x version):
You can achieve this using getSegmentsAtEvent(event)
Calling
getSegmentsAtEvent(event)
on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at that the same position of that event.
From: Prototype Methods
So you can do:
$("#myChart").click(
function(evt){
var activePoints = myNewChart.getSegmentsAtEvent(evt);
/* do something */
}
);
Here is a full working example:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
$("#myChart").click(
function(evt){
var activePoints = myNewChart.getSegmentsAtEvent(evt);
var url = "http://example.com/?label=" + activePoints[0].label + "&value=" + activePoints[0].value;
alert(url);
}
);
}
);
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>
If you run "dir c:\
", the last line will give you the free disk space.
Edit:
Better solution: "fsutil volume diskfree c:
"
I've never heard of such a function, but it would be trivial enough to implement...
def die(msg)
puts msg
exit
end
Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)
You can try opening the wsdl in web browser and saving with .wsdl extension. And set the WSDL in SOAP UI project to this .wsdl file. This really works.
Using
data : JSON.stringify(obj)
in the above situation would have worked I believe.
Note: You should add json2.js library all browsers don't support that JSON object (IE7-) Difference between json.js and json2.js
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
Usually for jumping people use Rigidbody2D.AddForce
with Forcemode.Impulse
. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.
Example:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
If you work on Windows , you must start Android Studio name by Administrator. It solved my problem
There's native method to work with date
const date = new Date();
let hours = date.getHours();
public int this[int index]
{
get => values[index];
}
If you have root access to the server where mysql is running you should stop the mysql server using this command
sudo service mysql stop
Now start mysql using this command
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
Now you can login to mysql using
sudo mysql
FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
Full instructions can be found here http://www.techmatterz.com/recover-mysql-root-password/
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
Late answer, but for up-to-date info...
If you install node.js using the recommend method from the node github installation readme, it suggests following the instructions on the nodesource blog article, rather than installing from the out of date apt-get repo, node.js should run using the node
command, as well as the nodejs
command, without having to make a new symlink.
This method from article is:
# Note the new setup script name for Node.js v0.12
curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -
# Then install with:
sudo apt-get install -y nodejs
Note that this is for v0.12, which will get likely become outdated in the not to distant future.
Also, if you're behind a corporate proxy (like me) you'll want to add the -E option to the sudo command, to preserve the env vars required for the proxy:
curl -sL https://deb.nodesource.com/setup_0.12 | sudo -E bash -
With current version of Angular Material (6.4.7) you can use a custom class:
let dialogRef = dialog.open(UserProfileComponent, {
panelClass: 'my-class'
});
Now put your class somewhere global (haven't been able to make this work elsewhere), e.g. in styles.css
:
.my-class .mat-dialog-container{
height: 400px;
width: 600px;
border-radius: 10px;
background: lightcyan;
color: #039be5;
}
Done!
White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:
if ($someElement.children().length == 0){
someAction();
}
For reasonably modern versions of sed, edit the standard input to yield the standard output with
$ echo 't???? ß?ß??? ?? ??p??' | sed -E -e 's/[[:blank:]]+/\n/g'
t????
ß?ß???
??
??p??
If your vocabulary words are in files named lesson1
and lesson2
, redirect sed’s standard output to the file all-vocab
with
sed -E -e 's/[[:blank:]]+/\n/g' lesson1 lesson2 > all-vocab
What it means:
[[:blank:]]
matches either a single space character or
a single tab character.
[[:space:]]
instead to match any single whitespace character (commonly space, tab, newline, carriage return, form-feed, and vertical tab).+
quantifier means match one or more of the previous pattern.[[:blank:]]+
is a sequence of one or more characters that are all space or tab.\n
in the replacement is the newline that you want./g
modifier on the end means perform the substitution as many times as possible rather than just once.-E
option tells sed to use POSIX extended regex syntax and in particular for this case the +
quantifier. Without -E
, your sed command becomes sed -e 's/[[:blank:]]\+/\n/g'
. (Note the use of \+
rather than simple +
.)For those familiar with Perl-compatible regexes and a PCRE-capable sed, use \s+
to match runs of at least one whitespace character, as in
sed -E -e 's/\s+/\n/g' old > new
or
sed -e 's/\s\+/\n/g' old > new
These commands read input from the file old
and write the result to a file named new
in the current directory.
Going back to almost any version of sed since Version 7 Unix, the command invocation is a bit more baroque.
$ echo 't???? ß?ß??? ?? ??p??' | sed -e 's/[ \t][ \t]*/\
/g'
t????
ß?ß???
??
??p??
Notes:
+
quantifier and simulate it with a single space-or-tab ([ \t]
) followed by zero or more of them ([ \t]*
).\n
for newline, we have to include it on the command line verbatim.
\
and the end of the first line of the command is a continuation marker that escapes the immediately following newline, and the remainder of the command is on the next line.
The commands above all used single quotes (''
) rather than double quotes (""
). Consider:
$ echo '\\\\' "\\\\"
\\\\ \\
That is, the shell applies different escaping rules to single-quoted strings as compared with double-quoted strings. You typically want to protect all the backslashes common in regexes with single quotes.
Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:
#! /bin/bash
awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2
Use it like so:
$ ./cgrep pattern [file]
Unfortunately, it doesn't have all the functionality of grep.
For more information , you can refer to an article "So You Like Color" in Linux Journal
This happened to me earlier (didn't have access to an EC2 instance someone else created but had access to AWS web console) and I blogged the answer: http://readystate4.com/2013/04/09/aws-gaining-ssh-access-to-an-ec2-instance-you-lost-access-to/
Basically, you can detached the EBS drive, attach it to an EC2 that you do have access to. Add your SSH pub key to ~ec2-user/.ssh/authorized_keys
on this attached drive. Then put it back on the old EC2 instance. step-by-step in the link using Amazon AMI.
No need to make snapshots or create a new cloned instance.
Your understanding is correct. However, if we walk through:
(.*)
will swallow the whole string;(\\d+)
is satistifed (which is why 0
is captured, and not 3000
);(.*)
will then capture the rest.I am not sure what the original intent of the author was, however.
How about using the entity codes...
@ = %40
& = %26
So, you would have:
curl -d 'name=john&passwd=%4031%263*J' https://www.mysite.com
Loop through the file.
f = open("masters.txt")
lines = f.readlines()
for line in lines:
print line
DML have to be committed or rollbacked. DDL cannot.
http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands
You can switch auto-commit on and that's again only for DML. DDL are never part of transactions and therefore there is nothing like an explicit commit/rollback.
truncate
is DDL and therefore commited implicitly.
Edit
I've to say sorry. Like @DCookie and @APC stated in the comments there exist sth like implicit commits for DDL. See here for a question about that on Ask Tom.
This is in contrast to what I've learned and I am still a bit curious about.
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
while making ReactiveForm:[define properety disbaled in FormControl]
'fieldName'= new FormControl({value:null,disabled:true})
html:
<input type="text" aria-label="billNo" class="form-control" formControlName='fieldName'>
These are the changes since python 2:
try:
1 / 0
except Exception as e: # (as opposed to except Exception, e:)
# ^ that will just look for two classes, Exception and e
# for the repr
print(repr(e))
# for just the message, or str(e), since print calls str under the hood
print(e)
# the arguments that the exception has been called with.
# the first one is usually the message. (OSError is different, though)
print(e.args)
You can look into the standard library module traceback for fancier stuff.
In RStudio you can write directly in a cell.
Suppose your data.frame is called myDataFrame
and the row and column are called columnName
and rowName
.
Then the code would look like:
myDataFrame["rowName", "columnName"] <- value
Hope that helps!
Simple code to implement ReCaptcha v3
The basic JS code
<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
.then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
The basic HTML code
<form id="form_id" method="post" action="your_action.php">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="hidden" name="action" value="validate_captcha">
.... your fields
</form>
The basic PHP code
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
} else {
$captcha = false;
}
if (!$captcha) {
//Do something with error
} else {
$secret = 'Your secret key here';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
// use json_decode to extract json response
$response = json_decode($response);
if ($response->success === false) {
//Do something with error
}
}
//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->success==true && $response->score <= 0.5) {
//Do something to denied access
}
You have to filter access using the value of $response.score. It can takes values from 0.0 to 1.0, where 1.0 means the best user interaction with your site and 0.0 the worst interaction (like a bot). You can see some examples of use in ReCaptcha documentation.
The ps
solution was nearly what I needed and with some bash thrown in does exactly what the original question asked for: to see per-core usage of specific processes
This shows per-core usage of multi-threaded processes too.
Use like: cpustat `pgrep processname` `pgrep otherprocessname` ...
#!/bin/bash
pids=()
while [ $# != 0 ]; do
pids=("${pids[@]}" "$1")
shift
done
if [ -z "${pids[0]}" ]; then
echo "Usage: $0 <pid1> [pid2] ..."
exit 1
fi
for pid in "${pids[@]}"; do
if [ ! -e /proc/$pid ]; then
echo "Error: pid $pid doesn't exist"
exit 1
fi
done
while [ true ]; do
echo -e "\033[H\033[J"
for pid in "${pids[@]}"; do
ps -p $pid -L -o pid,tid,psr,pcpu,comm=
done
sleep 1
done
Note: These stats are based on process lifetime, not the last X seconds, so you'll need to restart your process to reset the counter.
The -p
flag of netstat
gives you PID of the process:
netstat -l -p
Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat
.
As we worked out during the discussion with @Cyclone, the line that does the job is:
sockstat -4 -l | grep :80 | awk '{print $3}' | head -1
Because the people who created Java wanted boolean to mean unambiguously true or false, not 1 or 0.
There's no consensus among languages about how 1 and 0 convert to booleans. C uses any nonzero value to mean true and 0 to mean false, but some UNIX shells do the opposite. Using ints weakens type-checking, because the compiler can't guard against cases where the int value passed in isn't something that should be used in a boolean context.
On Ubuntu 16.04
Here's how I fixed this issue: Refer Docker Compose documentation
sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
After you do the curl command , it'll put docker-compose into the
/usr/local/bin
which is not on the PATH
.
To fix it, create a symbolic link:
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
And now if you do:
docker-compose --version
You'll see that docker-compose is now on the PATH
String s = "3.14";
float f = Float.parseFloat(s);
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
May be like this:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^OLDDOMAIN\.com$ [NC]
RewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L]
Add %0D%0A
to any place you want to encode a line break on the URL.
%0D
is a carriage return character%0A
is a line break characterThis is the new line sequence on windows machines, though not the same on linux and macs, should work in both.
If you want a linebreak in actual javascript, use the \n
escape sequence.
onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'
Don't overlook AT&T's U/Win software, which is designed to help you compile Unix applications on windows (last version - 2012-08-06; uses Eclipse Public License, Version 1.0).
Like Cygwin they have to run against a library; in their case POSIX.DLL
. The AT&T guys are terrific engineers (same group that brought you ksh and dot) and their stuff is worth checking out.
Use With in the code.
Try this way :
''''Way 1
currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))
''''Way 2
With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With
''''Way 3
With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then()
so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback
app.service('cookieInfoService', function() {
this.getInfo = function(callback) {
var model = {};
chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
model.response= response;
callback(model);
});
};
});
Then in my controller
app.controller("MyCtrl", function ($scope, cookieInfoService) {
cookieInfoService.getInfo(function (info) {
console.log(info);
});
});
Hope this can help others getting the same issue.
In Android 5.0 material design guidelines discourage the use of icon in actionBar
to enable it add the following code
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
credit goes to author of this article
I found that I had accidentally changed the provisioning profile to have a wildcard in it.
Ie., it went from com.companyname.appnickname to com.companyname.*
I made a new provisioning profile with the full name correctly named, downloaded it, set the Target->build settings->provisioning profile to that new profile, restarted xcode, got a bizarre error from xcode (it seemed to confuse my various app developer logins), restarted xcode again, and it worked!
I didn't want to delete the existing app, because I was trying to test what happens when a user upgraded their app to a newer version, so I had installed the app store version and then run my xcode with the newer version (which acts like 'upgrading' the app without removing any user data).
Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
I have noticed that your success function has the parameter "html", and you are trying to add "data" to your elements html()
... Change it so these both match:
$.ajax({
type:"POST",
url: "ajax.php",
data:"id="+id ,
success: function(data){
$("#response").html(data);
}
});
You could use Reflection to get the value of the property.
list = list.OrderBy( x => TypeHelper.GetPropertyValue( x, sortBy ) )
.ToList();
Where TypeHelper has a static method like:
public static class TypeHelper
{
public static object GetPropertyValue( object obj, string name )
{
return obj == null ? null : obj.GetType()
.GetProperty( name )
.GetValue( obj, null );
}
}
You might also want to look at Dynamic LINQ from the VS2008 Samples library. You could use the IEnumerable extension to cast the List as an IQueryable and then use the Dynamic link OrderBy extension.
list = list.AsQueryable().OrderBy( sortBy + " " + sortDirection );
You almost always want autocrlf=input
unless you really know what you are doing.
Some additional context below:
It should be either
core.autocrlf=true
if you like DOS ending orcore.autocrlf=input
if you prefer unix-newlines. In both cases, your Git repository will have only LF, which is the Right Thing. The only argument forcore.autocrlf=false
was that automatic heuristic may incorrectly detect some binary as text and then your tile will be corrupted. So,core.safecrlf
option was introduced to warn a user if a irreversable change happens. In fact, there are two possibilities of irreversable changes -- mixed line-ending in text file, in this normalization is desirable, so this warning can be ignored, or (very unlikely) that Git incorrectly detected your binary file as text. Then you need to use attributes to tell Git that this file is binary.
The above paragraph was originally pulled from a thread on gmane.org, but it has since gone down.
I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs
$('#parentContainer td:nth-child(2)')
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
Building on jävi's answer, this can be done without IDs or additional button attributes like this:
http://jsfiddle.net/isherwood/E5Ly5/
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My first popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My second popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My third popover content goes here.</div>
$('.popper').popover({
container: 'body',
html: true,
content: function () {
return $(this).next('.popper-content').html();
}
});
The only way I know is by copying:
List<TestB> list = new ArrayList<TestB> (
Arrays.asList (
testAList.toArray(new TestB[0])
)
);
In selec2 site you can see options. There is "disabled" option for api. You can use like :
$('#foo').select2({
disabled: true
});
This works best for me on OS X:
grep -r -l 'searchtext' . | sort | uniq | xargs perl -e "s/matchtext/replacetext/" -pi
Source: http://www.praj.com.au/post/23691181208/grep-replace-text-string-in-files
I assume the original question included how does Express use this environment variable.
Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error
, to avoid leaking implementation details to the world.
If the code for your jar library is on GitHub then importing into Android Studio is easy with JitPack.
Your will just need to add the repository to build.gradle:
allprojects{
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
and then the library's GitHub repository as a dependency:
dependencies {
// ...
compile 'com.github.YourUsername:LibraryRepo:ReleaseTag'
}
JitPack acts as a maven repository and can be used like Maven Central. The nice thing is that you don't have to upload the jar manually. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore it works only if the repo has a build file in it (build.gradle).
There is also a guide on how to prepare an Android project.
One more simple way is using the File.AppendText
it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter
using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{
sw.WriteLine("this is a log");
}
You can convert BigDecimal
to double
using .doubleValue()
. But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal
objects directly. Precision loss in these calculations are big time problems in currency related calculations.
First run command composer install
Then check for .env.example and .env files in your project folder.
.env file is your main configuration file for database and .env.example is backup file for .env file.
.env.example file will always be there but sometimes .env file can be missing. just copy the .env.example file and paste in the same project folder with filename .env .
now run php artisan key:generate
command. this will generate key for your application.
I believe the problem is simply a spelling error when writing bbcode as bbocde:
$("#vinanghinguyen_images_bbocde").val('')
should be:
$("#vinanghinguyen_images_bbcode").val('')
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack
In case .empty() doesn't work for you, which is for me
function SetDropDownToEmpty()
{
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");
}
$(document).ready(
SetDropDownToEmpty() ;
)
If anyone wants to add an URL on a single marker which not require for loops, here is how it goes:
if ($('#googleMap').length) {
var initialize = function() {
var mapOptions = {
zoom: 15,
scrollwheel: false,
center: new google.maps.LatLng(45.725788, -73.5120818),
styles: [{
stylers: [{
saturation: -100
}]
}]
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
animation: google.maps.Animation.BOUNCE,
icon: 'example-marker.png',
map: map,
url: 'https://example.com'
});
//Add an url to the marker
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
// Add the map initialize function to the window load function
google.maps.event.addDomListener(window, "load", initialize);
}
In SQL, a comparison between a null
value and any other value (including another null
) using a comparison operator (eg =
, !=
, <
, etc) will result in a null
, which is considered as false
for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).
The reasoning is that a null
means "unknown", so the result of any comparison to a null
is also "unknown". So you'll get no hit on rows by coding where my_column = null
.
SQL provides the special syntax for testing if a column is null
, via is null
and is not null
, which is a special condition to test for a null
(or not a null
).
Here's some SQL showing a variety of conditions and and their effect as per above.
create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);
select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);
returns only 1 row (as expected):
TEST X Y
x = y 1 1
See this running on SQLFiddle
I found this catered for dates in 21st Century that could be entered as dd/mm or dd/mm/yy. It is intended to print an attendance register and asks for the meeting date to start with.
Sub Print_Register()
Dim MeetingDate, Answer
Sheets("Register").Select
Range("A1").Select
GetDate:
MeetingDate = DateValue(InputBox("Enter the date of the meeting." & Chr(13) & _
"Note Format" & Chr(13) & "Format DD/MM/YY or DD/MM", "Meeting Date", , 10000, 10000))
If MeetingDate = "" Then GoTo TheEnd
If MeetingDate < 36526 Then MeetingDate = MeetingDate + 36526
Range("Current_Meeting_Date") = MeetingDate
Answer = MsgBox("Date OK?", 3)
If Answer = 2 Then GoTo TheEnd
If Answer = 7 Then GoTo GetDate
ExecuteExcel4Macro "PRINT(1,,,1,,,,,,,,2,,,TRUE,,FALSE)"
TheEnd:
End Sub
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
Using command line:
python -c "import scipy; print(scipy.__version__)"
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Python's ability to provide default values for function arguments gives us a way out.
def fce(x=myX, y=myY):
myFunction(x,y)
button = Tk.Button(mainWin, text='press', command=fce)
See: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/extra-args.html
For more buttons you can create a function which returns a function:
def fce(myX, myY):
def wrapper(x=myX, y=myY):
pass
pass
pass
return x+y
return wrapper
button1 = Tk.Button(mainWin, text='press 1', command=fce(1,2))
button2 = Tk.Button(mainWin, text='press 2', command=fce(3,4))
button3 = Tk.Button(mainWin, text='press 3', command=fce(9,8))
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
You can change the matplotlib using backend using the from agg
to Tkinter TKAgg
using command
matplotlib.use('TKAgg',warn=False, force=True)
Well, after doing more research on this topic I ended up using following solution for targeting IE 10+. As IE10&11 are the only browsers which support the -ms-high-contrast media query, that is a good option without any JS:
@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none) {
/* IE10+ specific styles go here */
}
Works perfectly.
git commit --amend
and press Enter.git push --force example-branch
command to force push over the old commit.Source: https://help.github.com/articles/changing-a-commit-message/
Many ways to do this. You could use wildcards in double brackets:
str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi
You can use substring expansion:
if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi
Or a regex:
if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
Edit: Add some code to account for the page scrolling.
function findPos(id) {
var node = document.getElementById(id);
var curtop = 0;
var curtopscroll = 0;
if (node.offsetParent) {
do {
curtop += node.offsetTop;
curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
} while (node = node.offsetParent);
alert(curtop - curtopscroll);
}
}
The id argument is the id of the element whose offset you want. Adapted from a quirksmode post.
Think about the gitk
tool also , provided with git and very useful to see the changes