It has to do with the order in which bytes are stored in memory. The decimal number 5001
is 0x1389
in hexadecimal, so the bytes involved are 0x13
and 0x89
. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001
will be stored as
0x89 0x13
The htons()
function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order
0x13 0x89
On a little-endian machine, the number with the swapped bytes is 0x8913
in hexadecimal, which is 35091
in decimal notation. Note that if you were working on a big-endian machine, the htons()
function would not need to do any swapping since the number would already be stored in the right way in memory.
The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.
Have you installed it using sudo? Was the error in my case.
Try this:
// this will fix old browsers
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return i;
}
}
return -1;
}
}
// example
if ([1, 2, 3].indexOf(2) != -1) {
// yay!
}
I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow
.border {_x000D_
background-color: #ededed;_x000D_
padding: 10px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
.border-top {_x000D_
box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-right {_x000D_
box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-bottom {_x000D_
box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-left {_x000D_
box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
}
_x000D_
<div class="border border-top">border-top</div>_x000D_
<div class="border border-right">border-right</div>_x000D_
<div class="border border-bottom">border-bottom</div>_x000D_
<div class="border border-left">border-left</div>
_x000D_
EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.
Syntax error, remove the ( )
from select
.
insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
this answer is based on Shamil Yakupov answer, with real object instead of string.
using System.Dynamic;
dynamic response = new ExpandoObject();
response.message = "Email address already exist";
return Content<object>(HttpStatusCode.BadRequest, response);
An absolutely positioned element is actually positioned regarding a relative
parent, or the nearest found relative parent. So the element with overflow: hidden
should be between relative
and absolute
positioned elements:
<div class="relative-parent">
<div class="hiding-parent">
<div class="child"></div>
</div>
</div>
.relative-parent {
position:relative;
}
.hiding-parent {
overflow:hidden;
}
.child {
position:absolute;
}
For Windows you can use
(if exist node_modules rmdir node_modules /q /s) && npm install
which removes node_modules
directory and performs npm install
then. Removal before install assures that all packages are reinstalled.
There are two solutions for this are :-
(1) do not put onClick in xml
(2) remove
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
and put
public void setLogin(View v) {
// Your code here
}
The limit of the enhanced format notifications is documented here.
It explicitly states:
The payload must not exceed 256 bytes and must not be null-terminated.
ascandroli claims above that they were able to send messages with 1400 characters. My own testing with the new notification format showed that a message just 1 byte over the 256 byte limit was rejected. Given that the docs are very explicit on this point I suggest it is safer to use 256 regardless of what you may be able to achieve experimentally as there is no guarantee Apple won't change it to 256 in the future.
As for the alert text itself, if you can fit it in the 256 total payload size then it will be displayed by iOS. They truncate the message that shows up on the status bar, but if you open the notification center, the entire message is there. It even renders newline characters \n
.
print all folders name where batch script file is kept
for /d %%d in (*.*) do (
set test=%%d
echo !test!
)
pause
Add one more condition in where clause
SELECT * FROM product
WHERE pdate >= DATEADD(day,-30,GETDATE())
and pdate <= getdate()
Or use DateDiff
SELECT * FROM product
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30
Regular Expressions are compiled before being used when using the second version. If you are going to executing it many times it is definatly better to compile it first. If not compiling every time you match for one off's is fine.
Honestly, I have difficulty implementing it because there's barely any tutorials I've searched that displays writing the keys into the files. The accepted answer was "fine". But for me I had to improve it so that both keys gets saved into two separate files. I've written a helper class so y'all just gotta copy and paste it. Hope this helps lol.
using Microsoft.Win32;
using System;
using System.IO;
using System.Security.Cryptography;
namespace RsaCryptoExample
{
class RSAFileHelper
{
readonly string pubKeyPath = "public.key";//change as needed
readonly string priKeyPath = "private.key";//change as needed
public void MakeKey()
{
//lets take a new CSP with a new 2048 bit rsa key pair
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
//how to get the private key
RSAParameters privKey = csp.ExportParameters(true);
//and the public key ...
RSAParameters pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
File.WriteAllText(pubKeyPath, pubKeyString);
}
string privKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, privKey);
//get the string from the stream
privKeyString = sw.ToString();
File.WriteAllText(priKeyPath, privKeyString);
}
}
public void EncryptFile(string filePath)
{
//converting the public key into a string representation
string pubKeyString;
{
using (StreamReader reader = new StreamReader(pubKeyPath)){pubKeyString = reader.ReadToEnd();}
}
//get a stream from the string
var sr = new StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters((RSAParameters)xs.Deserialize(sr));
byte[] bytesPlainTextData = File.ReadAllBytes(filePath);
//apply pkcs#1.5 padding and encrypt our data
var bytesCipherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
string encryptedText = Convert.ToBase64String(bytesCipherText);
File.WriteAllText(filePath,encryptedText);
}
public void DecryptFile(string filePath)
{
//we want to decrypt, therefore we need a csp and load our private key
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
string privKeyString;
{
privKeyString = File.ReadAllText(priKeyPath);
//get a stream from the string
var sr = new StringReader(privKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSAParameters privKey = (RSAParameters)xs.Deserialize(sr);
csp.ImportParameters(privKey);
}
string encryptedText;
using (StreamReader reader = new StreamReader(filePath)) { encryptedText = reader.ReadToEnd(); }
byte[] bytesCipherText = Convert.FromBase64String(encryptedText);
//decrypt and strip pkcs#1.5 padding
byte[] bytesPlainTextData = csp.Decrypt(bytesCipherText, false);
//get our original plainText back...
File.WriteAllBytes(filePath, bytesPlainTextData);
}
}
}
in light of the ambiguity as to the number of non-user databases, you should probably add:
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
and add the names of the reporting services databases
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
Rails-specific
In case someone only needs to call to_s
method to each of the values and is not using Rails 4.2 ( which includes transform_values
method link), you can do the following:
original_hash = { :a => 'a', :b => BigDecimal('23.4') }
#=> {:a=>"a", :b=>#<BigDecimal:5c03a00,'0.234E2',18(18)>}
JSON(original_hash.to_json)
#=> {"a"=>"a", "b"=>"23.4"}
Note: The use of 'json' library is required.
Note 2: This will turn keys into strings as well
Include Client Statistics by pressing Ctrl+Alt+S. Then you will have all execution information in the statistics tab below.
Just enable parsing of the autoexec.bat in the registry, using these instructions.
:: works only on windows vista and earlier
Run REGEDT32.EXE.
Modify the following value within HKEY_CURRENT_USER:
Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec
1 = autoexec.bat is parsed
0 = autoexec.bat is not parsed
This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:
import sys
print sys.path
What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH
environment variable. If you use bash
, here's how:
~/.bashrc
export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH
where /path/to/PyQt5/directory
is the path to the folder where the PyQt5 library is located.
You are trying to solve the wrong problem.
Solution 1: Each time you put dirty socks in your laundry basket, tie them in a little knot. That way you will not have to do any sorting after the washing. Think of it like registering an index in a Mongo database. A little work ahead for some CPU savings in the future.
Solution 2: If it's winter, you don't have to wear matching socks. We are programmers. Nobody needs to know, as long as it works.
Solution 3: Spread the work. You want to perform such a complex CPU process asynchronously, without blocking the UI. Take that pile of socks and stuff them in a bag. Only look for a pair when you need it. That way the amount of work it takes is much less noticeable.
Hope this helps!
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
Solved jQuery: Add element after another element
<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>
OR
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>
Download the SDK from here: http://developer.android.com/sdk/ to C:\android-sdk\.
Then when you launch Android Studio again, it will prompt you for the SDK path just point it to: C:\android-sdk\.
Update: new download location, https://developer.android.com/studio/#command-tools
You could change your for loop declaration to make the code shorter:
char* reverse_string(char *str)
{
char temp;
size_t len = strlen(str) - 1;
size_t stop = len/2;
size_t i,k;
for(i = 0, k = len; i < stop; i++, k--)
{
temp = str[k];
str[k] = str[i];
str[i] = temp;
}
return str;
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Source W3schools
Use this line of code when scanning the second value:
scanf(" %lf", &b);
also replace all %ld with %lf.
It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
import sys
sys.argv[1:]
will give you a list of arguments (not including the name of the python file)
In your specific case you can use the following bash
command (bash
is the default shell on macOS):
for f in *.png; do echo mv "$f" "${f/_*_/_}"; done
Note: If there's a chance that your filenames start with -
, place --
before them[1]:
mv -- "$f" "${f/_*_/_}"
Note: echo
is prepended to mv
so as to perform a dry run. Remove it to perform actual renaming.
You can run it from the command line or use it in a script.
"${f/_*_/_}"
is an application of bash
parameter expansion: the (first) substring matching pattern _*_
is replaced with literal _
, effectively cutting the middle token from the name._*_
is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash
and search for Pattern Matching
).If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename
utility.
On macOS you can install it using popular package manager Homebrew as follows:
brew install rename
Here's the equivalent of the command at the top using rename
:
rename -n -e 's/_.*_/_/' *.png
Again, this command performs a dry run; remove -n
to perform actual renaming.
bash
solution, s/.../.../
performs text substitution, but - unlike in bash
- true regular expressions are used.[1] The purpose of special argument --
, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -
, as Jacob C. notes.
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
For those of you who are popping up a new window to print from, and then automatically closing it after the user clicks "Print" or "Cancel" on the Chrome print preview, I used the following (thanks to the help from PaulVB's answer):
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var showPopup = false;
window.onbeforeunload = function () {
if (showPopup) {
return 'You must use the Cancel button to close the Print Preview window.\n';
} else {
showPopup = true;
}
}
window.print();
window.close();
} else {
window.print();
window.close();
}
I am debating if it would be a good idea to also filter by the version of Chrome...
(Excel 2003 or earlier) Choose Edit | Paste Special | Multiply
(Excel 2007 or later) Click on the Paste down arrow | Paste Special | Multiply
You can also do this:
static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
if(alist==null || alist.isEmpty())
{
return null;
}
ArrayList<String> rlist = new ArrayList<>(alist);
Collections.reverse(rlist);
return rlist;
}
For Android Studio below 4.1:
From the Top menu Click File and then click Export to Zip File
For Android Studio 4.1 and above:
From the Top menu click File > Manage IDE Settings > Export to Zip File ()
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
CONVERT(column1 USING utf8)
Solves my problem. Where column1 is the column which gives me this error.
If you want to have transparent background and android:outlineProvider="bounds"
doesn't work for you, you can create custom ViewOutlineProvider:
class TransparentOutlineProvider extends ViewOutlineProvider {
@Override
public void getOutline(View view, Outline outline) {
ViewOutlineProvider.BACKGROUND.getOutline(view, outline);
Drawable background = view.getBackground();
float outlineAlpha = background == null ? 0f : background.getAlpha()/255f;
outline.setAlpha(outlineAlpha);
}
}
And set this provider to your transparent view:
transparentView.setOutlineProvider(new TransparentOutlineProvider());
Sources: https://code.google.com/p/android/issues/detail?id=78248#c13
[EDIT] Documentation of Drawable.getAlpha() says that it is specific to how the Drawable threats the alpha. It is possible that it will always return 255. In this case you can provide the alpha manually:
class TransparentOutlineProvider extends ViewOutlineProvider {
private float mAlpha;
public TransparentOutlineProvider(float alpha) {
mAlpha = alpha;
}
@Override
public void getOutline(View view, Outline outline) {
ViewOutlineProvider.BACKGROUND.getOutline(view, outline);
outline.setAlpha(mAlpha);
}
}
If your view background is a StateListDrawable with default color #DDFF0000 that is with alpha DDx0/FFx0 == 0.86
transparentView.setOutlineProvider(new TransparentOutlineProvider(0.86f));
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true
, which is true (a || b
is true if either a
or b
is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
For the code above... //*[contains(@prop,'foo')]
You can use it without casting such as:
select sum(`stuff`) as mySum from test;
Or cast it to decimal:
select sum(cast(`stuff` as decimal(4,2))) as mySum from test;
EDIT
For SQL Server, you can use:
select sum(cast(stuff as decimal(5,2))) as mySum from test;
Just to add my answer, it seems that the transitions need to be based on initial values and final values within the css properties to be able to manage the animation.
Those reworked css classes should provide the expected result :
.box{_x000D_
position: relative; _x000D_
top:0px;_x000D_
left:0px;_x000D_
width:0px;_x000D_
}_x000D_
_x000D_
.box:hover .hidden{_x000D_
opacity: 1;_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.box .hidden{ _x000D_
background: yellow;_x000D_
height: 300px; _x000D_
position: absolute; _x000D_
top: 0px;_x000D_
left: 0px; _x000D_
width: 0px;_x000D_
opacity: 0; _x000D_
transition: all 1s ease;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
<a href="#">_x000D_
<img src="http://farm9.staticflickr.com/8207/8275533487_5ebe5826ee.jpg"></a>_x000D_
<div class="hidden"></div>_x000D_
_x000D_
</div>
_x000D_
You can also specify <error-page>
for exceptions using <exception-type>
, eg below:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errorpages/exception.html</location>
</error-page>
Or map a error code using <error-code>
:
<error-page>
<error-code>404</error-code>
<location>/errorpages/404error.html</location>
</error-page>
Here is one way that I hope is easy to understand:
$(document).ready(function() {
$("#chkdwn2").click(function() {
if ($(this).is(":checked")) {
$("#dropdown").prop("disabled", true);
} else {
$("#dropdown").prop("disabled", false);
}
});
});
The primary purpose of AF_INET was to allow for other possible network protocols or address families (AF is for address family; PF_INET is for the (IPv4) internet protocol family). For example, there probably are a few Netware SPX/IPX networks around still; there were other network systems like DECNet, StarLAN and SNA, not to mention the ill-begotten ISO OSI (Open Systems Interconnection), and these did not necessarily use the now ubiquitous IP address to identify the peer host in network connections.
The ubiquitous alternative to AF_INET (which, in retrospect, should have been named AF_INET4) is AF_INET6, for the IPv6 address family. IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.
You may see some other values - but they are unusual. It is there to allow for alternatives and future directions. The sockets interface is actually very general indeed - which is one of the reasons it has thrived where other networking interfaces have withered.
Life has (mostly) gotten simpler - be grateful.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
I would not recomend you to use document.write
as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).
Use innerHTML instead
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
I solved this problem with:
inputObj.css('cssText', inputObj.attr('style')+'padding-left: ' + (width + 5) + 'px !IMPORTANT;');
So no inline-Style is lost, an the last overrides the first
I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:
Changed
=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3)
to
=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3)
You can use inbuilt library pickle
This library allows you to save any object in python to a file
This library will maintain the format as well
import pickle
with open('/content/list_1.txt', 'wb') as fp:
pickle.dump(list_1, fp)
you can also read the list back as an object using same library
with open ('/content/list_1.txt', 'rb') as fp:
list_1 = pickle.load(fp)
reference : Writing a list to a file with Python
MS SQL Studio take care of when you delete the column but if you need to Delete Constraint Programmatically here is simple solution
Here’s a code snippet that’ll drop a column with a default constraint:
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND name='__ColumnName__')
EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')
Just replace TableName and ColumnName with the appropriate values. You can safely run this even if the column has already been dropped.
Bonus: Here’s the code to drop foreign keys and other types of constraints.
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__')
BEGIN
SELECT @ConstraintName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__'
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
END
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
Try max(): http://php.net/manual/en/function.max.php See the first comment on that page
In the windows when we open jupyter notebook in command prompt we can see the instructions in first 10 lines in that there is one instruction- "to open notebook, open this file in browser file://C:/Users/{username}/appdata/roaming/jupyetr/runtime/nbserver-xywz-open.html " , open this html with browser of your choice.
It could be due to below reasons: -
Either you dont have INTERNET permission in manifest file. If so then please use this statement <uses-permission android:name="android.permission.INTERNET" />
Or you are connected to a network but your internet connection is not working. Like you are connected to a Wi-Fi but it doesnt have internet connection or Mobile data on your phone is ON but you dont have data connectivity on your phone.
Point# 2 is interesting and its not assumption, I have tested the same at my end.
Hope this will help you
Summved
You can try to add some time.sleep
calls to your code.
It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.
In order to avoid your code from crashing, try to catch this error with try .. except
around the urllib2 calls.
Here's a tiny, complete Code Snippet that combines all the answers. Press: "Run Code Snippet" then press "Full Page" and resize the window to see it in action:
function refresh(referenceWidth, referenceHeight, drawFunction) {
const myCanvas = document.getElementById("myCanvas");
myCanvas.width = myCanvas.clientWidth;
myCanvas.height = myCanvas.clientHeight;
const ratio = Math.min(
myCanvas.width / referenceWidth,
myCanvas.height / referenceHeight
);
const ctx = myCanvas.getContext("2d");
ctx.scale(ratio, ratio);
drawFunction(ctx, ratio);
window.requestAnimationFrame(() => {
refresh(referenceWidth, referenceHeight, drawFunction);
});
}
//100, 100 is the "reference" size. Choose whatever you want.
refresh(100, 100, (ctx, ratio) => {
//Custom drawing code! Draw whatever you want here.
const referenceLineWidth = 1;
ctx.lineWidth = referenceLineWidth / ratio;
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.arc(50, 50, 49, 0, 2 * Math.PI);
ctx.stroke();
});
_x000D_
div {
width: 90vw;
height: 90vh;
}
canvas {
width: 100%;
height: 100%;
object-fit: contain;
}
_x000D_
<div>
<canvas id="myCanvas"></canvas>
</div>
_x000D_
This snippet uses canvas.clientWidth and canvas.clientHeight rather than window.innerWidth and window.innerHeight to make the snippet run inside a complex layout correctly. However, it works for full window too if you just put it in a div that uses full window. It's more flexible this way.
The snippet uses the newish window.requestAnimationFrame to repeatedly resize the canvas every frame. If you can't use this, use setTimeout instead. Also, this is inefficient. To make it more efficient, store the clientWidth and clientHeight and only recalculate and redraw when clientWidth and clientHeight change.
The idea of a "reference" resolution lets you write all of your draw commands using one resolution... and it will automatically adjust to the client size without you having to change the drawing code.
The snippet is self explanatory, but if you prefer it explained in English: https://medium.com/@doomgoober/resizing-canvas-vector-graphics-without-aliasing-7a1f9e684e4d
The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d
- This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.
open
also has an -a flag, that you can use to open up an app from within the Applications folder by it's name (or by bundle identifier with -b flag). You can combine this with the --args option to achieve the result you want:
open -a APP_NAME --args ARGS
To open up a video in VLC player that should scale with a factor 2x and loop you would for example exectute:
open -a VLC --args -L --fullscreen
Note that I could not get the output of the commands to the terminal. (although I didn't try anything to resolve that)
There is one example where in
actually kills your performance.
If you use in
on a O(1) container that only implements __getitem__
and has_key()
but not __contains__
you will turn an O(1) search into an O(N) search (as in
falls back to a linear search via __getitem__
).
Fix is obviously trivial:
def __contains__(self, x):
return self.has_key(x)
With a different example:
Consider this is the string and pattern to be searched for is 'cat':
text = "catmania thiscat thiscatmaina";
Now definitions,
'\b' finds/matches the pattern at the beginning or end of each word.
'\B' does not find/match the pattern at the beginning or end of each word.
Different Cases:
Case 1: At the beginning of each word
result = text.replace(/\bcat/g, "ct");
Now, result is "ctmania thiscat thiscatmaina"
Case 2: At the end of each word
result = text.replace(/cat\b/g, "ct");
Now, result is "catmania thisct thiscatmaina"
Case 3: Not in the beginning
result = text.replace(/\Bcat/g, "ct");
Now, result is "catmania thisct thisctmaina"
Case 4: Not in the end
result = text.replace(/cat\B/g, "ct");
Now, result is "ctmania thiscat thisctmaina"
Case 5: Neither beginning nor end
result = text.replace(/\Bcat\B/g, "ct");
Now, result is "catmania thiscat thisctmaina"
Hope this helps :)
You can set the datatable as a datasource to many elements.
For eg
gridView
repeater
datalist
etc etc
If you need to extract data from each row then you can use
table.rows[rowindex][columnindex]
or
if you know the column name
table.rows[rowindex][columnname]
If you need to iterate the table then you can either use a for loop or a foreach loop like
for ( int i = 0; i < table.rows.length; i ++ )
{
string name = table.rows[i]["columnname"].ToString();
}
foreach ( DataRow dr in table.Rows )
{
string name = dr["columnname"].ToString();
}
Try this:
UPDATE barang
SET ID FROM(SELECT tblkatalog.tblkatalog_id FROM tblkatalog
WHERE tblkatalog.tblkatalog_nomor = barang.NO_CAT) WHERE barang.NO_CAT <>'';
Add bind(this) to your setTimeout callback function
setTimeout(function () {
this.basketAddSuccess = false
}.bind(this), 2000)
The extension is the best option for this problem. Create an extension of View or Button
public extension UIView {
//Round the corners
func roundCorners(){
let radius = bounds.maxX / 16
layer.cornerRadius = radius
}
}
Call it from the code
button.roundCorners()
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
I've solved this issue with the optional parameter count set to -1.
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
Use ifelse
:
frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
...
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
The difference between if
and ifelse
:
if
is a control flow statement, taking a single logical value as an argumentifelse
is a vectorised function, taking vectors as all its arguments.The help page for if
, accessible via ?"if"
will also point you to ?ifelse
You could also do that:
In package.json
:
"scripts": {
"cool": "./cool.js"
}
In cool.js
:
console.log({ myVar: process.env.npm_config_myVar });
In CLI:
npm --myVar=something run-script cool
Should output:
{ myVar: 'something' }
Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_
variables? I'm also using better-npm-run
, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar
, try process.env.npm_config_myvar
This blog post was helpful for me. I used the "Homebrew built Vim" solution, which in my case saved the new version in /usr/local/bin. At this point, the post suggested hiding the system vim, which didn't work for me, so I used an alias instead.
$ brew install vim
$ alias vim='/path/to/new/vim
$ which vim
vim: aliased to /path/to/new/vim
Took me a while to read through the above. This was the answer for me:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=False
)
plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)
Reference this for more arguments: matplotlib.pyplot.legend
Create composer.json file with requisite library for ex:
{
"require": {
"mpdf/mpdf": "^6.1"
}
}
Execute the below command where composer.json exists:
composer install
In case of Drupal :
Use the web root folder of drupal to include autoload for ex:
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/vendor/autoload.php';
In case of other systems: Use the root folder variable or location to include the autoload.php
You can use the built in cache attribute to prevent caching.
For .net Framework: [OutputCache(NoStore = true, Duration = 0)]
For .net Core: [ResponseCache(NoStore = true, Duration = 0)]
Be aware that it is impossible to force the browser to disable caching. The best you can do is provide suggestions that most browsers will honor, usually in the form of headers or meta tags. This decorator attribute will disable server caching and also add this header: Cache-Control: public, no-store, max-age=0
. It does not add meta tags. If desired, those can be added manually in the view.
Additionally, JQuery and other client frameworks will attempt to trick the browser into not using it's cached version of a resource by adding stuff to the url, like a timestamp or GUID. This is effective in making the browser ask for the resource again but doesn't really prevent caching.
On a final note. You should be aware that resources can also be cached in between the server and client. ISP's, proxies, and other network devices also cache resources and they often use internal rules without looking at the actual resource. There isn't much you can do about these. The good news is that they typically cache for shorter time frames, like seconds or minutes.
In my case, I created a new table with the same structure, created the relationships with the other tables, then extracted the data in CSV from the old table that has the problem, then imported the CSV to the new table and disabled foreign key checking and disabled import interruption, all my data are inserted to the new table that has no problem successfully, then deleted the old table.
It worked for me.
Unless you get a better answer from a Scala user (which I'm not), here's my understanding.
It only appears as part of an expression beginning with for
, which states how to generate a new list from an existing list.
Something like:
var doubled = for (n <- original) yield n * 2
So there's one output item for each input (although I believe there's a way of dropping duplicates).
This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.
(If you're familiar with C#, it's closer to LINQ's select
operator than it is to yield return
).
Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.
setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
Based on comment of @alessandro-pezzato.
Run multiples commands by using &
between the commands.
Example:
$ sleep 3 & sleep 5 & sleep 2 &
It's will execute the commands in background.
You can simply use the powerful .loc
method and use one condition or several depending on your need (tested with pandas=1.0.5).
Code Summary:
df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))
df['Color'] = "red"
df.loc[(df['Set']=="Z"), 'Color'] = "green"
#practice!
df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"
Explanation:
df=pd.DataFrame(dict(Type='A B B C'.split(), Set='Z Z X Y'.split()))
# df so far:
Type Set
0 A Z
1 B Z
2 B X
3 C Y
add a 'color' column and set all values to "red"
df['Color'] = "red"
Apply your single condition:
df.loc[(df['Set']=="Z"), 'Color'] = "green"
# df:
Type Set Color
0 A Z green
1 B Z green
2 B X red
3 C Y red
or multiple conditions if you want:
df.loc[(df['Set']=="Z")&(df['Type']=="B")|(df['Type']=="C"), 'Color'] = "purple"
You can read on Pandas logical operators and conditional selection here: Logical operators for boolean indexing in Pandas
I just added class hide to the div before "card-body" and it hidden by default.
<div id="collapseOne" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">
They're generally stored on the server. Where they're stored is up to you as the developer. You can use the session.save_handler
configuration variable and the session_set_save_handler
to control how sessions get saved on the server. The default save method is to save sessions to files. Where they get saved is controlled by the session.save_path
variable.
What you missed here is timezones.
Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.
You need to read the top of the datetime
docs, which explain about timezones and "naive" and "aware" objects.
If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp
instead of fromtimestamp
.
On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0)
instead.
Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.
If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp
method instead of trying to figure out how to do it yourself. And even if you don't, you may want to consider borrowing its source code.
(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)
If the query optimizer is doing its job right, there should be no difference between those queries. They are just two ways to specify the same desired result.
Use COALESCE
to avoid that outcome.
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
MySQL 5.5.32 Schema Setup:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
Query 1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export
using Sql Developer 3.0
See SQL Developer downloads for latest versions
Try in html:
style="display: inline-block; margin-top: 50px;"
or in css:
display: inline-block;
margin-top: 50px;
Here's a lightly more fleshed out update to try to handle some formatting for breaks and lists. I used Amaya's output as a guide.
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Stack;
import java.util.logging.Logger;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class HTML2Text extends HTMLEditorKit.ParserCallback {
private static final Logger log = Logger
.getLogger(Logger.GLOBAL_LOGGER_NAME);
private StringBuffer stringBuffer;
private Stack<IndexType> indentStack;
public static class IndexType {
public String type;
public int counter; // used for ordered lists
public IndexType(String type) {
this.type = type;
counter = 0;
}
}
public HTML2Text() {
stringBuffer = new StringBuffer();
indentStack = new Stack<IndexType>();
}
public static String convert(String html) {
HTML2Text parser = new HTML2Text();
Reader in = new StringReader(html);
try {
// the HTML to convert
parser.parse(in);
} catch (Exception e) {
log.severe(e.getMessage());
} finally {
try {
in.close();
} catch (IOException ioe) {
// this should never happen
}
}
return parser.getText();
}
public void parse(Reader in) throws IOException {
ParserDelegator delegator = new ParserDelegator();
// the third parameter is TRUE to ignore charset directive
delegator.parse(in, this, Boolean.TRUE);
}
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
log.info("StartTag:" + t.toString());
if (t.toString().equals("p")) {
if (stringBuffer.length() > 0
&& !stringBuffer.substring(stringBuffer.length() - 1)
.equals("\n")) {
newLine();
}
newLine();
} else if (t.toString().equals("ol")) {
indentStack.push(new IndexType("ol"));
newLine();
} else if (t.toString().equals("ul")) {
indentStack.push(new IndexType("ul"));
newLine();
} else if (t.toString().equals("li")) {
IndexType parent = indentStack.peek();
if (parent.type.equals("ol")) {
String numberString = "" + (++parent.counter) + ".";
stringBuffer.append(numberString);
for (int i = 0; i < (4 - numberString.length()); i++) {
stringBuffer.append(" ");
}
} else {
stringBuffer.append("* ");
}
indentStack.push(new IndexType("li"));
} else if (t.toString().equals("dl")) {
newLine();
} else if (t.toString().equals("dt")) {
newLine();
} else if (t.toString().equals("dd")) {
indentStack.push(new IndexType("dd"));
newLine();
}
}
private void newLine() {
stringBuffer.append("\n");
for (int i = 0; i < indentStack.size(); i++) {
stringBuffer.append(" ");
}
}
public void handleEndTag(HTML.Tag t, int pos) {
log.info("EndTag:" + t.toString());
if (t.toString().equals("p")) {
newLine();
} else if (t.toString().equals("ol")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("ul")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("li")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("dd")) {
indentStack.pop();
;
}
}
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
log.info("SimpleTag:" + t.toString());
if (t.toString().equals("br")) {
newLine();
}
}
public void handleText(char[] text, int pos) {
log.info("Text:" + new String(text));
stringBuffer.append(text);
}
public String getText() {
return stringBuffer.toString();
}
public static void main(String args[]) {
String html = "<html><body><p>paragraph at start</p>hello<br />What is happening?<p>this is a<br />mutiline paragraph</p><ol> <li>This</li> <li>is</li> <li>an</li> <li>ordered</li> <li>list <p>with</p> <ul> <li>another</li> <li>list <dl> <dt>This</dt> <dt>is</dt> <dd>sdasd</dd> <dd>sdasda</dd> <dd>asda <p>aasdas</p> </dd> <dd>sdada</dd> <dt>fsdfsdfsd</dt> </dl> <dl> <dt>vbcvcvbcvb</dt> <dt>cvbcvbc</dt> <dd>vbcbcvbcvb</dd> <dt>cvbcv</dt> <dt></dt> </dl> <dl> <dt></dt> </dl></li> <li>cool</li> </ul> <p>stuff</p> </li> <li>cool</li></ol><p></p></body></html>";
System.out.println(convert(html));
}
}
If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.
I'm assuming you're using DB2 for z/OS, which unfortunately (for whatever reason, I never really understood why) doesn't support using a values-list where a full-select would be appropriate.
You can use a select like below. It's a little unwieldy, but it works:
INSERT INTO tableName (col1, col2, col3, col4, col5)
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1
Your statement would work on DB2 for Linux/Unix/Windows (LUW), at least when I tested it on my LUW 9.7.
I'm using autolayout and none of the answers worked for me. Here is my solution that finally worked:
@property (nonatomic, assign) BOOL shouldScrollToLastRow;
- (void)viewDidLoad {
[super viewDidLoad];
_shouldScrollToLastRow = YES;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Scroll table view to the last row
if (_shouldScrollToLastRow)
{
_shouldScrollToLastRow = NO;
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
}
}
I found catching exception of driver.switchTo().alert();
is so slow in Firefox
(FF V20 & selenium-java-2.32.0).`
So I choose another way:
private static boolean isDialogPresent(WebDriver driver) {
try {
driver.getTitle();
return false;
} catch (UnhandledAlertException e) {
// Modal dialog showed
return true;
}
}
And it's a better way when most of your test cases is NO dialog present (throwing exception is expensive).
You can use -i''
(--in-place
) for sed
as already suggested. See: The -i
in-place argument, however note that -i
option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed
is a Stream EDitor, not a file editor.
Alternative way is to use built-in substitution in Vim Ex mode, like:
$ ex +%s/foo/bar/g -scwq file.txt
and for multiple-files:
$ ex +'bufdo!%s/foo/bar/g' -scxa *.*
To edit all files recursively you can use **/*.*
if shell supports that (enable by shopt -s globstar
).
Another way is to use gawk
and its new "inplace" extension such as:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1
Try this one -
"SELECT
ID, Salt, password, BannedEndDate
, (
SELECT COUNT(1)
FROM dbo.LoginFails l
WHERE l.UserName = u.UserName
AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"
str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
console.log("true");
}
update: Just saw the reference to call_user_func_array
in your post. that's different. use getattr
to get the function object and then call it with your arguments
class A(object):
def method1(self, a, b, c):
# foo
method = A.method1
method
is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1
with one of the two decorators discussed below, pass it an instance of A
as the first argument or access the method on an instance of A
.
a = A()
method = a.method1
method(1, 2)
You have three options for doing this
A
to call method1
(using two possible forms)classmethod
decorator to method1
: you will no longer be able to reference self
in method1
but you will get passed a cls
instance in it's place which is A
in this case.staticmethod
decorator to method1
: you will no longer be able to reference self
, or cls
in staticmethod1
but you can hardcode references to A
into it, though obviously, these references will be inherited by all subclasses of A
unless they specifically override method1
and do not call super
.Some examples:
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b
@staticmethod
def method2(a, b):
return a + b
@classmethod
def method3(cls, a, b):
return cls.method2(a, b)
t = Test1() # same as doing it in another class
Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one
Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class
Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)
Note that in the same way that the name of the self
variable is entirely up to you, so is the name of the cls
variable but those are the customary values.
Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.
I think you can just cast to ObjectNode and use put
method. Like this
ObjectNode o = (ObjectNode) jsonNode;
o.put("value", "NO");
Also, when you uninstall the package, the first item listed is the directory to the executable.
Here's a good evaluation of several engines http://engineering.linkedin.com/frontend/client-side-templating-throwdown-mustache-handlebars-dustjs-and-more
you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
<div>
<img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
</img>
<span>
Hello World!
</span>
</div>
What about this? No absolute positioning on div, but instead on img and span.
Rather than writing your own code / reinventing, consider using CalcBinding:
Automatic two way convertion of bool expression to Visibility and back if target property has such type: description
<Button Visibility="{c:Binding !IsChecked}" />
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
CalcBinding is also quite useful for numerous other scenarios.
PHP VERSION >= 5.3.0
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
.project
When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.
.classpath
Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
To get the latest stable version just run
npm install npm@latest -g
It worked just fine for me!
\t
is a tab character. Use a raw string instead:
test_file=open(r'c:\Python27\test.txt','r')
or double the slashes:
test_file=open('c:\\Python27\\test.txt','r')
or use forward slashes instead:
test_file=open('c:/Python27/test.txt','r')
In order to determine optimal k-cluster in clustering methods. I usually using Elbow
method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:
Elbow method
elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}
Running Elbow parallel
no_cores <- detectCores()
cl<-makeCluster(no_cores)
clusterEvalQ(cl, library(GMD))
clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
start.time <- Sys.time()
elbow.k.handle(data.clustering))
k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
end.time <- Sys.time()
cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)
It works well.
In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL
:
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];
return [NSData dataWithContentsOfURL:URL];
This will return in hh:mm:ss format
public static string ConvertTime(long secs)
{
TimeSpan ts = TimeSpan.FromSeconds(secs);
string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
return displayTime;
}
You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column
create table logins (userid int auto_increment primary key,
username varchar(30), password varchar(30));
then no special code is needed on insert. Just
insert into logins (username, password) values ('user','pass');
The MySQL API has functions to tell you what userid was created when you execute this statement in client code.
Try CONVERT instead of CAST.
CONVERT allows a third parameter indicating the date format.
List of formats is here: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Update after another answer has been selected as the "correct" answer:
I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.
You can do this via a couple ways.
One is when you run your application, you can pass it a flag.
java -Dgate.home="http://gate.ac.uk/wiki/code-repository" your_application
Or set it programmatically in code before the piece of code that needs this property set. Java keeps a Properties
object for System
wide configuration.
Properties props = System.getProperties();
props.setProperty("gate.home", "http://gate.ac.uk/wiki/code-repository");
Not tested, but it should work (edited after comments)
lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)
I believe that phrase should have been worded as follows:
bcrypt has salts built into the generated hashes to prevent rainbow table attacks.
The bcrypt
utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt
). Put another way, the "hash" generated by bcrypt
is not just the hash. Rather, it is the hash and the salt concatenated.
Python's standard library has json
and urllib2
modules.
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.
You can use java.awt.Robot
to achieve this task.
below is the code of server, which saves the captured screenshot as image in your Directory.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.
package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
@Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
When inplace=True
is passed, the data is renamed in place (it returns nothing), so you'd use:
df.an_operation(inplace=True)
When inplace=False
is passed (this is the default value, so isn't necessary), performs the operation and returns a copy of the object, so you'd use:
df = df.an_operation(inplace=False)
get the latest version information from:
https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin
click on the latest version (or the one you'd like to use) and you'll see the the dependency info (as of 2019-05 it's 3.8.1):
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
you might want to use the version tag and the comment for your plugin tag.
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
if you like you can modify your pom to have the version information in the properties tag as outlined in another answer.
This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.
In my case the problem that I faced was:
CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.4'
Fortunatelly, the target did not implemented anything, so a quick solution is remove it.
In SQL server 2012, below can be used
select FORMAT(getdate(), 'MMM yyyy')
This gives exact "Jun 2016"
There is a better way to write polar(), here it is:
def polar(x,y):
`returns r, theta(degrees)`
return math.hypot(x,y),math.degrees(math.atan2(y,x))
In short, the original purpose was to make a field which will be submitted with form's submit. Sometimes, there were need to store some information in hidden field(for example, id of user) and submit it with form's submit.
From HTML September 22, 1995 specification
An INPUT element with `TYPE=HIDDEN' represents a hidden field.The user does not interact with this field; instead, the VALUE attribute specifies the value of the field. The NAME and VALUE attributes are required.
Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.
Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.
Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.
For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.
Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).
2.0 Compatible Answer: While above mentioned answer explain in detail on how to use GPU on Keras Model, I want to explain how it can be done for Tensorflow Version 2.0
.
To know how many GPUs are available, we can use the below code:
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
To find out which devices your operations and tensors are assigned to,
put tf.debugging.set_log_device_placement(True)
as the first statement of your program.
Enabling device placement logging causes any Tensor allocations or operations to be printed. For example, running the below code:
tf.debugging.set_log_device_placement(True)
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
gives the Output shown below:
Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32)
For more information, refer this link
You need to install the Microsoft.Extensions.Logging.Log4Net.AspNetCore NuGet package and add a log4net.config-file to your application. Then this should work:
public class Program
{
private readonly ILogger<Program> logger;
public Program()
{
var services = new ServiceCollection()
.AddLogging(logBuilder => logBuilder.SetMinimumLevel(LogLevel.Debug))
.BuildServiceProvider();
logger = services.GetService<ILoggerFactory>()
.AddLog4Net()
.CreateLogger<Program>();
}
static void Main(string[] args)
{
Program program = new Program();
program.Run();
Console.WriteLine("\n\nPress any key to continue...");
Console.ReadKey();
}
private void Run()
{
logger.LogInformation("Logging is working");
}
}
For swift 3 purposes
theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
You can also use
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php:
function toptable()
{
echo 'something happens in here';
}
Hope it helps somebody
tick_params is very useful for setting tick properties. Labels can be moved to the top with:
ax.tick_params(labelbottom=False,labeltop=True)
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
You can use the $.ajax()
, and if you don't want to put the parameters directly into the URL, use the data:
. That's appended to the URL
You can use the folowing to get the full path to your program like this:
Environment.CurrentDirectory
Have you tried looking at your %PATH% variable. That's what Windows uses to find any executable.
From the documentation:
Installing and Updating Cygwin for 64-bit versions of Windows
Run setup-x86_64.exe any time you want to update or install a Cygwin package for 64-bit windows. The signature for setup-x86_64.exe can be used to verify the validity of this binary using this public key.
You can turn off the "Disable Script Debugging"
option inside of Internet Explorer and start debugging with Visual Studio
if you happen to have that around.
I've found that it is one of few ways to diagnose some of those IE
specific issues.
By using the following code you can find name, path, size as like this all kind of information of all audio song files
String[] STAR = { "*" };
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
cursor = managedQuery(allaudiosong, STAR, audioselection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
} while (cursor.moveToNext());
You go into ~/.janus
and run:
git submodule add <git@github ...> snipmate-snippets/snippets/
If you need more information about submodules (or git in general) ProGit is pretty useful.
$x = '1234567'; echo substr ($x, 0, 3); // outputs 123 echo substr ($x, 1, 1); // outputs 2 echo substr ($x, -2); // outputs 67 echo substr ($x, 1); // outputs 234567 echo substr ($x, -2, 1); // outputs 6
DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);
Try this
ALTER TABLE users
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;
check the syntax
Given an instance of the struct, you set the values.
student thisStudent;
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
thisStudent.s_id = int.Parse(Console.ReadLine());
thisStudent.s_name = Console.ReadLine();
thisStudent.c_name = Console.ReadLine();
thisStudent.s_dob = Console.ReadLine();
Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cnt extends CI_Controller {
public function insert_view()
{
$this->load->view('insert');
}
public function insert_data(){
$name=$this->input->post('emp_name');
$salary=$this->input->post('emp_salary');
$arr=array(
'emp_name'=>$name,
'emp_salary'=>$salary
);
$resp=$this->Model->insert_data('emp1',$arr);
echo "<script>alert('$resp')</script>";
$this->insert_view();
}
}
for more detail visit: http://wheretodownloadcodeigniter.blogspot.com/2018/04/insert-using-codeigniter.html
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH
environment variable (or other language equivalent, like PYTHONPATH
, LD_LIBRARY_PATH
) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.
Appearently Browsers still have troubles (although Chrome and Firefox Nightly do fine). I have a hacky approach for the people that really have to use a number field (maybe because of the little arrows that text fields dont have).
I added a keyup
event Handler to the form input and tracked the state and set the value once it comes valid again.
var currentString = '';_x000D_
var badState = false;_x000D_
var lastCharacter = null;_x000D_
_x000D_
document.getElementById("field").addEventListener("keyup",($event) => {_x000D_
if ($event.target.value && !$event.target.validity.badInput) {_x000D_
currentString = $event.target.value;_x000D_
} else if ($event.target.validity.badInput) {_x000D_
if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {_x000D_
$event.target.value = ((+currentString) + (+$event.key / 10));_x000D_
badState = false;_x000D_
} else {_x000D_
badState = true;_x000D_
}_x000D_
}_x000D_
document.getElementById("number").textContent = $event.target.value;_x000D_
lastCharacter = $event.key;_x000D_
});_x000D_
_x000D_
document.getElementById("field").addEventListener("blur",($event) => {_x000D_
if (badState) {_x000D_
$event.target.value = (+currentString);_x000D_
badState = false;_x000D_
document.getElementById("number").textContent = $event.target.value;_x000D_
}_x000D_
});
_x000D_
#result{_x000D_
padding: 10px;_x000D_
background-color: orange;_x000D_
font-size: 25px;_x000D_
width: 400px;_x000D_
margin-top: 10px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
#field{_x000D_
padding: 5px;_x000D_
border-radius: 5px;_x000D_
border: 1px solid grey;_x000D_
width: 400px;_x000D_
}
_x000D_
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">_x000D_
_x000D_
<span id="result" >_x000D_
<span >Current value: </span>_x000D_
<span id="number"></span>_x000D_
</span>
_x000D_
@Directive({_x000D_
selector: '[appFloatHelper]'_x000D_
})_x000D_
export class FloatHelperDirective {_x000D_
private currentString = '';_x000D_
private badState = false;_x000D_
private lastCharacter: string = null;_x000D_
_x000D_
@HostListener("blur", ['$event']) onBlur(event) {_x000D_
if (this.badState) {_x000D_
this.model.update.emit((+this.currentString));_x000D_
this.badState = false;_x000D_
}_x000D_
}_x000D_
_x000D_
constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {_x000D_
this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {_x000D_
if (el.nativeElement.value && !el.nativeElement.validity.badInput) {_x000D_
this.currentString = el.nativeElement.value;_x000D_
} else if (el.nativeElement.validity.badInput) {_x000D_
if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {_x000D_
model.update.emit((+this.currentString) + (+e.key / 10));_x000D_
el.nativeElement.value = (+this.currentString) + (+e.key / 10);_x000D_
this.badState = false;_x000D_
} else {_x000D_
this.badState = true;_x000D_
}_x000D_
} _x000D_
this.lastCharacter = e.key;_x000D_
});_x000D_
}_x000D_
_x000D_
}
_x000D_
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">
_x000D_
Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
Using the credentials helper command-line option:
git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin
Actually, the best solution is using JSON:
JSON.parse(text[, reviver]);
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3) Passing a function to JSON
var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();
Given some form:
<form action='/somepath' method='post'>
<input type='text' name='name'></input>
</form>
Using express
app.post('/somepath', function(req, res) {
console.log(JSON.stringify(req.body));
console.log('req.body.name', req.body['name']);
});
Output:
{"name":"x","description":"x"}
req.param.name x
Here is a sample Max-Heap in Java :
PriorityQueue<Integer> pq1= new PriorityQueue<Integer>(10, new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
if (x < y) return 1;
if (x > y) return -1;
return 0;
}
});
pq1.add(5);
pq1.add(10);
pq1.add(-1);
System.out.println("Peek: "+pq1.peek());
The output will be 10
Also set ${COMMAND}
to g++
on Linux
Under:
Replace:
${COMMAND} ${FLAGS} -E -P -v -dD "${INPUTS}"
with:
g++ -std=c++11 -E -P -v -dD "${INPUTS}"
If you don't do this, the Eclipse stdout shows:
Unable to find full path for "-E"
and logs under ${HOME}/eclipse-workspace/.metadata/.log
show:
!ENTRY org.eclipse.cdt.core 4 0 2020-04-23 20:17:07.288
!MESSAGE Error: Cannot run program "-E": Unknown reason
because ${COMMAND} ${FLAGS}
are empty, and so Eclipse tries to execute the -E
that comes next.
I wonder if we can properly define the COMMAND
and FLAGS
variables on the settings, but I tried to add them as build variables and it didn't work.
C version of the question: "Unresolved inclusion" error with Eclipse CDT for C standard library headers
Tested on Eclipse 2020-03 (4.15.0), Ubuntu 19.10, and this minimal Makefile project with existing sources.
You could set it up as a Scheduled Task, and set the Task Trigger for "At Startup"
It's probably best/easiest to set up a 301 redirect. No DNS hacking required.
You can't access element like you did (document.frm_new_user_request
). You have to use the function getElementById
:
document.getElementById("frm_new_user_request")
So getting a value from an input could look like this:
var value = document.getElementById("frm_new_user_request").value
Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.
Getting a value from an input using jQuery would look like this:
var value = $("#element).value
var value = $(".element).value
If the keystore contains other key-entries with different password you have to change them also or you can isolate your key to different keystore using below command,
keytool -importkeystore -srckeystore mystore.jck -destkeystore myotherstore.jks -srcstoretype jceks
-deststoretype jks -srcstorepass mystorepass -deststorepass myotherstorepass -srcalias myserverkey
-destalias myotherserverkey -srckeypass mykeypass -destkeypass myotherkeypass
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
If you want mm-dd-yyyy
format you can use:
mkdir %date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
Find the path to a process name
#!/bin/bash
# @author Lukas Gottschall
PID=`ps aux | grep precessname | grep -v grep | awk '{ print $2 }'`
PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print $10 }'`
echo $PATH
You are accessing an object that is not defined.
The solution is check for null or undefined (to see whether the object exists) and only then iterate.
I prefer using a more cleaner approach :
val.to_i.zero?
val.to_i
will return a 0
if val is a nil
,
after that, all we need to do is check whether the final value is a zero.
As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval
:
/*jshint evil:true */
function helloEval(str) {
/*jshint evil:true */
eval(str);
}
You can use sys.platform
:
from sys import platform
if platform == "linux" or platform == "linux2":
# linux
elif platform == "darwin":
# OS X
elif platform == "win32":
# Windows...
sys.platform
has finer granularity than sys.name
.
For the valid values, consult the documentation.
See also the answer to “What OS am I running on?”
You can assign, but not declare, inside an if
:
Try this:
int v; // separate declaration
if((v = someMethod()) != 0) return true;
What I did was append an extra '/' to my url, e.g.:
String url = "http://www.google.com"
to
String url = "http://www.google.com/"
This error can happen if you instantiate a class that relies on that table, for example in views.py.
// "TypeName"
func stringType(of some: Any) -> String {
let string = (some is Any.Type) ? String(describing: some) : String(describing: type(of: some))
return string
}
// "ModuleName.TypeName"
func fullStringType(of some: Any) -> String {
let string = (some is Any.Type) ? String(reflecting: some) : String(reflecting: type(of: some))
return string
}
print(stringType(of: SomeClass())) // "SomeClass"
print(stringType(of: SomeClass.self)) // "SomeClass"
print(stringType(of: String())) // "String"
print(fullStringType(of: String())) // "Swift.String"
Method 1: Add an event listener for input
:
element.addEventListener("input", myFunction);
Method 2: Define the oninput
property with JavaScript:
element.oninput = function()
{
myFunction();
};
Method 3: Define the oninput
property with HTML:
<input type="text" oninput="myFunction();">
If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.
Call locale charmap
from the shell (not the python interpreter) and you should see
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
If this is not the case, and you see something else, e.g.
[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $
Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding()
and sys.setdefaultencoding()
is in this case ignored.
If you find that you have this problem, you can fix that by
[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf
(or whichever file governs the locale definition in your system) to correct this.
Disabling the "SETTINGS > PRIVACY > don´t allow JavaScript" in Chrome will enable the right click function and allow the Firebug Console to work; but will also disable all the other JavaScript codes.
The right way to do this is to disable only the specific JavaScript; looking for any of the following lines of code:
For macOs users you can use Homebrew instead :
# For php v7.0
brew install [email protected]
# For php v7.1
brew install [email protected]
# For php v7.2
brew install [email protected]
# For php v7.3
brew install [email protected]
# For php v7.4
brew install [email protected]
Minor variation on Geoff's answer.
New Data in Array:
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
New Data in Horizontal Range:
Sub AddDataRow(tableName As String, NewData As Range)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last table row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Copy NewData to new table record
Set lastRow = table.ListRows(table.ListRows.Count).Range
lastRow.Value = NewData.Value
End Sub
this work for me, just prevent the event, add the url to an <a>
tag
then trigger the click event on that tag
.
Js
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href',"http://someurl.com");
$(this).trigger('click');
});
HTML
<a href="#" class="myBtn" target="_blank">Go</a>
Inspired by @skiwi, I solved it the following way:
public static <T> T toSingleton(Stream<T> stream) {
List<T> list = stream.limit(1).collect(Collectors.toList());
if (list.isEmpty()) {
return null;
} else {
return list.get(0);
}
}
And then:
User user = toSingleton(users.stream().filter(...).map(...));
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
As this is specifically tagged for jQuery -
$("#myElement")[0].getBoundingClientRect();
or
$("#myElement").get(0).getBoundingClientRect();
(These are functionally identical, in some older browsers .get()
was slightly faster)
Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...
Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect()
calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...
Basically , Data in a Date column in Oracle can be stored in any user defined format or kept as default. It all depends on NLS parameter.
Current format can be seen by : SELECT SYSDATE FROM DUAL;
If you try to insert a record and insert statement is NOT in THIS format then it will give : ORA-01843 : not a valid month error. So first change the database date format before insert statements ( I am assuming you have bulk load of insert statements) and then execute insert script.
Format can be changed by : ALTER SESSION SET nls_date_format = 'mm/dd/yyyy hh24:mi:ss';
Also You can Change NLS settings from SQL Developer GUI , (Tools > preference> database > NLS)
If you open your second link in a browser you'll see the source code:
#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov
[...]
# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4
for year in {2002..2003}
do
for tile in {1159..1160}
do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
# An example using curl instead of wget
#do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
done
done
So it's a bash script. Got Linux?
In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.
Move the cursor to the begining or end with insert mode
I
- Moves the cursor to the first non blank character in the current line and enables insert mode.A
- Moves the cursor to the last character in the current line and enables insert mode.Here I
is equivalent to ^
+ i
. Similarly A
is equivalent to $
+ a
.
Just moving the cursor to the begining or end
^
- Moves the cursor to the first non blank character in the current
line0
- Moves the cursor to the first character in the current line$
- Moves the cursor to the last character in the current lineBest way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:
function waitSeconds(iMilliSeconds) {_x000D_
var counter= 0_x000D_
, start = new Date().getTime()_x000D_
, end = 0;_x000D_
while (counter < iMilliSeconds) {_x000D_
end = new Date().getTime();_x000D_
counter = end - start;_x000D_
}_x000D_
}
_x000D_
I suggest that all events for Spinner are divided on two types:
User events (you meant as "click" event).
Program events.
I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:
private void setSelectionWithoutDispatch(Spinner spinner, int position) {
AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
spinner.setOnItemSelectedListener(null);
spinner.setSelection(position, false);
spinner.setOnItemSelectedListener(onItemSelectedListener);
}
There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.
Build Version Increment (GPL) gives you (nearly) everything you need for controlling the version of your assemblies.
Some Features (copied from the site):
Use RGBA like this: background-color: rgba(255, 0, 0, .5)
DBeaver allows you connect to a DB2 database, run a query, and export the result-set to a CSV file that can be opened and fine-tuned in MS Excel or LibreOffice Calc.
To do this, all you have to do (in DBeaver) is right-click on the results grid (after running the query) and select "Export Resultset" from the context-menu.
This produces the dialog below, where you can ultimately save the result-set to a file as CSV, XML, or HTML:
There is not a program but you can make a batch file and run a command like that :
powershell "start-process 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -workingdirectory 'C:\Program Files (x86)\IIS Express\' -windowstyle Hidden"
As other people said defining private methods in the @implementation
block is OK for most purposes.
On the topic of code organization - I like to keep them together under pragma mark private
for easier navigation in Xcode
@implementation MyClass
// .. public methods
# pragma mark private
// ...
@end
This is the correct answer. It will refresh the previous page.
window.location=document.referrer;
It's easy, if your mailx
command supports the -a
(append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html
If it doesn't, try using sendmail
:
# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
Simple Solution, just type the below:
conda update pandas
Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).
They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.
If you're experiencing a different behaviour, it's time to change for another DBMS.
I found that the best way to determine if the service call has timed out is to use a cancellation token and not the HttpClient's timeout property:
var cts = new CancellationTokenSource();
cts.CancelAfter(timeout);
And then handle the CancellationException during the service call...
catch(TaskCanceledException)
{
if(!cts.Token.IsCancellationRequested)
{
// Timed Out
}
else
{
// Cancelled for some other reason
}
}
Of course if the timeout occurs on the service side of things, that should be able to handled by a WebException.
I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:
window.parent.document.getElementById('yourdiv');
Then do whatever you want with that div.
It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.
You can use cat
if it's installed, which will most likely be the case if it's not a bare/raw container. It works in a pinch, and ok when copy+pasting to a proper editor locally.
cat > file
# 1. type in your content
# 2. leave a newline at end of file
# 3. ctrl-c / (better: ctrl-d)
cat file
cat
will output each line on receiving a newline. Make sure to add a newline for that last line. ctrl-c sends a SIGINT
for cat to exit gracefully. From the comments you see that you can also hit ctrl-d to denote end-of-file ("no more input coming").
Another option is something like infilter
which injects a process into the container namespace with some ptrace magic: https://github.com/yadutaf/infilter