You can use
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
If you want to copy a line to the clipboard you can also use the trick:
Ctrl-Alt-Down followed by Ctrl-X
The drawback is that the file where you copy the line from becomes dirty.
Try putting \
at the end of each line before copying it.
Example:
echo "Hello world" && \
script_b.sh
echo $?
The exit code ($?
) is now the full sequence of commands, and not just the last command.
library(plyr)
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[2:4],sep="",collapse="-"))))
# x
#1 a-d-g
#2 b-e-h
#3 c-f-i
# and with just the vector of names you have:
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[c('b','c','d')],sep="",collapse="-"))))
# or equally:
mynames <-c('b','c','d')
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[mynames],sep="",collapse="-"))))
$(document).ready(function() {
$("#editor").bind('paste', function (e){
$(e.target).keyup(getInput);
});
function getInput(e){
var inputText = $(e.target).html(); /*$(e.target).val();*/
alert(inputText);
$(e.target).unbind('keyup');
}
});
See this example: http://www.p2e.dk/diverse/detectPaste.htm
It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:
$ (something).bind ("input paste", function (e) {
// check for paste as in example above and
// do something
})
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
If all image’s heights are same,
imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
np.concatenate(
[np.array(Image.open(x)) for x in imgs],
axis=1
)
)
maybe you can resize images before the concatenation like this,
imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
np.concatenate(
[np.array(Image.open(x).resize((640,480)) for x in imgs],
axis=1
)
)
use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Below are the example of use:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
I hope above example is useful.
Form user_rpt = Application.OpenForms["frmUesr_reports"];
if (user_rpt == null)
{
/// Do Something here
}
Try This This is the short idea to check Form open or not open
I found the presented versions way to aggressive, especially if you commit patches from other developers, this will essentially steal their code.
The version below does work on all branches and changes the author and comitter separately to prevent that.
Kudos to leif81 for the all option.
#!/bin/bash
git filter-branch --env-filter '
if [ "$GIT_AUTHOR_NAME" = "<old author>" ];
then
GIT_AUTHOR_NAME="<new author>";
GIT_AUTHOR_EMAIL="<[email protected]>";
fi
if [ "$GIT_COMMITTER_NAME" = "<old committer>" ];
then
GIT_COMMITTER_NAME="<new commiter>";
GIT_COMMITTER_EMAIL="<[email protected]>";
fi
' -- --all
To just get the index column names df.index.names
will work for both a single Index or MultiIndex as of the most recent version of pandas.
As someone who found this while trying to find the best way to get a list of index names + column names, I would have found this answer useful:
names = list(filter(None, df.index.names + df.columns.values.tolist()))
This works for no index, single column Index, or MultiIndex. It avoids calling reset_index() which has an unnecessary performance hit for such a simple operation. I'm surprised there isn't a built in method for this (that I've come across). I guess I run into needing this more often because I'm shuttling data from databases where the dataframe index maps to a primary/unique key, but is really just another column to me.
It is because you must have set content type as text/html instead of text/css for your server page (php,node.js etc)
It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.
You can't change the height of the br
tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.
You can change the line height using the line-height
style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.
For completeness: Text blocks in HTML is usually done using the p
tag around text blocks. That way you can control the line height inside the p
tag, and also the spacing between the p
tags.
My solution (vb.net):
Private Function ConvertToBoolean(p1 As Object) As Boolean
If p1 Is Nothing Then Return False
If IsDBNull(p1) Then Return False
If p1.ToString = "1" Then Return True
If p1.ToString.ToLower = "true" Then Return True
Return False
End Function
How about the following 3 statements?
-- change to your schema
ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;
-- check current schema
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;
-- generate drop table statements
SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';
COPY the RESULT and PASTE and RUN.
There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension
It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.
Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?
Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.
tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.
Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.
hth! Regards, Remco
Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:
MsgBox RunMacros
You can download and install two different xampps like I do: (first is php7 second is php5)
and if you don't want to do that, I suggest you use wamp and change versions like shown here.
You can use the CURSOR_STATUS function to determine its state.
IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
DEALLOCATE myCursor
END
The easiest thing you can do is wrap the contents of the <li>
in a <span>
or equivalent then you can set the color independently.
Alternatively, you could make an image with the bullet color you want and set it with the list-style-image
property.
Error in Events:
The application (VMware Workstation, from vendor VMware, Inc.) has the following problem: To function properly, VMware Workstation must be reinstalled after you upgrade Windows.
Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).
With this in mind, the first version should be preferred.
Using element-wise multiplication and a set:
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})
Output:
{4, 5, 7}
1st preference external style sheet.
<span class="myClass">test</span>
css
.myClass
{
color:red;
}
2nd preference inline style
<span style="color:red">test</span>
<font>
as mentioned is deprecated.
None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.
from pyhive import hive
cursor = hive.connect(host="localhost",
port=10000,
username="shadan",
auth="KERBEROS",
kerberos_service_name="hive"
).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
The given solution did not work for me, however a similar version did...
This is with a cloned repository, hence the submodule git repos are contained in the top repositories .git dir. All cations are from the top repository:
Edit .gitmodules and change the "path =" setting for the submodule in question. (No need to change the label, nor to add this file to index.)
Edit .git/modules/name/config and change the "worktree =" setting for the submodule in question
run:
mv submodule newpath/submodule
git add -u
git add newpath/submodule
I wonder if it makes a difference if the repositories are atomic, or relative submodules, in my case it was relative (submodule/.git is a ref back to topproject/.git/modules/submodule)
Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>()
for more readable code. Also you might want to consider checking the MemoryStream
class depending on what you're trying to achieve.
I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.
Hope this is of some help.
Instead of rejecting, resolve it with a object. You could do something like this when you are implementing promise
const promise = arg => {_x000D_
return new Promise((resolve, reject) => {_x000D_
setTimeout(() => {_x000D_
try{_x000D_
if(arg != 2)_x000D_
return resolve({success: true, data: arg});_x000D_
else_x000D_
throw new Error(arg)_x000D_
}catch(e){_x000D_
return resolve({success: false, error: e, data: arg})_x000D_
}_x000D_
}, 1000);_x000D_
})_x000D_
}_x000D_
_x000D_
Promise.all([1,2,3,4,5].map(e => promise(e))).then(d => console.log(d))
_x000D_
From http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
I faced same issue on my wordpress site. After the lot of debugging i fixed my problem step by step like this.
define('SCRIPT_DEBUG', TRUE); define('WP_DEBUG', TRUE); define( 'WP_DEBUG_LOG', true );
deferred.jqXHR = $.ajax( options ).done( function( response ) { try { response = JSON.parse(response); } catch (Exception) { response = response; }
Please check your may be resolved.
define('SCRIPT_DEBUG', TRUE); define('WP_DEBUG', TRUE); define( 'WP_DEBUG_LOG', true );
*change your own risk if your update your wordpress version your changed may be lost.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples
${parameter-default}, ${parameter:-default}
If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra :
makes a difference only when parameter has been declared, but is null.
unset EGGS
echo 1 ${EGGS-spam} # 1 spam
echo 2 ${EGGS:-spam} # 2 spam
EGGS=
echo 3 ${EGGS-spam} # 3
echo 4 ${EGGS:-spam} # 4 spam
EGGS=cheese
echo 5 ${EGGS-spam} # 5 cheese
echo 6 ${EGGS:-spam} # 6 cheese
${parameter=default}, ${parameter:=default}
If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS # 2 spam
EGGS=
: ${EGGS=spam}
echo 3 $EGGS # 3 (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS # 4 spam
EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS # 6 cheese
${parameter+alt_value}, ${parameter:+alt_value}
If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
unset EGGS
echo 1 ${EGGS+spam} # 1
echo 2 ${EGGS:+spam} # 2
EGGS=
echo 3 ${EGGS+spam} # 3 spam
echo 4 ${EGGS:+spam} # 4
EGGS=cheese
echo 5 ${EGGS+spam} # 5 spam
echo 6 ${EGGS:+spam} # 6 spam
To produce key events without Windows Forms Context, We can use the following method,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
I got its answer. Here is my code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
And my script is
$(function() {
$('#dbType').change(function() {
$('.selectDBType').slideUp("slow");
$('#' + $(this).val()).slideDown("slow");
});
});
To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
.
The point is that you have to call Invoke()
of the Dispatcher
of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher
. So instead you should use YourControl.Dispatcher.Invoke()
to be safe. I was banging my head for a couple of hours before I realized this.
For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.
Use breakpoint mixins like this:
.something {
padding: 5px;
@include media-breakpoint-up(sm) {
padding: 20px;
}
@include media-breakpoint-up(md) {
padding: 40px;
}
}
v4 alpha6 breakpoints reference
Below full options and values.
Breakpoint & up (toggle on value and above):
@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }
breakpoint & up values:
// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
breakpoint & down (toggle on value and down):
@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }
breakpoint & down values:
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }
// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width
breakpoint only:
@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }
breakpoint only values (toggle in between values only):
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1()
from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
The answer to many CSS formatting problems seems to be "add another <div>!"
So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):
textarea_x000D_
{_x000D_
width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
border:1px solid #999999;_x000D_
margin:5px 0;_x000D_
padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
<label for="rules" id="ruleslabel">Rules:</label>_x000D_
<div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
You can use
filter: brightness(0) invert(1);
html {_x000D_
background: red;_x000D_
}_x000D_
p {_x000D_
float: left;_x000D_
max-width: 50%;_x000D_
text-align: center;_x000D_
}_x000D_
img {_x000D_
display: block;_x000D_
max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
-webkit-filter: brightness(0) invert(1);_x000D_
filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
Original:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
Filter:_x000D_
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
First, brightness(0)
makes all image black, except transparent parts, which remain transparent.
Then, invert(1)
makes the black parts white.
You could use Mono for Android
:
http://xamarin.com/monoforandroid
An alternative is dot42
:
dot42 provides a free community licence as well as a professional licence for $399.
Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.
If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.
For example, in a query you link two tables in a select statement with a join:
SELECT a, b from table1 LEFT JOIN table2 USING (common_field);
IntelliJ needs the subversion command(svn) added into Subversion settings. Here are the steps: 1. Download and Install subversion. 2. check on the command line prompt on windows(cmd) for the same command - svn.
You can open the project in the firebase, then you should click on the project overview, then goto project settings you will see the web API Key there.
This may help you.
try
{
con.Open();
if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
{
filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
ext = System.IO.Path.GetExtension(filename).ToLower();
string str=@"/Resumes/" + filename;
saveloc = (Server.MapPath(".") + str);
string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
for (int i = 0; i < exts.Length; i++)
{
if (ext == exts[i])
fileok = true;
}
if (fileok)
{
if (File.Exists(saveloc))
throw new Exception(Label1.Text="File exists!!!");
fileUpload1.PostedFile.SaveAs(saveloc);
cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Upload Successful!!!";
Label1.ForeColor = System.Drawing.Color.Blue;
con.Close();
}
else
{
Label1.Text = "Upload not successful!!!";
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ee) { Label1.Text = ee.Message; }
I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.
If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar
, which is available in SQLLIB/java/
folder of your db2 installation.
Just put the condition into the lambda itself, e.g.
animalMap.entrySet().stream()
.forEach(
pair -> {
if (pair.getValue() != null) {
myMap.put(pair.getKey(), pair.getValue());
} else {
myList.add(pair.getKey());
}
}
);
Of course, this assumes that both collections (myMap
and myList
) are declared and initialized prior to the above piece of code.
Update: using Map.forEach
makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:
animalMap.forEach(
(key, value) -> {
if (value != null) {
myMap.put(key, value);
} else {
myList.add(key);
}
}
);
Let's say you have a shiny Foo class. Well you have 3 options:
1) You want to use the method (or attribute) of a class inside the definition of that class:
class Foo(object):
attribute1 = 1 # class attribute (those don't use 'self' in declaration)
def __init__(self):
self.attribute2 = 2 # instance attribute (those are accessible via first
# parameter of the method, usually called 'self'
# which will contain nothing but the instance itself)
def set_attribute3(self, value):
self.attribute3 = value
def sum_1and2(self):
return self.attribute1 + self.attribute2
2) You want to use the method (or attribute) of a class outside the definition of that class
def get_legendary_attribute1():
return Foo.attribute1
def get_legendary_attribute2():
return Foo.attribute2
def get_legendary_attribute1_from(cls):
return cls.attribute1
get_legendary_attribute1() # >>> 1
get_legendary_attribute2() # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo) # >>> 1
3) You want to use the method (or attribute) of an instantiated class:
f = Foo()
f.attribute1 # >>> 1
f.attribute2 # >>> 2
f.attribute3 # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3 # >>> 3
You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:
package main
import (
"fmt"
"encoding/json"
)
type User struct {
name string
}
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
}{
Name: "customized" + u.name,
})
}
func main() {
user := &User{name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Though this is probably far too late, there is a slightly simpler alternative to the previous answer:
__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)
(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using str()
.)
Of course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__
, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int()
and str()
can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)
This is, of course, my own view, and I would gladly like others' input on using a numerical tuple.
As shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing __version_info__
(or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.
Just add http://download.eclipse.org/egit/updates to your Eclipse update manager.
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
This is a very common looping idiom. in
is an operator. For when to use for key in dict
and when it must be for key in dict.keys()
see David Goodger's Idiomatic Python article (archived copy).
I added
"types": [
"node"
]
in my tsconfig file and its worked for me tsconfig.json file look like
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": [
"node",
"underscore"
]
},
here describes the process well. However, some of the characters that didn't fit in latin space are gone forever. UTF-8 is a SUPERSET of latin1. Not the reverse. Most will fit in single byte space, but any undefined ones will not (check a list of latin1 - not all 256 characters are defined, depending on mysql's latin1 definition)
To resolve problem go to the MDaemon-->setup-->Miscellaneous options-->Server-->SMTP Server Checks commands and headers for RFC Compliance
If you are add more than argument ya dropdownlist in Asp.Net MVC. When you Edit record or pass value in view bag.
Use this it will be work:-
@Html.DropDownList("CurrencyID",null,String.Empty, new { @class = "form-control-mandatory" })
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
The best way in my eyes is to use the concat()
method provided by the String
class itself.
The useage would, in your case, look like this:
String myConcatedString = cursor.getString(numcol).concat('-').
concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
You can substitute in HTML entitiy:
$FileName = preg_replace("/'/", "\'", $UserInput);
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
You can change the row height of the Datagridview in the
.cs [Design]
.
Then click the datagridview Properties
.
Look for RowTemplate
and expand it,
then type the value in the Height
.
"FetchType.LAZY
" will only fire for primary table. If in your code you call any other method that has a parent table dependency then it will fire query to get that table information. (FIRES MULTIPLE SELECT)
"FetchType.EAGER
" will create join of all table including relevant parent tables directly. (USES JOIN
)
When to Use:
Suppose you compulsorily need to use dependant parent table informartion then choose FetchType.EAGER
.
If you only need information for certain records then use FetchType.LAZY
.
Remember, FetchType.LAZY
needs an active db session factory at the place in your code where if you choose to retrieve parent table information.
E.g. for LAZY
:
.. Place fetched from db from your dao loayer
.. only place table information retrieved
.. some code
.. getCity() method called... Here db request will be fired to get city table info
Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.
You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.
This answer shows how to write "normal/easily understandable" pythonic code.
I suggest not using zip
as not really everyone knows about it.
The solutions use list comprehensions and common built-in functions.
a = [2, 2, 2]
b = [1, 1, 1]
result = [a[i] - b[i] for i in range(len(a))]
Recommended as it only uses the most basic functions in Python
a = [2, 2, 2]
b = [1, 1, 1]
result = [x - b[i] for i, x in enumerate(a)]
a = [2, 2, 2]
b = [1, 1, 1]
result = list(map(lambda x, y: x - y, a, b))
Here is a class 'getJ' with a static function 'chr()'. This function reads one char.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class getJ {
static char chr()throws IOException{
BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
return bufferReader.readLine().charAt(0);
}
}
In order to read a char use this:
anyFunc()throws IOException{
...
...
char c=getJ.chr();
}
Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean you don't need to do:
getJ ob = new getJ;
c=ob.chr();
You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:
anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
}
catch(IOException e)
{
System.out.println("IOException has been caught");
}
Credit to: tutorialspoint.com
See also: geeksforgeeks.
This was in response to your other question, that looks like it's been deleted....the point still stands.
Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.
.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).
My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:
using System.Text;
string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);
byte[] bAsciiString = encoder.GetBytes(inputString);
// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString);
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));
Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)
DEFAULT
is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL
constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT
in UPDATE
statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL
constraint will cause an error with statements 4, 6
, while 1-3, 5
are still valid statements. So to answer your question: No, they're not redundant.
You can extend multiple Interfaces
but you cannot extend multiple classes
.
The reason that it is not possible in Java to extending multiple classes, is the bad experience from C++ where this is possible.
The alternative for multipe inheritance is that a class can implement multiple interfaces (or an Interface can extend multiple Interfaces)
A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:
#globals.py
class dbinfo : # for database globals
username = 'abcd'
password = 'xyz'
class runtime :
debug = False
output = 'stdio'
Then, if you have two code files c1.py and c2.py, both can have at the top
import globals as gl
Now all code can access and set values, as such:
gl.runtime.debug = False
print(gl.dbinfo.username)
People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.
By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.
This lacks some of the clever error checking of other approaches, but is simple and easy to follow.
I had the same problem. I was using Python 2, Windows 10 and Git Bash. Turns out in Git Bash you need to use:
source venv/Scripts/activate
Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')
Holding down the Ctrl key highlight two or more columns in the left hand table margin
Hit the little 'Key' on the standard menu bar at the top
You're done..
:-)
Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app
module, call mod_login.mod_login
app.py
from flask import Flask
import mod_login
# ...
do_stuff_with(mod_login.mod_login)
mod_login.py
from app import app
mod_login = something
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(7);
vec.push_back(4);
vec.push_back(9);
vec.push_back(7);
std::ostringstream oss;
if (!vec.empty())
{
// Convert all but the last element to avoid a trailing ","
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator<int>(oss, ","));
// Now add the last element with no delimiter
oss << vec.back();
}
std::cout << oss.str() << std::endl;
}
There are two distinct uses of mipmaps:
For launcher icons when building density specific APKs. Some developers build separate APKs for every density, to keep the APK size down. However some launchers (shipped with some devices, or available on the Play Store) use larger icon sizes than the standard 48dp. Launchers use getDrawableForDensity and scale down if needed, rather than up, so the icons are high quality. For example on an hdpi tablet the launcher might load the xhdpi icon. By placing your launcher icon in the mipmap-xhdpi directory, it will not be stripped the way a drawable-xhdpi directory is when building an APK for hdpi devices. If you're building a single APK for all devices, then this doesn't really matter as the launcher can access the drawable resources for the desired density.
The actual mipmap API from 4.3. I haven't used this and am not familiar with it. It's not used by the Android Open Source Project launchers and I'm not aware of any other launcher using.
Using mordernizr to detect browsers that are not supporting Placeholder, I created this short code to fix them.
//If placeholder is not supported
if (!Modernizr.input.placeholder){
//Loops on inputs and place the placeholder attribute
//in the textbox.
$("input[type=text]").each( function() {
$(this).val($(this).attr('placeholder'));
})
}
try:
s.remove("")
except ValueError:
print "new_tag_list has no empty string"
Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);
should call the function properly; like- Fibonacci:input
For me, the problem was that my target profile by accident got set to ".Net Framework 4 Client profile". When I rebuilt the service in question using the ".Net Framework 4", the problem went away!
An alternative if you sometimes do not have spaces do not want to use the CASE statement
select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))
This works in SQL Server, and according to my searching MySQL has the same functions
When running on some trimmed down images that restrict root access, I had to add my user to the sudoers and run as sudo cron
FROM node:8.6.0_x000D_
RUN apt-get update && apt-get install -y cron sudo_x000D_
_x000D_
COPY crontab /etc/cron.d/my-cron_x000D_
RUN chmod 0644 /etc/cron.d/my-cron_x000D_
RUN touch /var/log/cron.log_x000D_
_x000D_
# Allow node user to start cron daemon with sudo_x000D_
RUN echo 'node ALL=NOPASSWD: /usr/sbin/cron' >>/etc/sudoers_x000D_
_x000D_
ENTRYPOINT sudo cron && tail -f /var/log/cron.log
_x000D_
Maybe that helps someone
This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.
The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).
<UserControl.Resources>
<!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect -->
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="DarkGray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<!-- usage in xaml -->
<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find
or Array.FindLast
if you just want one.
If you use CSS style, you can use:
$("#element").css("background-color","none");
and then replace with:
$("#element").css("background-color", color);
If you don't use CSS style and you have attribute in HTML element, you can use:
$("#element").attr("style.background-color",color);
if you want smooth scrolling add behavior
configuration.
document.getElementById('id').scrollIntoView({
behavior: 'smooth'
});
Don't live fanatically with the conventions that SUN have med up, do whats feel right to you and your team.
For example this is how eclipse do it, breaking the convention. Try adding implements Serializable
and eclipse will ask to generate this line for you.
Update: There were special cases that was excluded didn't know that. I however withholds to do what you and your team seems fit.
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
surprise to see that no have given this syntax.
.each
syntax with data or collection
jQuery.each(collection, callback(indexInArray, valueOfElement));
OR
jQuery.each( jQuery('#list option'), function(indexInArray, valueOfElement){
//your code here
});
Comparing floating point number can't always be done precisely because of rounding. To compare
(x == .1)
the computer really compares
(x - .1) vs 0
Result of sybtraction can not always be represeted precisely because of how floating point number are represented on the machine. Therefore you get some nonzero value and the condition evaluates to false
.
To overcome this compare
Math.Abs(x- .1) vs some very small threshold ( like 1E-9)
I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:
tfidfLsNew = [x for x in tfidfLs if x != []]
the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.
Be sure to include the Key
in the imports...
const {Builder, By, logging, until, Key} = require('selenium-webdriver');
searchInput.sendKeys(Key.ENTER)
worked great for me
From the feature comparison list... MySQL Workbench offers Schema Diff and Schema Synchronization in their community edition.
I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:
['file' + str(i) + '.pdf' for i in range(1,4)]
From manual: s[i:j:k] slice of s from i to j with step k
li = range(100)
sub = li[0::10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!
I think you can use date()
function to achive this
$date = '19:24:15 06/13/2013';
echo date('h:i:s a m/d/Y', strtotime($date));
This will output
07:24:15 pm 06/13/2013
h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)
Updated
This is with DateTime
$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
You can simply do this:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.
Please try:
DECLARE @FrmDt DATETIME, @ToDt DATETIME
SELECT @FrmDt='2013-01-03', @ToDt='2013-01-09'
SELECT *
FROM Product_sales
WHERE (@FrmDt BETWEEN From_date AND To_date) OR
(@ToDt BETWEEN From_date AND To_date)
As per David Manpearl answer
https://stackoverflow.com/a/12347567/7226732
we just need to modify onActivityResult() like
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == YOUR_SELECT_PICTURE_REQUEST_CODE) {
final boolean isCamera;
if (data.getExtras() == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = fileUri;
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
image_view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
}
} else {
selectedImageUri = data == null ? null : data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
Toast.makeText(CreateWaterType.this, "Image Saved!", Toast.LENGTH_SHORT).show();
image_view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(CreateWaterType.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
and set the capture or pick images in image view.
we can use \b as a word boundary and then; \b\d+\b
In order to insert the first record set of a stored procedure into a temporary table you need to know the following:
sp_executesql
)The above may look as limitation, but IMHO it perfectly makes sense - if you are using sp_executesql
you can once return two columns and once ten, and if you have multiple result sets, you cannot insert them into several tables as well - you can insert maximum in two table in one T-SQL statement (using OUTPUT
clause and no triggers).
So, the issue is mainly how to define the temporary table structure before performing the EXEC ... INTO ...
statement.
The first works with OBJECT_ID
while the second and the third works with Ad-hoc queries as well. I prefer to use the DMV instead of the sp as you can use CROSS APPLY
and build the temporary table definitions for multiple procedures at the same time.
SELECT p.name, r.*
FROM sys.procedures AS p
CROSS APPLY sys.dm_exec_describe_first_result_set_for_object(p.object_id, 0) AS r;
Also, pay attention to the system_type_name
field as it can be very useful. It stores the column complete definition. For, example:
smalldatetime
nvarchar(max)
uniqueidentifier
nvarchar(1000)
real
smalldatetime
decimal(18,2)
and you can use it directly in most of the cases to create the table definition.
So, I think in most of the cases (if the stored procedure match certain criteria) you can easily build dynamic statements for solving such issues (create the temporary table, insert the stored procedure result in it, do what you need with the data).
Note, that the objects above fail to define the first result set data in some cases like when dynamic T-SQL statements are executed or temporary tables are used in the stored procedure.
Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.
Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.
However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...
So if you must detect every change, you have to poll for it. You could window.setInterval
to check the field against its previous value every (say) second. You could also wire onkeyup
to the same function so that changes that are caused by keypresses are reflected quicker.
Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.
The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter.
function PaulDixonSolution(required, optionalArg){
optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
console.log(optionalArg);
};
PaulDixonSolution("required");
PaulDixonSolution("required", "provided");
PaulDixonSolution("required", null);
PaulDixonSolution("required", false);
The result is:
defaultValue
provided
null
false
Those last two are potentially bad. Instead try:
function bulletproof(required, optionalArg){
optionalArg = optionalArg ? optionalArg : "defaultValue";;
console.log(optionalArg);
};
bulletproof("required");
bulletproof("required", "provided");
bulletproof("required", null);
bulletproof("required", false);
Which results in:
defaultValue
provided
defaultValue
defaultValue
The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null.
You can write like this:
CSS
span{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
left:-30px;
display:none;
padding:0 20px;
}
span:after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
margin:100px;
float:left;
position:relative;
cursor:pointer;
}
p:hover span{
display:block;
}
HTML
<p>Hover here<span>some text here ?</span></p>
Check this http://jsfiddle.net/UNs9J/1/
In my case ping works from device but not from the emulator. I found this documentation: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
On the topic of "Local Networking Limitations" it says:
"Depending on the environment, the emulator may not be able to support other protocols (such as ICMP, used for "ping") might not be supported. Currently, the emulator does not support IGMP or multicast."
Further information: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297
this is a known limitation of the QEMU user-mode network stack. Quoting from the original doc: Note that ping is not supported reliably to the internet as it would require root privileges. It means you can only ping the local router (10.0.2.2).
WORKING:
$("#ContentPlaceHolder1_txtNombre").keyup(function () {
var txt = $(this).val();
$('.column').each(function () {
$(this).show();
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
$(this).hide();
}
});
//}
});
I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):
UPDATE table SET phone_num = concat('0', phone_num)
I just concated 0 in front of the phone_num
.
the implementation in the cpp file should be in the form
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
not within a class gameObject { } definition block
I had this problem and used this technique.
Its the best solution i found which is very flexible.
Also please vote here to add support for cumulative section declaration
As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.
Not dependent on Java Math.round() types
As @arpanmangal, the solutions above do not work for me (matplotlib 3.0.3
, python 3.5.2
).
It seems that using .show()
in a figure, e.g., figure.show()
, is not recommended, because this method does not manage a GUI event loop and therefore the figure is just shown briefly. (See figure.show() documentation). However, I do not find any another way to show only a figure.
In my solution I get to prevent the figure for instantly closing by using click events. We do not have to close the figure — closing the figure deletes it.
I present two options:
- waitforbuttonpress(timeout=-1)
will close the figure window when clicking on the figure, so we cannot use some window functions like zooming.
- ginput(n=-1,show_clicks=False)
will wait until we close the window, but it releases an error :-.
import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots(1) # Creates figure fig1 and add an axes, ax1
fig2, ax2 = plt.subplots(1) # Another figure fig2 and add an axes, ax2
ax1.plot(range(20),c='red') #Add a red straight line to the axes of fig1.
ax2.plot(range(100),c='blue') #Add a blue straight line to the axes of fig2.
#Option1: This command will hold the window of fig2 open until you click on the figure
fig2.waitforbuttonpress(timeout=-1) #Alternatively, use fig1
#Option2: This command will hold the window open until you close the window, but
#it releases an error.
#fig2.ginput(n=-1,show_clicks=False) #Alternatively, use fig1
#We show only fig2
fig2.show() #Alternatively, use fig1
Try this:
using System.Globalization;
using System.Threading;
public void ToTitleCase(TextBox TextBoxName)
{
int TextLength = TextBoxName.Text.Length;
if (TextLength == 1)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = 1;
}
else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength)
{
int x = TextBoxName.SelectionStart;
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = x;
}
else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = TextLength;
}
}
Call this method in the TextChanged event of the TextBox.
This seems a far easier method than those suggested elsewhere in this thread.
writelines()
does not add line separators. You can alter the list of strings by using map()
to add a new \n
(line break) at the end of each string.
items = ['abc', '123', '!@#']
items = map(lambda x: x + '\n', items)
w.writelines(items)
verify if gradle.properties define right one JAVA_HOVE
org.gradle.java.home=C:\Program Files (x86)\Java\jdk1.8.0_181
or
You could launch
a coroutine, delay
it and then call the function:
/*GlobalScope.*/launch {
delay(1000)
yourFn()
}
If you are outside of a class or object prepend GlobalScope
to let the coroutine run there, otherwise it is recommended to implement the CoroutineScope
in the surrounding class, which allows to cancel all coroutines associated to that scope if necessary.
ArrayList ar = new ArrayList();
ar.Add(1);
ar.Add(5);
ar.Add(25);
ar.Add(37);
ar.Add(6);
ar.Add(11);
ar.Add(35);
Random r = new Random();
int index = r.Next(0,ar.Count-1);
MessageBox.Show(ar[index].ToString());
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc
) as it's allocated on the heap:
char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);
More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
You can use shuf
(from the GNU coreutils package) for that. Just feed it a list of file names and ask it to return the first line from a random permutation:
ls dirname | shuf -n 1
# probably faster and more flexible:
find dirname -type f | shuf -n 1
# etc..
Adjust the -n, --head-count=COUNT
value to return the number of wanted lines. For example to return 5 random filenames you would use:
find dirname -type f | shuf -n 5
if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.
I'd prefer to use OneJar for this issue.
A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322's answer on Java 6 (i.e., Android) would be to catch all Exception
s and re-throw RuntimeException
s. This wouldn't work if you're planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.
For instance:
try {
// CODE THAT THROWS EXCEPTION
} catch (Exception e) {
if (e instanceof RuntimeException) {
// this exception was not expected, so re-throw it
throw e;
} else {
// YOUR CODE FOR ALL CHECKED EXCEPTIONS
}
}
That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.
Because interfaces are in inheritance structure, and static methods don't inherit well.
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9
Keep in mind that international users may be using a decimal separator other than .
in which case values can get mixed up or just become nil when using intValue
on a string.
For example, in the UK 1.23
is written 1,23
, so the number 1.777
would be input by user as 1,777
, which, as .intValue
, will be 1777
not 1
(truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)
I ran into the same issue and it's even worse: I needed both "import" and "require"
Here is what worked for me:
Turn your js file into .mjs as suggested in other answers
"require" is not defined with ES6 module, so you can define it this way:
import { createRequire } from 'module'
const require = createRequire(import.meta.url);
Now 'require' can be used in the usual way.
Use import for ES6 modules and require for commonJS.
Some useful links: node.js's own documentation. difference between import and require. Mozilla has some nice documentation about import
This will work as well:
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:
# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
In this case curl will send your defined cookie along with the cookies from the file.
If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).
The utma utmc, utmz
are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.
Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt
) instead of relative one.
Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.
curl_setopt($ch, CURLOPT_VERBOSE, true);
\b\d{1,6}\b
Explanation
\b # word boundary - start
\d # any digits between 0 to 9 (inclusive)
{1,6} # length - min 1 digit or max 6 digits
\b # word boundary - end
Somehow placing under "src" folder didn't work for me.
Instead placing cfg.xml as below:
[Project Folder]\src\main\resources\hibernate.cfg.xml
worked. Using this code
new Configuration().configure().buildSessionFactory().openSession();
in a file under
[Project Folder]/src/main/java/com/abc/xyz/filename.java
In addition have this piece of code in hibernate.cfg.xml
<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />
Placed the above hbm.xml files under:
EDIT:
[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml
Above structure worked.
In addition to the wrong modifier, which port of gcc to Windows? mingw uses the Microsoft C library and I seem to remember that this library has no support for 80bits long double (microsoft C compiler use 64 bits long double for various reasons).
I am going to Necro this topic.
Starting around ms-access-2016, you can execute Data Definition Queries (DDQ) through Macro's
ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);
Open Query
actionQuery Name
field; View
and Data Mode
settings are not relevant and can leave the default valuesIn visual studio.
If no errors, you should be able to see the service reference in the object browser and all related methods.
If you have couple of json files:
import data from 'sample.json';
If you were to dynamically load one of the many json file, you might have to use a fetch
instead:
fetch(`${fileName}.json`)
.then(response => response.json())
.then(data => console.log(data))
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
Follow the below steps
From feature/branch (enter the below command)
git checkout master
git pull
git checkout feature/branchname
git merge master
In addition to the other great answers, here is the typical schema people use to show the difference between NP, NP-Complete, and NP-Hard:
set STATICBUILD=true && pip install lxml
run this command instead, must have VS C++ compiler installed first
https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/
It works for me with Python 3.5.2 and Windows 7
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
Get the selected item with Kotlin:
spinner.selectedItem.toString()
This was a quick script I found that worked... .Result is assigned to a label.
$(".Result").html($("option:selected").text());
If you merge a commit into your branch, you should get all the history between.
Observe:
$ git init ./ Initialized empty Git repository in /Users/dfarrell/git/demo/.git/ $ echo 'a' > letter $ git add letter $ git commit -m 'Initial Letter' [master (root-commit) 6e59e76] Initial Letter 1 file changed, 1 insertion(+) create mode 100644 letter $ echo 'b' >> letter $ git add letter && git commit -m 'Adding letter' [master 7126e6d] Adding letter 1 file changed, 1 insertion(+) $ echo 'c' >> letter; git add letter && git commit -m 'Adding letter' [master f2458be] Adding letter 1 file changed, 1 insertion(+) $ echo 'd' >> letter; git add letter && git commit -m 'Adding letter' [master 7f77979] Adding letter 1 file changed, 1 insertion(+) $ echo 'e' >> letter; git add letter && git commit -m 'Adding letter' [master 790eade] Adding letter 1 file changed, 1 insertion(+) $ git log commit 790eade367b0d8ab8146596cd717c25fd895302a Author: Dan Farrell Date: Thu Jul 16 14:21:26 2015 -0500 Adding letter commit 7f77979efd17f277b4be695c559c1383d2fc2f27 Author: Dan Farrell Date: Thu Jul 16 14:21:24 2015 -0500 Adding letter commit f2458bea7780bf09fe643095dbae95cf97357ccc Author: Dan Farrell Date: Thu Jul 16 14:21:19 2015 -0500 Adding letter commit 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Author: Dan Farrell Date: Thu Jul 16 14:20:52 2015 -0500 Adding letter commit 6e59e7650314112fb80097d7d3803c964b3656f0 Author: Dan Farrell Date: Thu Jul 16 14:20:33 2015 -0500 Initial Letter $ git checkout 6e59e7650314112fb80097d7d3803c964b3656f $ git checkout 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Note: checking out '7126e6dcb9c28ac60cb86ae40fb358350d0c5fad'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_name HEAD is now at 7126e6d... Adding letter $ git checkout -b B 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad Switched to a new branch 'B' $ git pull 790eade367b0d8ab8146596cd717c25fd895302a fatal: '790eade367b0d8ab8146596cd717c25fd895302a' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. $ git merge 7f77979efd17f277b4be695c559c1383d2fc2f27 Updating 7126e6d..7f77979 Fast-forward letter | 2 ++ 1 file changed, 2 insertions(+) $ cat letter a b c d
I added this for an answer to another question and seemed relevant. Hopefully might help someone that needs to change the value of the keys in an array. Uses built-in functions for php.
$inputArray = array('app_test' => 'test', 'app_two' => 'two');
/**
* Used to remap keys of an array by removing the prefix passed in
*
* Example:
* $inputArray = array('app_test' => 'test', 'app_two' => 'two');
* $keys = array_keys($inputArray);
* array_walk($keys, 'removePrefix', 'app_');
* $remappedArray = array_combine($keys, $inputArray);
*
* @param $value - key value to replace, should be from array_keys
* @param $omit - unused, needed for prefix call
* @param $prefix - prefix to string replace in keys
*/
function removePrefix(&$value, $omit, $prefix) {
$value = str_replace($prefix, '', $value);
}
// first get all the keys to remap
$keys = array_keys($inputArray);
// perform internal iteration with prefix passed into walk function for dynamic replace of key
array_walk($keys, 'removePrefix', 'app_');
// combine the rewritten keys and overwrite the originals
$remappedArray = array_combine($keys, $inputArray);
// see full output of comparison
var_dump($inputArray);
var_dump($remappedArray);
Output:
array(2) {
'attr_test' =>
string(4) "test"
'attr_two' =>
string(3) "two"
}
array(2) {
'test' =>
string(4) "test"
'two' =>
string(3) "two"
}
I see this hasn't been answered as final.
I see you have max-width as 100% and width as 600. Flip those.
A simple way also is:
<img src="image.png" style="max-width:600px;width:100%">
I use this often, and then you can control individual images as well, and not have it on all img tags. You could CSS it also like below.
.image600{
width:100%;
max-width:600px;
}
<img src="image.png" class="image600">
Ok, I think I got it.
The client is the docker
command installed into OS X.
The host is the Boot2Docker VM.
The daemon is a background service running inside Boot2Docker.
This variable tells the client how to connect to the daemon.
When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST
set, so that's why docker
commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.
Failing to set it gives a message like this:
$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create:
dial unix /var/run/docker.sock: no such file or directory
One way to fix that would be to simply do this:
$ export DOCKER_HOST=tcp://192.168.59.103:2375
But, as pointed out by others, it's better to do this:
$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]
To spell out this possibly non-intuitive Bash command, running boot2docker shellinit
returns a set of Bash commands that set environment variables:
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
Hence running $(boot2docker shellinit)
generates those commands, and then runs them.
In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.
As an example of the Output Clause during inserts: SQL Server list of insert identities
DECLARE @InsertedIDs table(ID int);
INSERT INTO YourTable
OUTPUT INSERTED.ID
INTO @InsertedIDs
SELECT ...
HTH
For removing the particular object from arrayList there are two ways. Call the function of arrayList.
arrayList.remove(object);
This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.
arrayList.remove(index);
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
There's lots of FTP sites you can get into with the 'anonymous' account and download, but a 'public' site that allows anonymous uploads would be utterly swamped with pr0n and warez in short order.
It's easy enough to set up your own FTP server for testing uploads. There's plenty of them for most any desktop OS. There's one built into IIS, for instance.
While you declare the model at the top of the view using code like this:
@model MyModel
you need to capitalise your references to it below, for example:
@Html.Encode(Model.MyDisplayValue)
I believe a missing web.config in the Views folder would be the major cause of this, but if that is fixed and the problem still persists, check that you are using Model, not model to refer to it in the source.
This is what I ended up using, as of 2018:
<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">
Under Jenkins it complains like :
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-1.el7_6.x86_64/ doesn’t look like a JDK directory
Reason : Unable to found any Dev Kit for JDK.
Solution:
Please make sure to install openjdk-devel package as well along with your JDK-1.8* version and reexport with : # source ~/.bash_profile
Sounds like you need to add the formatting to the WHERE
:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()
Also, if you want case-insensitive comparison, in recent versions of Java the String
class contains a public static final
field called CASE_INSENSITIVE_ORDER
which is of type Comparator<String>
, as I just recently found out. So, you can get your job done using String.CASE_INSENSITIVE_ORDER
.
I ran into this issue while making REST calls from my app server running in AWS EC2. The following Steps fixed the issue for me.
curl -vs https://your_rest_path will now work!
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
One drawback of using componentDidUpdate
, or componentDidMount
is that they are actually executed before the dom elements are done being drawn, but after they've been passed from React to the browser's DOM.
Say for example if you needed set node.scrollHeight to the rendered node.scrollTop, then React's DOM elements may not be enough. You need to wait until the elements are done being painted to get their height.
Solution:
Use requestAnimationFrame
to ensure that your code is run after the painting of your newly rendered object
scrollElement: function() {
// Store a 'this' ref, and
var _this = this;
// wait for a paint before running scrollHeight dependent code.
window.requestAnimationFrame(function() {
var node = _this.getDOMNode();
if (node !== undefined) {
node.scrollTop = node.scrollHeight;
}
});
},
componentDidMount: function() {
this.scrollElement();
},
// and or
componentDidUpdate: function() {
this.scrollElement();
},
// and or
render: function() {
this.scrollElement()
return [...]
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
You just need to manually set the desired permissions with chmod()
:
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
// Set perms with chmod()
chmod($file, 0777);
return true;
}
The below snippet works fine for me(I used the size())
String itemId;
for (int i = 0; i < itemList.size(); i++) {
JSONObject itemObj = (JSONObject)itemList.get(i);
itemId=(String) itemObj.get("ItemId");
System.out.println(itemId);
}
If it is wrong to use use size() kindly advise
VB.net 4.0 framework Code :
Threading.Thread.Sleep(5000)
The integer is in miliseconds ( 1 sec = 1000 miliseconds)
I did test it and it works
You can change the port while you open your XAMP control panel, follow the steps:
httpd.conf
, a text file will openlisten:80
,listen:80
replace with listen:8080
andOnce done that, you will be able to start your local server.
For completely transparent color, use:
rbga(255,255,255,0)
A little more visible:
rbga(255,255,255,.3)
Mid(strYourString, 4)
(i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.
Not sure why you aren't able to set it. In the source, PUBLIC_URL
takes precedence over homepage
const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
You can try setting breakpoints in their code to see what logic is overriding your environment variable.
Anyone who is looking to do this in Ubuntu/linux using php -
Ubuntu comes with libre office installed default. Anyone can use the shell command to use the headless libre office for this.
shell_exec('/usr/bin/libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /var/www/html/demo/public_html/src/var/output /var/www/html/demo/public_html/src/var/source/sample.doc');
Hope it helps others like me.
I've faced the same issue and want to share how I solved it and why.
As you mentioned there are two problems. The first:
In Asp.Net Core how do I register these services and resolve it at runtime based on some key?
So what options do we have? Folks suggest two:
Use a custom factory (like _myFactory.GetServiceByKey(key)
)
Use another DI engine (like _unityContainer.Resolve<IService>(key)
)
Is the Factory pattern the only option here?
In fact both options are factories because each IoC Container is also a factory (highly configurable and complicated though). And it seems to me that other options are also variations of the Factory pattern.
So what option is better then? Here I agree with @Sock who suggested using custom factory, and that is why.
First, I always try to avoid adding new dependencies when they are not really needed. So I agree with you in this point. Moreover, using two DI frameworks is worse than creating custom factory abstraction. In the second case you have to add new package dependency (like Unity) but depending on a new factory interface is less evil here. The main idea of ASP.NET Core DI, I believe, is simplicity. It maintains a minimal set of features following KISS principle. If you need some extra feature then DIY or use a corresponding Plungin that implements desired feature (Open Closed Principle).
Secondly, often we need to inject many named dependencies for single service. In case of Unity you may have to specify names for constructor parameters (using InjectionConstructor
). This registration uses reflection and some smart logic to guess arguments for the constructor. This also may lead to runtime errors if registration does not match the constructor arguments. From the other hand, when using your own factory you have full control of how to provide the constructor parameters. It's more readable and it's resolved at compile-time. KISS principle again.
The second problem:
How can _serviceProvider.GetService() inject appropriate connection string?
First, I agree with you that depending on new things like IOptions
(and therefore on package Microsoft.Extensions.Options.ConfigurationExtensions
) is not a good idea. I've seen some discussing about IOptions
where there were different opinions about its benifit. Again, I try to avoid adding new dependencies when they are not really needed. Is it really needed? I think no. Otherwise each implementation would have to depend on it without any clear need coming from that implementation (for me it looks like violation of ISP, where I agree with you too). This is also true about depending on the factory but in this case it can be avoided.
The ASP.NET Core DI provides a very nice overload for that purpose:
var mongoConnection = //...
var efConnection = //...
var otherConnection = //...
services.AddTransient<IMyFactory>(
s => new MyFactoryImpl(
mongoConnection, efConnection, otherConnection,
s.GetService<ISomeDependency1>(), s.GetService<ISomeDependency2>())));
$files = glob('uploads/*');
$count = 0;
$totalCount = 0;
$subFileCount = 0;
foreach ($files as $file)
{
global $count, $totalCount;
if(is_dir($file))
{
$totalCount += getFileCount($file);
}
if(is_file($file))
{
$count++;
}
}
function getFileCount($dir)
{
global $subFileCount;
if(is_dir($dir))
{
$subfiles = glob($dir.'/*');
if(count($subfiles))
{
foreach ($subfiles as $file)
{
getFileCount($file);
}
}
}
if(is_file($dir))
{
$subFileCount++;
}
return $subFileCount;
}
$totalFilesCount = $count + $totalCount;
echo 'Total Files Count ' . $totalFilesCount;
Use listagg_clob function created like this:
create or replace package list_const_p
is
list_sep varchar2(10) := ',';
end list_const_p;
/
sho err
create type listagg_clob_t as object(
v_liststring varchar2(32767),
v_clob clob,
v_templob number,
static function ODCIAggregateInitialize(
sctx IN OUT listagg_clob_t
) return number,
member function ODCIAggregateIterate(
self IN OUT listagg_clob_t, value IN varchar2
) return number,
member function ODCIAggregateTerminate(
self IN OUT listagg_clob_t, returnValue OUT clob, flags IN number
) return number,
member function ODCIAggregateMerge(
self IN OUT listagg_clob_t, ctx2 IN OUT listagg_clob_t
) return number
);
/
sho err
create or replace type body listagg_clob_t is
static function ODCIAggregateInitialize(sctx IN OUT listagg_clob_t)
return number is
begin
sctx := listagg_clob_t('', '', 0);
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(
self IN OUT listagg_clob_t,
value IN varchar2
) return number is
begin
if nvl(lengthb(v_liststring),0) + nvl(lengthb(value),0) <= 4000 then
self.v_liststring:=self.v_liststring || value || list_const_p.list_sep;
else
if self.v_templob = 0 then
dbms_lob.createtemporary(self.v_clob, true, dbms_lob.call);
self.v_templob := 1;
end if;
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), v_liststring);
self.v_liststring := value || list_const_p.list_sep;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(
self IN OUT listagg_clob_t,
returnValue OUT clob,
flags IN number
) return number is
begin
if self.v_templob != 0 then
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), self.v_liststring);
dbms_lob.trim(self.v_clob, dbms_lob.getlength(self.v_clob) - 1);
else
self.v_clob := substr(self.v_liststring, 1, length(self.v_liststring) - 1);
end if;
returnValue := self.v_clob;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT listagg_clob_t, ctx2 IN OUT listagg_clob_t) return number is
begin
if ctx2.v_templob != 0 then
if self.v_templob != 0 then
dbms_lob.append(self.v_clob, ctx2.v_clob);
dbms_lob.freetemporary(ctx2.v_clob);
ctx2.v_templob := 0;
else
self.v_clob := ctx2.v_clob;
self.v_templob := 1;
ctx2.v_clob := '';
ctx2.v_templob := 0;
end if;
end if;
if nvl(lengthb(self.v_liststring),0) + nvl(lengthb(ctx2.v_liststring),0) <= 4000 then
self.v_liststring := self.v_liststring || ctx2.v_liststring;
ctx2.v_liststring := '';
else
if self.v_templob = 0 then
dbms_lob.createtemporary(self.v_clob, true, dbms_lob.call);
self.v_templob := 1;
end if;
dbms_lob.writeappend(self.v_clob, length(self.v_liststring), self.v_liststring);
dbms_lob.writeappend(self.v_clob, length(ctx2.v_liststring), ctx2.v_liststring);
self.v_liststring := '';
ctx2.v_liststring := '';
end if;
return ODCIConst.Success;
end;
end;
/
sho err
CREATE or replace FUNCTION listagg_clob (input varchar2) RETURN clob
PARALLEL_ENABLE AGGREGATE USING listagg_clob_t;
/
sho err
Well System.Reflection.MethodBase.GetCurrentMethod().Name
is not a very good choice 'cause it will just display the method name without additional information.
Like for string MyMethod(string str)
the above property will return just MyMethod
which is hardly adequate.
It is better to use System.Reflection.MethodBase.GetCurrentMethod().ToString()
which will return the entire method signature...
Allocate maximum memory to your docker machine from (docker preference -> advance )
Screenshot of advance settings:
This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.
docker run -m=4g {imageID}
Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
A simple tweak to Paresh's solution:
Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
As Martin K suggested java.util.concurrent.CountDownLatch
seems to be a better solution for this. Just adding an example for the same
public class CountDownLatchDemo
{
public static void main (String[] args)
{
int noOfThreads = 5;
// Declare the count down latch based on the number of threads you need
// to wait on
final CountDownLatch executionCompleted = new CountDownLatch(noOfThreads);
for (int i = 0; i < noOfThreads; i++)
{
new Thread()
{
@Override
public void run ()
{
System.out.println("I am executed by :" + Thread.currentThread().getName());
try
{
// Dummy sleep
Thread.sleep(3000);
// One thread has completed its job
executionCompleted.countDown();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
try
{
// Wait till the count down latch opens.In the given case till five
// times countDown method is invoked
executionCompleted.await();
System.out.println("All over");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
If you put the username and password at clientside into the request this way:
URL url = new URL("http://localhost:8080/myapplication?wsdl");
MyWebService webservice = new MyWebServiceImplService(url).getMyWebServiceImplPort();
Map<String, Object> requestContext = ((BindingProvider) webservice).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
and call your webservice
String response = webservice.someMethodAtMyWebservice("test");
Then you can read the Basic Authentication string like this at the server side (you have to add some checks and do some exceptionhandling):
@Resource
WebServiceContext webserviceContext;
public void someMethodAtMyWebservice(String parameter) {
MessageContext messageContext = webserviceContext.getMessageContext();
Map<String, ?> httpRequestHeaders = (Map<String, ?>) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
List<?> authorizationList = (List<?>) httpRequestHeaders.get("Authorization");
if (authorizationList != null && !authorizationList.isEmpty()) {
String basicString = (String) authorizationList.get(0);
String encodedBasicString = basicString.substring("Basic ".length());
String decoded = new String(Base64.getDecoder().decode(encodedBasicString), StandardCharsets.UTF_8);
String[] splitter = decoded.split(":");
String usernameFromBasicAuth = splitter[0];
String passwordFromBasicAuth = splitter[1];
}
Your code as it stands is correct but I am having a hard time figuring out how it could/would be used in a real world scenario. With that said, please be aware of a few caveats when returning pointers from functions:
int arr[5];
, it's allocated on the stack and is local to the function.arr
to test()
.std::unique_ptr
/std::shared_ptr<>
.Edit - to answer the use-case of matrix multiplication
You have two options. The naive way is to use std::unique_ptr
/std::shared_ptr<>
. The Modern C++ way is to have a Matrix
class where you overload operator *
and you absolutely must use the new rvalue references
if you want to avoid copying the result of the multiplication to get it out of the function. In addition to having your copy constructor
, operator =
and destructor
, you also need to have move constructor
and move assignment operator
. Go through the questions and answers of this search to gain more insight on how to achieve this.
Edit 2 - answer to appended question
int* test (int a[5], int b[5]) {
int *c = new int[5];
for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
return c;
}
If you are using this as int *res = test(a,b);
, then sometime later in your code, you should call delete []res
to free the memory allocated in the test()
function. You see now the problem is it is extremely hard to manually keep track of when to make the call to delete
. Hence the approaches on how to deal with it where outlined in the answer.
htdocs
is your default document-root directory, so you have to use localhost/index.html
to see that html file. In other words, localhost
is mapped to xampp/htdocs
, so index.html
is at localhost
itself. You can change the location of document root by modifying httpd.conf
and restarting the server.
You have to read
database column
here. You could have a look on following code snippet
string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
{
SqlDataReader sqlDataReader = command.ExecuteReader();
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
}
}
sqlDataReader.Close();
}
_connection.Close();
Once an instance has been started, there is no way to change the keypair associated with the instance at a meta data level, but you can change what ssh key you use to connect to the instance.
stackoverflow.com/questions/7881469/change-key-pair-for-ec2-instance
About the progressbar
control in a userform, it won't show any progress if you don't use the repaint
event. You have to code this event inside the looping (and obviously increment the progressbar
value).
Example of use:
userFormName.repaint
If this issue occurs, kindly check web.config in below section
Below section gives the version of particular dll used
after checking this section in web.config, open solution explorer and select reference from the project tree as shown . Solution Explorer->Reference
After expanding reference, find the dll which caused the error. Right click on the dll reference and check for version like shown in the image above.
If both config dll version and referenced dll is different you would get this exception. Make sure both are of same version which would help.
A linebreak in regex is \n, so your script would be
var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));
In my legacy app Array.from of prototype js was conflicting with angular's Array.from that was causing this problem. I resolved it by saving angular's Array.from version and reassigning it after prototype load.
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
I struggled with this for a few hours today because all of these answers are kind of out of date now what with MDC and the new theming capabilities I just could not see how to override app:titleTextColor
app wide as a style.
The answer is that titleTextColor
is available in the styles.xml is you are overriding something that inherits from Widget.AppCompat.Toolbar
. Today I think the best choice is supposed to be Widget.MaterialComponents.Toolbar
:
<style name="Widget.LL.Toolbar" parent="@style/Widget.MaterialComponents.Toolbar">
<item name="titleTextAppearance">@style/TextAppearance.LL.Toolbar</item>
<item name="titleTextColor">@color/white</item>
<item name="android:background">?attr/colorSecondary</item>
</style>
<style name="TextAppearance.LL.Toolbar" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textStyle">bold</item>
</style>
And in your app theme, specify the toolbarStyle:
<item name="toolbarStyle">@style/Widget.LL.Toolbar</item>
Now you can leave the xml where you specify the tool bar unchanged. For a long time I thought changing the android:textColor
in the toolbar title text appearance should be working, but for some reason it does not.
To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:
SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)
Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1 Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by @yeoman and @betlista
@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion
@betlista I would recomment to not to have build.xml in src folder
Experimentally, I've discovered that you can provide:
<b>…</b>
for boldface,<i>…</i>
for italics,<u>…</u>
for underline,<br />
to enforce a single line break,http://google.com
; this appears as a hyperlink.<a>
tag for a custom description does not work and breaks the formatting.)→
(→), ™
(™) and ®
(®); consult this W3 reference for the exhaustive list.• 
yields "• ").Special notes concerning only Google Play app:
<blockquote>…</blockquote>
to indent a paragraph of text,<small>…</small>
for slightly smaller text,<big>…</big>
for slightly larger text,<sup>…</sup>
and <sub>…</sub>
for super- and subscripts.<font color="#a32345">…</font>
for setting font colors in HEX code.Special notes concerning only Google Play website:
Since Jackson 2.0 you can use JsonInclude
@JsonInclude(Include.NON_NULL)
public class Shop {
//...
}
I hope it also useful
window.addEventListener("load", function()
{
if(!window.pageYOffset)
{
hideAddressBar();
}
window.addEventListener("orientationchange", hideAddressBar);
});
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html
file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = '<a href="' + url + '" target="_blank">Process</a>';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs
script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
You can use the Boolean constants - Boolean.TRUE
and Boolean.FALSE
instead of 0
and 1
. You can create your variable as of type boolean
if primitive is what you are after. This way you won't have to create new Boolean
objects.
1: I have downloaded the mysql-connector-java-5.1.24-bin.jar
Okay.
2: I have created a lib folder in my project and put the jar in there.
Wrong. You need to drop JAR in /WEB-INF/lib
folder. You don't need to create any additional folders.
3: properties of project->build path->add JAR and selected the JAR above.
Unnecessary. Undo it all to avoid possible conflicts.
4: I still get java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/mysql
This exception can have 2 causes:
JDBC URL is not recognized by any of the loaded JDBC drivers. Indeed, the JDBC URL is wrong, there should as per the MySQL JDBC driver documentation be another colon between the scheme and the host.
jdbc:mysql://localhost:3306/mysql