An object is defined by an OBJECT_ID, which is unique. If A and B are objects and A == B is true, then they are the very same object, they have the same data and methods, but, this is also true:
A.OBJECT_ID == B.OBJECT_ID
if A.Equals(B) is true, that means that the two objects are in the same state, but this doesn't mean that A is the very same as B.
Strings are objects.
Note that the == and Equals operators are reflexive, simetric, tranzitive, so they are equivalentic relations (to use relational algebraic terms)
What this means: If A, B and C are objects, then:
(1) A == A is always true; A.Equals(A) is always true (reflexivity)
(2) if A == B then B == A; If A.Equals(B) then B.Equals(A) (simetry)
(3) if A == B and B == C, then A == C; if A.Equals(B) and B.Equals(C) then A.Equals(C) (tranzitivity)
Also, you can note that this is also true:
(A == B) => (A.Equals(B)), but the inverse is not true.
A B =>
0 0 1
0 1 1
1 0 0
1 1 1
Example of real life: Two Hamburgers of the same type have the same properties: they are objects of the Hamburger class, their properties are exactly the same, but they are different entities. If you buy these two Hamburgers and eat one, the other one won't be eaten. So, the difference between Equals and ==: You have hamburger1 and hamburger2. They are exactly in the same state (the same weight, the same temperature, the same taste), so hamburger1.Equals(hamburger2) is true. But hamburger1 == hamburger2 is false, because if the state of hamburger1 changes, the state of hamburger2 not necessarily change and vice versa.
If you and a friend get a Hamburger, which is yours and his in the same time, then you must decide to split the Hamburger into two parts, because you.getHamburger() == friend.getHamburger() is true and if this happens: friend.eatHamburger(), then your Hamburger will be eaten too.
I could write other nuances about Equals and ==, but I'm getting hungry, so I have to go.
Best regards, Lajos Arpad.
Don't customize your bootstrap CSS by directly editing bootstrap CSS file.Instead, I suggest to copy paste bootstrap CSS and save them in a different CSS folder and there you can customize or edit stylings suitable to your needs.
EDIT: Use the accepted answer, this will not work if the default location isn't being used, for example: The user moved the desktop to another drive like D:\Desktop
At least on Windows XP, Vista and 7 you can use the "%UserProfile%\Desktop"
safely.
Windows XP en-US it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows XP pt-BR it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows 7 en-US it will expand to "C:\Users\YourName\Desktop"
Windows 7 pt-BR it will expand to "C:\Usuarios\YourName\Desktop"
On XP you can't use this to others folders exept for Desktop
My documents
turning to Meus Documentos
and Local Settings
to Configuracoes locais
Personaly I thinks this is a bad thing when projecting a OS.
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
A good library available named log4j for Java.
This will provide numerous feature. Go through link and you will find your solution.
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
I've written an extension method for this purpose:
public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
return Convert.FromBase64String(base64String);
}
Call it like this:
byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();
I hope it helps someone.
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
It is either:
if (B.class.isInstance(view))
API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)
or:
if (B.class.isAssignableFrom(view.getClass()))
API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter
or (without reflection and the recommended one):
if (view instanceof B)
To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:
if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}
This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).
For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.
If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH');
in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
If you have GNU find
, then there are a legion of relevant options. The only snag is that the interface to them is less than stellar:
-mmin n
(modification time in minutes)-mtime n
(modification time in days)-newer file
(modification time newer than modification time of file)-daystart
(adjust start time from current time to start of day)The hard part is determining the number of minutes since a time.
One option worth considering: use touch
to create a file with the required modification time stamp; then use find
with -newer
.
touch -t 200901031231.43 /tmp/wotsit
find . -newer /tmp/wotsit -print
rm -f /tmp/wotsit
This looks for files newer than 2009-01-03T12:31:43. Clearly, in a script, /tmp/wotsit
would be a name with the PID or other value to make it unique; and there'd be a trap
to ensure it gets removed even if the user interrupts, and so on and so forth.
This solution will take a character vector of package names and attempt to load them, or install them if loading fails. It relies on the return behaviour of require
to do this because...
require
returns (invisibly) a logical indicating whether the required package is available
Therefore we can simply see if we were able to load the required package and if not, install it with dependencies. So given a character vector of packages you wish to load...
foo <- function(x){
for( i in x ){
# require returns TRUE invisibly if it was able to load package
if( ! require( i , character.only = TRUE ) ){
# If package was not able to be loaded then re-install
install.packages( i , dependencies = TRUE )
# Load package after installing
require( i , character.only = TRUE )
}
}
}
# Then try/install packages...
foo( c("ggplot2" , "reshape2" , "data.table" ) )
Using Encoding.Unicode won't accurately decode an ANSI file in the same way that a JPEG decoder won't understand a GIF file.
I'm surprised that Encoding.Default
didn't work for the ANSI file if it really was ANSI - if you ever find out exactly which code page Notepad was using, you could use Encoding.GetEncoding(int)
.
In general, where possible I'd recommend using UTF-8.
var map = new google.maps.Map(document.getElementById("map"),{
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
}
map.fitBounds(bounds);
You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
The family of methods that does this are:
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
Just pass it as normal parameters and access it in PHP using the $argv
array.
php myfile.php daily
and in myfile.php
$type = $argv[1];
Scrolling to the bottom of a page:
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Running npm start from react-native directory worked out for me.
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
If you want to be real smart, at the command line type:
echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd
Then you have CreateService.cmd
that you can run whenever you want (.cmd
is just another extension for .bat
files)
If you use the enumerable mixin (as Rails does) you can do something similar to the php snippet listed. Just use the each_slice method and flatten the hash.
require 'enumerator'
['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
# is equivalent to...
{'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
Less monkey-patching required.
However, this does cause problems when you have a recursive array or a hash with array values. In ruby 1.9 this problem is solved with a parameter to the flatten method that specifies how deep to recurse.
# Ruby 1.8
[1,2,[1,2,3]].flatten
=> [1,2,1,2,3]
# Ruby 1.9
[1,2,[1,2,3]].flatten(0)
=> [1,2,[1,2,3]]
As for the question of whether this is a code smell, I'm not sure. Usually when I have to bend over backwards to iterate over something I step back and realize I'm attacking the problem wrong.
imho there are two cases for branches that were forgot to close
Case 1: branch was not merged into default
in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.
hg up myBranch
hg commit --close-branch
Case 2: branch was merged into default
This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.
in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!
hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch
Hope this helps future readers.
$(this).value
is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val()
.
function suppressNonNumericInput(event){
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
}
Jquery: Fire Button click event Using enter Button Press try this::
tabindex="0" onkeypress="return EnterEvent(event)"
<!--Enter Event Script-->
<script type="text/javascript">
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=btnSave.UniqueID%>', "");
}
}
</script>
<!--Enter Event Script-->
Edit: My initial answer had a strong focus on AMQP. I decided to rewrite it to offer a wider view on the topic.
These 3 messaging technologies have different approaches on building distributed systems :
RabbitMQ is one of the leading implementation of the AMQP protocol (along with Apache Qpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.
ZeroMq is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices). Zmq is very flexible but you’ll have to study the 80 pages or so of the guide (which I recommend reading for anybody writing distributed system, even if you don’t use Zmq) before being able to do anything more complicated than sending messages between 2 peers.
ActiveMQ is in the middle ground. Like Zmq, it can be deployed with both broker and P2P topologies. Like RabbitMQ, it’s easier to implement advanced scenarios but usually at the cost of raw performance. It’s the Swiss army knife of messaging :-).
Finally, all 3 products:
You could use smth like this in WPF. I've created example method. Check below.
public string getFolderPath()
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog() == true)
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(openFileDialog.FileName);
return fInfo.DirectoryName;
}
return null;
}
As a supplement,
1, Carriage return: It's a printer terminology meaning changing the print location to the beginning of current line. In computer world, it means return to the beginning of current line in most cases but stands for new line rarely.
2, Line feed: It's a printer terminology meaning advancing the paper one line. So Carriage return and Line feed are used together to start to print at the beginning of a new line. In computer world, it generally has the same meaning as newline.
3, Form feed: It's a printer terminology, I like the explanation in this thread.
If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.
It's almost obsolete and you can refer to Escape sequence \f - form feed - what exactly is it? for detailed explanation.
Note, we can use CR or LF or CRLF to stand for newline in some platforms but newline can't be stood by them in some other platforms. Refer to wiki Newline for details.
LF: Multics, Unix and Unix-like systems (Linux, OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others
CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS up to version 9, MIT Lisp Machine and OS-9
RS: QNX pre-POSIX implementation
0x9B: Atari 8-bit machines using ATASCII variant of ASCII (155 in decimal)
CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM OSes
LF+CR: Acorn BBC and RISC OS spooled text output.
Put this sentence in a crontab file: 0 0 * * * /usr/local/bin/python /opt/ByAccount.py > /var/log/cron.log 2>&1
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.
export interface ISearchResult {
title: string;
listTitle:string;
entityName?: string,
lookupName?:string,
lookupId?:string
}
In Oracle 12c you can also declare an identity column
CREATE TABLE identity_test_tab (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description VARCHAR2(30)
);
examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.
Instead of parsing it manually it's better to use pathinfo function:
$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];
column-span: all; /* W3C */
-webkit-column-span: all; /* Safari & Chrome */
-moz-column-span: all; /* Firefox */
-ms-column-span: all; /* Internet Explorer */
-o-column-span: all; /* Opera */
http://www.quackit.com/css/css3/properties/css_column-span.cfm
Print pg_hba.conf file location:
su - postgres -c "psql -t -P format=unaligned -c 'show hba_file';"
Print postgresql.conf file location:
su - postgres -c "psql -t -P format=unaligned -c 'SHOW config_file';"
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
NumPy is slower because it casts the input to boolean values (so None and 0 becomes False and everything else becomes True).
import pandas as pd
import numpy as np
s = pd.Series([True, None, False, True])
np.logical_not(s)
gives you
0 False
1 True
2 True
3 False
dtype: object
whereas ~s would crash. In most cases tilde would be a safer choice than NumPy.
Pandas 0.25, NumPy 1.17
Here's how I do it:
<span style="font-size:1.5em;" class="glyphicon glyphicon-th-list"></span>
This allows you to change size on the fly. Works best for ad hoc requirements to change the size, rather than changing the css and having it apply to all.
I didn't see my thoughts repeated already, so I will suggest that you look at string.Trim
in the Microsoft documentation for C# you can add a character to be trimmed instead of simply trimming empty spaces:
string withQuotes = "\"hellow\"";
string withOutQotes = withQuotes.Trim('"');
should result in withOutQuotes being "hello"
instead of ""hello""
A. If using "target": "es5"
and TypeScript version below 2.0:
typings install es6-promise --save --global --source dt
B. If using "target": "es5"
and TypeScript version 2.0 or higer:
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
C. If using "target": "es6"
, there's no need to do anything.
Notice: This is for MySQLdb module in Python.
For a SELECT
statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]
) for cursor.fetchall()
and None
for cursor.fetchone()
.
For any other statement, e.g. INSERT
or UPDATE
, that doesn't return a recordset, you can neither call fetchall()
nor fetchone()
on the cursor. Otherwise, an exception will be raised.
There's one way to distinguish between the above two types of cursors:
def yield_data(cursor):
while True:
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT, yield data
yield cursor.fetchall()
# Or yield column names with
# yield [col[0] for col in cursor.description]
# Go to the next recordset
if not cursor.nextset():
# End of recordsets
return
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
I think what you are looking for is the 'not' operator?
if not var
Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
Demo here: http://jsfiddle.net/hW7Ch/
You don't need to rely on the preprocessor to ensure your enums and strings are in sync. To me using macros tend to make the code harder to read.
enum fruit
{
APPLE = 0,
ORANGE,
GRAPE,
BANANA,
/* etc. */
FRUIT_MAX
};
const char * const fruit_str[] =
{
[BANANA] = "banana",
[ORANGE] = "orange",
[GRAPE] = "grape",
[APPLE] = "apple",
/* etc. */
};
Note: the strings in the fruit_str
array don't have to be declared in the same order as the enum items.
printf("enum apple as a string: %s\n", fruit_str[APPLE]);
If you are afraid to forget one string, you can add the following check:
#define ASSERT_ENUM_TO_STR(sarray, max) \
typedef char assert_sizeof_##max[(sizeof(sarray)/sizeof(sarray[0]) == (max)) ? 1 : -1]
ASSERT_ENUM_TO_STR(fruit_str, FRUIT_MAX);
An error would be reported at compile time if the amount of enum items does not match the amount of strings in the array.
Just remove the (
and the )
on your SELECT statement:
insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;
I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled
attribute.
<input disabled="disabled" id="price_from" value="price from ">
While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.
Nettica must be running a custom redirection solution for this, here is the problem:
You could create a CNAME alias like aws.example.com
for myaccount.signin.aws.amazon.com
, however, DNS provides no official support for aliasing a subdirectory like console
in this example.
https://myaccount.signin.aws.amazon.com/
(I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.
So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.
What about something like this:
First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method
option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean
with a window of 3 and min_periods=1 :
pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
favorable unfavorable other
enddate
2012-10-25 0.495000 0.485000 0.025000
2012-10-26 0.527500 0.442500 0.032500
2012-10-27 0.521667 0.451667 0.028333
2012-10-28 0.515833 0.450000 0.035833
2012-10-29 0.488333 0.476667 0.038333
2012-10-30 0.495000 0.470000 0.038333
2012-10-31 0.512500 0.460000 0.029167
2012-11-01 0.516667 0.456667 0.026667
2012-11-02 0.503333 0.463333 0.033333
2012-11-03 0.490000 0.463333 0.046667
2012-11-04 0.494000 0.456000 0.043333
2012-11-05 0.500667 0.452667 0.036667
2012-11-06 0.507333 0.456000 0.023333
2012-11-07 0.510000 0.443333 0.013333
UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:
df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()
I've cribbed together and tested with github the following approach, based on reading other answers, which combines a few techniques:
The advantage of this approach is, once set up, it doesn't require any additional work to get it right - for example, you don't need to change remote URLs or remember to clone things differently - the URL rewriting makes it all work.
~/.ssh/config
# Personal GitHub
Host github.com
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/github_id_rsa
# Work GitHub
Host github-work
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/work_github_id_rsa
Host *
IdentitiesOnly yes
~/.gitconfig
[user]
name = My Name
email = [email protected]
[includeIf "gitdir:~/dev/work/"]
path = ~/dev/work/.gitconfig
[url "github-work:work-github-org/"]
insteadOf = [email protected]:work-github-org/
~/dev/work/.gitconfig
[user]
email = [email protected]
As long as you keep all your work repos under ~/dev/work and personal stuff elsewhere, git will use the correct SSH key when doing pulls/clones/pushes to the server, and it will also attach the correct email address to all of your commits.
References:
n = ThisWorkbook.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
This line
except Vehicle.vehicledevice.device.DoesNotExist
means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like
except Device.DoesNotExist
First there is same .jar
file that in fb-sdk android-support-v4.jar
.
Then generate SHA1
key using:
PackageInfo info;
try {
info = getPackageManager().getPackageInfo(
"com.example.worldmission", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
Log.e("Hash key", something);
System.out.println("Hash key" + something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
select * from [tbl] where [link] is not null and len([link]) > 1
For MySQL user:
LENGTH([link]) > 1
Press 'Windows-Key"+R , and enter %APPDATA%\Code\User
And delete 'setting.json' at this location.
Press 'Windows-Key"+R , and enter %USERPROFILE%.vscode\extensions
And delete all the extensions there.
After two vote downs added images to make it more clear :)
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT @colsUpd = STUF ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
WHERE object_id = (
SELECT top 1 object_id
FROM sys.objects
WHERE name = ''+@TableNameTest+''
)
and name not in ('Action','Record_ID')
FOR XML PATH('')
), 1, 2, ''
) + ']'
Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)
Below is the easy one -
cat countvariable.sh
echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'
Output :
#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8
Models.py define the serializers
def default(o):
if isinstance(o, (date, datetime)):
return o.isoformat()
class User(db.Model):
__tablename__='user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
.......
####
def serializers(self):
dict_val={"id":self.id,"created_by":self.created_by,"created_at":self.created_at,"updated_by":self.updated_by,"updated_at":self.updated_at}
return json.loads(json.dumps(dict_val,default=default))
In RestApi, We can update the record dynamically by passing the json data into update query:
class UpdateUserDetails(Resource):
@auth_token_required
def post(self):
json_data = request.get_json()
user_id = current_user.id
try:
instance = User.query.filter(User.id==user_id)
data=instance.update(dict(json_data))
db.session.commit()
updateddata=instance.first()
msg={"msg":"User details updated successfully","data":updateddata.serializers()}
code=200
except Exception as e:
print(e)
msg = {"msg": "Failed to update the userdetails! please contact your administartor."}
code=500
return msg
From the command line, it's simply:
printf "compute sha1" | openssl sha1
You can invoke the library like this:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
int main()
{
unsigned char ibuf[] = "compute sha1";
unsigned char obuf[20];
SHA1(ibuf, strlen(ibuf), obuf);
int i;
for (i = 0; i < 20; i++) {
printf("%02x ", obuf[i]);
}
printf("\n");
return 0;
}
A scriptless, CSS-only experimental approach with image pre-loadingBONUS! and which only works in Firefox:
<style>
a.zoom .full { display: none; }
a.zoom:active .thumb { display: none; }
a.zoom:active .full { display: inline; }
</style>
<a class="zoom" href="#">
<img class="thumb" src="thumbnail.png"/>
<img class="full" src="fullsize.png"/>
</a>
Shows the thumbnail by default. Shows the full size image while the mouse button is clicked and held down. Goes back to the thumbnail as soon as the button is released. I'm in no way suggesting that this method be used; it's just a demo of a CSS-only approach that [very] partially solves the problem. With some z-index + relative position tweaks, it could work in other browsers too.
For someone who is trying all these solution but not working try this one, it worked for me
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>().Property(t => t.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}
You can get this error even with all the correct MapRoutes in your area registration. Try adding this line to your controller action:
If Not ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
ControllerContext.RouteData.DataTokens.Add("area", "MyAreaName")
End If
Assign the onclick like this:
divTag.onclick = printWorking;
The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking
).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>
, but this is generally not recommended.
Basically, window event may not be assigned to MVVM. In general, the Close button show a Dialog box to ask the user "save : yes/no/cancel", and this may not be achieved by the MVVM.
You may keep the OnClosing event handler, where you call the Model.Close.CanExecute() and set the boolean result in the event property. So after the CanExecute() call if true, OR in the OnClosed event, call the Model.Close.Execute()
It is and old question but let me add a detail just in case more people like me arrive here.
The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:
browser.setInitialScale(30);
The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.
I solved the problem by adding the following lines to the AppSettings section of my web.config file:
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
Depending on your privileges, this query might work:
SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql
A very old question I know but...
A pandas DataFrame seems to be the ideal option here.
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html
From the blurb
Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure
I would like to expand on Martin's answer there...
His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.
Martins Solution:
a.getClass().getName()
However, If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.
I myself used it like this:
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Using Generics:
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
let
is used to declare a constant value - you won't change it after giving it an initial value.
var
is used to declare a variable value - you could change its value as you wish.
This was our solution for replacing master on a corporate gitHub repository while maintaining history.
push -f
to master on corporate repositories is often disabled to maintain branch history. This solution worked for us.
git fetch desiredOrigin
git checkout -b master desiredOrigin/master // get origin master
git checkout currentBranch // move to target branch
git merge -s ours master // merge using ours over master
// vim will open for the commit message
git checkout master // move to master
git merge currentBranch // merge resolved changes into master
push your branch to desiredOrigin
and create a PR
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
I just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', {
// mode: 'no-cors',
method: 'GET',
headers: {
Accept: 'application/json',
},
},
).then(response => {
if (response.ok) {
response.json().then(json => {
console.log(json);
});
}
});
While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.
For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.
phantomjs.exe --web-security=no script.js
See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes
Set apache to list to a specific interface and port something like below:
Listen 192.170.2.1:80
Also check for Iptables and TCP Wrappers entries that might be interfering on the host with outside hosts accessing that port
The first part has already been answered, "just a suggestion" The second part has also been answered, "remove extra spaces around =" If both these didnt work, are you sure you have implemented ToolRunner ?
Another method to create this would be using the if
conditionals...meaning you would reference a cell that has a value and depending on that value it will give you the bucket such as small
.
For example, =if(b2>30,"large",if(b2>20,"medium",if(b2>=10,"small",if(b2<10,"tiny",""))))
So if cell b2
had a value of 12
, then it will return the word small
.
Hope this was what you're looking for.
JavaScript is duck-typed, so if you just copy a readable stream's API, it'll work just fine. In fact, you can probably not implement most of those methods or just leave them as stubs; all you'll need to implement is what the library uses. You can use Node's pre-built EventEmitter
class to deal with events, too, so you don't have to implement addListener
and such yourself.
Here's how you might implement it in CoffeeScript:
class StringStream extends require('events').EventEmitter
constructor: (@string) -> super()
readable: true
writable: false
setEncoding: -> throw 'not implemented'
pause: -> # nothing to do
resume: -> # nothing to do
destroy: -> # nothing to do
pipe: -> throw 'not implemented'
send: ->
@emit 'data', @string
@emit 'end'
Then you could use it like so:
stream = new StringStream someString
doSomethingWith stream
stream.send()
I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.
I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".
Perhaps a more pythonic way of doing so.
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, t, b, t, c)
plt.show()
This is a bit late but I know it will help someone:
If you are using datetimepicker
make sure you include the right CSS and JS files. datetimepicker
uses(Take note of their names);
and
On the above question asked by @mindfreak,The main problem is due to the imported files.
This will work too:
$('<li>').text('hello').appendTo('#mylist');
It feels more like a jquery way with the chained function calls.
Just answering this old thread can be installed without pip On windows or Linux:
1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button
2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there
3) Depending on the Os run the following command:
Thats it :)
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
Window --> Show View --> Variables
The same problem Error while retrieving information from server. [RPC:S-5:AEC-0]
was resolved after these steps:
Sign-in error
notification on your device.Actually, this helps me.
I fixed a similar error by adding the json dataType like so:
$.ajax({
type: "POST",
url: "someUrl",
dataType: "json",
data: {
varname1 : "varvalue1",
varname2 : "varvalue2"
},
success: function (data) {
$.each(data, function (varname, varvalue){
...
});
}
});
And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):
@RequestMapping(value = "/someUrl", method=RequestMethod.POST)
@ResponseBody
public String getJsonData(@RequestBody String parameters) {
// parameters = varname1=varvalue1&varname2=varvalue2
String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
return exampleData;
}
So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):
[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]
verified working with socket.io v3.1.1
It's as easy as:
client.emit("your message");
And that's it. Ok, but how does it work?
Here's an example of a simple client-server interaction where each client regularly receives a message containing a sequence number. There is a unique sequence for each client and that's where the "I need to send a message to a particular client" comes into play.
server.js
const
{Server} = require("socket.io"),
server = new Server(8000);
let
sequenceNumberByClient = new Map();
// event fired every time a new client connects:
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
// initialize this client's sequence number
sequenceNumberByClient.set(socket, 1);
// when socket disconnects, remove it from the list:
socket.on("disconnect", () => {
sequenceNumberByClient.delete(socket);
console.info(`Client gone [id=${socket.id}]`);
});
});
// sends each client its current sequence number
setInterval(() => {
for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
client.emit("seq-num", sequenceNumber);
sequenceNumberByClient.set(client, sequenceNumber + 1);
}
}, 1000);
The server starts listening on port 8000 for incoming connections. As soon as a new connection is established, that client is added to a map that keeps track of its sequence number. The server also listens for the disconnect
event to remove the client from the map when it leaves.
Each and every second, a timer is fired. When it does, the server walks through the map and sends a message to every client with their current sequence number, incrementing it right after. That's all that is to it. Easy peasy.
The client part is even simpler. It just connects to the server and listens for the seq-num
message, printing it to the console every time it arrives.
client.js
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:8000");
ioClient.on("seq-num", (msg) => console.info(msg));
Install the required libraries:
npm install [email protected] [email protected]
Run the server:
node server
Open other terminal windows and spawn as many clients as you want by running:
node client
I have also prepared a gist with the full code here.
.gitignore will only ignore files that you haven't already added to your repository.
If you did a git add .
, and the file got added to the index, .gitignore won't help you. You'll need to do git rm sites/default/settings.php
to remove it, and then it will be ignored.
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
You can also run conda init
as below,
C:\ProgramData\Anaconda3\Scripts\conda init cmd.exe
or
C:\ProgramData\Anaconda3\Scripts\conda init powershell
Note that the execution policy of powershell must be set, e.g. using Set-ExecutionPolicy Unrestricted
.
Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/
It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.
The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:
$data = [
"rs" => null
]
this above will work absolutely fine when used like:
$data["rs"] = 5;
But the below will throw a warning ::
$data = [
"rs" => [
"rs1" => null;
]
]
..
$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
Non-Unicode string data types:
Use STR for text file and VARCHAR for SQL Server columns.
Unicode string data types:
Use W_STR for text file and NVARCHAR for SQL Server columns.
The problem is that your data types do not match, so there could be a loss of data during the conversion.
I found the information in this conversation so helpful that I just wanted to add how I figured it out by using the timestamp from my MySQL database and a little PHP
<?= date("Y-m-d\TH:i:s\+01:00",strtotime($column['loggedin'])) ?>
The output was: 2017-03-03T08:22:36+01:00
Thanks very much Stewe you answer was a eureka for me.
As of Xcode 7.1 and Swift 2.1 containsString()
is working fine for me.
let string = "hello swift"
if string.containsString("swift") {
print("found swift")
}
Swift 4:
let string = "hello swift"
if string.contains("swift") {
print("found swift")
}
And a case insensitive Swift 4 example:
let string = "Hello Swift"
if string.lowercased().contains("swift") {
print("found swift")
}
Or using a case insensitive String
extension:
extension String {
func containsIgnoreCase(_ string: String) -> Bool {
return self.lowercased().contains(string.lowercased())
}
}
let string = "Hello Swift"
let stringToFind = "SWIFT"
if string.containsIgnoreCase(stringToFind) {
print("found: \(stringToFind)") // found: SWIFT
}
print("string: \(string)")
print("stringToFind: \(stringToFind)")
// console output:
found: SWIFT
string: Hello Swift
stringToFind: SWIFT
Here's a full featured TimeOfDay class.
This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.
It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.
Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:
This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.
// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT
using System;
using System.Text.RegularExpressions;
namespace Cambia
{
public class TimeOfDay
{
private const int MINUTES_PER_DAY = 60 * 24;
private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
private const int SECONDS_PER_HOUR = 3600;
private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");
public TimeOfDay()
{
Init(0, 0, 0);
}
public TimeOfDay(int hour, int minute, int second = 0)
{
Init(hour, minute, second);
}
public TimeOfDay(int hhmmss)
{
Init(hhmmss);
}
public TimeOfDay(DateTime dt)
{
Init(dt);
}
public TimeOfDay(TimeOfDay td)
{
Init(td.Hour, td.Minute, td.Second);
}
public int HHMMSS
{
get
{
return Hour * 10000 + Minute * 100 + Second;
}
}
public int Hour { get; private set; }
public int Minute { get; private set; }
public int Second { get; private set; }
public double TotalDays
{
get
{
return TotalSeconds / (24d * SECONDS_PER_HOUR);
}
}
public double TotalHours
{
get
{
return TotalSeconds / (1d * SECONDS_PER_HOUR);
}
}
public double TotalMinutes
{
get
{
return TotalSeconds / 60d;
}
}
public int TotalSeconds
{
get
{
return Hour * 3600 + Minute * 60 + Second;
}
}
public bool Equals(TimeOfDay other)
{
if (other == null) { return false; }
return TotalSeconds == other.TotalSeconds;
}
public override bool Equals(object obj)
{
if (obj == null) { return false; }
TimeOfDay td = obj as TimeOfDay;
if (td == null) { return false; }
else { return Equals(td); }
}
public override int GetHashCode()
{
return TotalSeconds;
}
public DateTime ToDateTime(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
}
public override string ToString()
{
return ToString("HH:mm:ss");
}
public string ToString(string format)
{
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
return dt.ToString(format);
}
public TimeSpan ToTimeSpan()
{
return new TimeSpan(Hour, Minute, Second);
}
public DateTime ToToday()
{
var now = DateTime.Now;
return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
}
#region -- Static --
public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 - ts;
return new TimeOfDay(dt2);
}
public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds != t2.TotalSeconds;
}
}
public static bool operator !=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 != dt2;
}
public static bool operator !=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 != dt2;
}
public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 + ts;
return new TimeOfDay(dt2);
}
public static bool operator <(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds < t2.TotalSeconds;
}
}
public static bool operator <(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 < dt2;
}
public static bool operator <(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 < dt2;
}
public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
if (t1 == t2) { return true; }
return t1.TotalSeconds <= t2.TotalSeconds;
}
}
public static bool operator <=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 <= dt2;
}
public static bool operator <=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 <= dt2;
}
public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else { return t1.Equals(t2); }
}
public static bool operator ==(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 == dt2;
}
public static bool operator ==(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 == dt2;
}
public static bool operator >(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds > t2.TotalSeconds;
}
}
public static bool operator >(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 > dt2;
}
public static bool operator >(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 > dt2;
}
public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds >= t2.TotalSeconds;
}
}
public static bool operator >=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 >= dt2;
}
public static bool operator >=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 >= dt2;
}
/// <summary>
/// Input examples:
/// 14:21:17 (2pm 21min 17sec)
/// 02:15 (2am 15min 0sec)
/// 2:15 (2am 15min 0sec)
/// 2/1/2017 14:21 (2pm 21min 0sec)
/// TimeOfDay=15:13:12 (3pm 13min 12sec)
/// </summary>
public static TimeOfDay Parse(string s)
{
// We will parse any section of the text that matches this
// pattern: dd:dd or dd:dd:dd where the first doublet can
// be one or two digits for the hour. But minute and second
// must be two digits.
Match m = _TodRegex.Match(s);
string text = m.Value;
string[] fields = text.Split(':');
if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
int hour = Convert.ToInt32(fields[0]);
int min = Convert.ToInt32(fields[1]);
int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;
return new TimeOfDay(hour, min, sec);
}
#endregion
private void Init(int hour, int minute, int second)
{
if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
Hour = hour;
Minute = minute;
Second = second;
}
private void Init(int hhmmss)
{
int hour = hhmmss / 10000;
int min = (hhmmss - hour * 10000) / 100;
int sec = (hhmmss - hour * 10000 - min * 100);
Init(hour, min, sec);
}
private void Init(DateTime dt)
{
Init(dt.Hour, dt.Minute, dt.Second);
}
}
}
Here is the code I've been using for programatically importing .cer files into a new KeyStore.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
//VERY IMPORTANT. SOME OF THESE EXIST IN MORE THAN ONE PACKAGE!
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
//Put everything after here in your function.
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);//Make an empty store
InputStream fis = /* insert your file path here */;
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
Certificate cert = cf.generateCertificate(bis);
trustStore.setCertificateEntry("fiddler"+bis.available(), cert);
}
Python3.exe is not defined in windows
Specify the path for required version of python when you need to used it by creating virtual environment for your project
virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment
virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment
then activate the environment using
.\environment\Scripts\activate.ps1
This is because Java Generics are implemented with Type Erasure.
Your methods would be translated, at compile time, to something like:
Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)
void add(Set ii);
void add(Set ss);
Both methods have the same signature without the type parameters, hence the error.
There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)
BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
next()
onnext
getValue()
method.Unique features of a subject compared to an observable are:
In addition, you can get an observable from behavior subject using the asObservable()
method on BehaviorSubject
.
Observable is a Generic, and BehaviorSubject
is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.
Example with BehaviorSubject:
// Behavior Subject
// a is an initial value. if there is a subscription
// after this, it would get "a" value immediately
let bSubject = new BehaviorSubject("a");
bSubject.next("b");
bSubject.subscribe(value => {
console.log("Subscription got", value); // Subscription got b,
// ^ This would not happen
// for a generic observable
// or generic subject by default
});
bSubject.next("c"); // Subscription got c
bSubject.next("d"); // Subscription got d
Example 2 with regular subject:
// Regular Subject
let subject = new Subject();
subject.next("b");
subject.subscribe(value => {
console.log("Subscription got", value); // Subscription wont get
// anything at this point
});
subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d
An observable can be created from both Subject
and BehaviorSubject
using subject.asObservable()
.
The only difference being you can't send values to an observable using next()
method.
In Angular services, I would use BehaviorSubject
for a data service as an angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component's subscription to this data.
Select * from dbo.sales group by shoppername having(count(Item) > 1)
This worked for me:
ssh -v [email protected] -p 443
There should be a default active record behavior on this I reckon. Querying dates is hard, especially when timezones are involved.
Anyway, I use:
scope :between, ->(start_date=nil, end_date=nil) {
if start_date && end_date
where("#{self.table_name}.created_at BETWEEN :start AND :end", start: start_date.beginning_of_day, end: end_date.end_of_day)
elsif start_date
where("#{self.table_name}.created_at >= ?", start_date.beginning_of_day)
elsif end_date
where("#{self.table_name}.created_at <= ?", end_date.end_of_day)
else
all
end
}
Go to
https://github.com/Darkseal/bootstrap4-glyphicons
download and include in your code
<link href="bootstrap4-glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet">
For those who want to get height and width of device even when the display is resized (dynamically & in real-time):
In that Component do: import { HostListener } from "@angular/core";
In the component's class body write:
@HostListener('window:resize', ['$event'])
onResize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
}
In the component's constructor
call the onResize
method to initialize the variables. Also, don't forget to declare them first.
constructor() {
this.onResize();
}
Complete code:
import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class FooComponent implements OnInit {
screenHeight: number;
screenWidth: number;
constructor() {
this.getScreenSize();
}
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
console.log(this.screenHeight, this.screenWidth);
}
}
This is a useful function for quick and easy xml parsing when an extension is not available:
<?php
/**
* Convert XML to an Array
*
* @param string $XML
* @return array
*/
function XMLtoArray($XML)
{
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $XML, $vals);
xml_parser_free($xml_parser);
// wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
$_tmp='';
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_level!=1 && $x_type == 'close') {
if (isset($multi_key[$x_tag][$x_level]))
$multi_key[$x_tag][$x_level]=1;
else
$multi_key[$x_tag][$x_level]=0;
}
if ($x_level!=1 && $x_type == 'complete') {
if ($_tmp==$x_tag)
$multi_key[$x_tag][$x_level]=1;
$_tmp=$x_tag;
}
}
// jedziemy po tablicy
foreach ($vals as $xml_elem) {
$x_tag=$xml_elem['tag'];
$x_level=$xml_elem['level'];
$x_type=$xml_elem['type'];
if ($x_type == 'open')
$level[$x_level] = $x_tag;
$start_level = 1;
$php_stmt = '$xml_array';
if ($x_type=='close' && $x_level!=1)
$multi_key[$x_tag][$x_level]++;
while ($start_level < $x_level) {
$php_stmt .= '[$level['.$start_level.']]';
if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
$php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
$start_level++;
}
$add='';
if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
if (!isset($multi_key2[$x_tag][$x_level]))
$multi_key2[$x_tag][$x_level]=0;
else
$multi_key2[$x_tag][$x_level]++;
$add='['.$multi_key2[$x_tag][$x_level].']';
}
if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
if ($x_type == 'open')
$php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
else
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
if (array_key_exists('attributes', $xml_elem)) {
if (isset($xml_elem['value'])) {
$php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
eval($php_stmt_main);
}
foreach ($xml_elem['attributes'] as $key=>$value) {
$php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
eval($php_stmt_att);
}
}
}
return $xml_array;
}
?>
(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)
You need to enclose your code within this wrapper:
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
echo %~nx0: running payload with parameters:
echo %*
echo ---------------------------------------------------
cd /d %2
shift
shift
rem put your code here
rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof
This makes batch file run itself as elevated user. It adds two parameters to the privileged code:
word payload
, to indicate this is payload call, i.e. already elevated. Otherwise
it would just open new processes over and over.
directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)
Note: Unfortunately, for some reason shift
does not work for %*
, so if you need
to pass actual arguments on, you will have to resort to the ugly notation I used
in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9
), which also brings in the limit of
maximum of 9 arguments
Try the ggplot2 function, cut_number
:
library(ggplot2)
x <- 1:10
n <- 3
cut_number(x, n) # labels = FALSE if you just want an integer result
#> [1] [1,4] [1,4] [1,4] [1,4] (4,7] (4,7] (4,7] (7,10] (7,10] (7,10]
#> Levels: [1,4] (4,7] (7,10]
# if you want it split into a list:
split(x, cut_number(x, n))
#> $`[1,4]`
#> [1] 1 2 3 4
#>
#> $`(4,7]`
#> [1] 5 6 7
#>
#> $`(7,10]`
#> [1] 8 9 10
Might be wrong but:
Tinyint is an integer between 0 and 255
bit is either 1 or 0
Therefore to me bit is the choice for booleans
It should be well noted that the use of live()
in jQuery has been deprecated since version 1.7
and has been removed in jQuery 1.9
. Instead, the use of on()
is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
document.body
and passing $selector as the second argument to on()
, elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body
rather than $selector
directly, which means $selector
can be added, removed and added again and will never load the event bound to it.off()
before on()
, this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.$(function() {...})
, this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready()
does not get fired for AJAX requests, while $(function() {...})
does.Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
Python 3 has the facility of Launching parallel tasks. This makes our work easier.
It has for thread pooling and Process pooling.
The following gives an insight:
ThreadPoolExecutor Example
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
Another Example
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()
All you need to use it the iterator.nextIndex() to return the current index that the iterator is on. This could be a bit easier than using your own counter variable (which still works also).
public static void main(String[] args) {
String[] str1 = {"list item 1", "list item 2", "list item 3", "list item 4"};
List<String> list1 = new ArrayList<String>(Arrays.asList(str1));
ListIterator<String> it = list1.listIterator();
int x = 0;
//The iterator.nextIndex() will return the index for you.
while(it.hasNext()){
int i = it.nextIndex();
System.out.println(it.next() + " is at index" + i);
}
}
This code will go through the list1 list one item at a time and print the item's text, then "is at index" then it will print the index that the iterator found it at. :)
Unless you want to talk to an SMTP server directly via telnet
you'd use commandline mailers like blat
:
blat -to [email protected] -f [email protected] -s "mail subject" ^
-server smtp.example.net -body "message text"
or bmail
:
bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
-a "mail subject" -b "message text"
You could also write your own mailer in VBScript or PowerShell.
make sure the input-name[]
is in inverted commas in the ruleset. Took me hours to figure that part out.
$('#testform').validate({
rules : {
"name[]": { required: true, minlength: 1 }
}
});
read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29
I'm not familiar with DB2, but have you tried COALESCE?
ie:
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
Adding more information to @Jesco
post.
Element.scrollIntoViewIfNeeded()
non-standard WebKit method
for Chrome, Opera, Safari browsers.
Element.scrollIntoView()
method scrolls the element on which it's called into the visible area of the browser window.Try the below code in mozilla.org
scrollIntoView()
link. Post to identify Browser
var xpath = '//*[@id="Notes"]';
ScrollToElement(xpath);
function ScrollToElement(xpath) {
var ele = $x(xpath)[0];
console.log( ele );
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
if (isChrome) { // Chrome
ele.scrollIntoViewIfNeeded();
} else {
var inlineCenter = { behavior: 'smooth', block: 'center', inline: 'start' };
ele.scrollIntoView(inlineCenter);
}
}
You can also take a look at this module for angular
Scikit-learn offers a function normalize()
that lets you apply various normalizations. The "make it sum to 1" is called L1-norm. Therefore:
from sklearn.preprocessing import normalize
matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
# array([[ 0., 3., 6.],
# [ 9., 12., 15.],
# [ 18., 21., 24.]])
normed_matrix = normalize(matrix, axis=1, norm='l1')
# [[ 0. 0.33333333 0.66666667]
# [ 0.25 0.33333333 0.41666667]
# [ 0.28571429 0.33333333 0.38095238]]
Now your rows will sum to 1.
Example an activity have 2 fragments and we use FragmentManager
to replace/add with addToBackstack
each fragment to a layout in activity
Use replace
Go Fragment1
Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume
Go Fragment2
Fragment2: onAttach
Fragment2: onCreate
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Pop Fragment2
Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach
Fragment1: onCreateView
Fragment1: onStart
Fragment1: onResume
Pop Fragment1
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach
Use add
Go Fragment1
Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume
Go Fragment2
Fragment2: onAttach
Fragment2: onCreate
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Pop Fragment2
Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach
Pop Fragment1
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
I found an extra
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.28.0" newVersion="2.2.28.0" />
</dependentAssembly>
in my web.config. removed that to get it to work. some other package I installed, and then removed caused the issue.
I am not sure in Razor but in ASPX you do:
<%if (item.Modify_Date != null)
{%>
<%=Html.Encode(String.Format("{0:D}", item.Modify_Date))%>
<%} %>
There must be something similar in Razor. Hopefully this will help someone.
My experience with Django is minimal but I do remember in The Django Book they have a chapter where they interview people running some of the larger Django applications. Here is a link. I guess it could provide some insights.
It says curse.com is one of the largest Django applications with around 60-90 million page views in a month.
Try with:
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
Or with:
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.
SELECT * FROM big_table ORDER BY A DESC LIMIT 10
When you initialize the array with int array[2]
, space for 2 integers is allocated; but the identifier array
simply points to the beginning of that space. When you then access array[3]
and array[4]
, the compiler then simply increments that address to point to where those values would be, if the array was long enough; try accessing something like array[42]
without initializing it first, you'll end up getting whatever value happened to already be in memory at that location.
Edit:
More info on pointers/arrays: http://home.netcom.com/~tjensen/ptr/pointers.htm
You can change the color of the navigation icon programmatically like this:
mToolbar.setNavigationIcon(getColoredArrow());
private Drawable getColoredArrow() {
Drawable arrowDrawable = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
Drawable wrapped = DrawableCompat.wrap(arrowDrawable);
if (arrowDrawable != null && wrapped != null) {
// This should avoid tinting all the arrows
arrowDrawable.mutate();
DrawableCompat.setTintList(wrapped, ColorStateList.valueOf(this.getResources().getColor(R.color.your_color)));
}
}
return wrapped;
}
You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text
tries to point to a string. Both groups
and items
are arrays.
Verbose version:
$.getJSON(url, function (data) {
// Iterate the groups first.
$.each(data.response.venue.tips.groups, function (index, value) {
// Get the items
var items = this.items; // Here 'this' points to a 'group' in 'groups'
// Iterate through items.
$.each(items, function () {
console.log(this.text); // Here 'this' points to an 'item' in 'items'
});
});
});
Or more simply:
$.getJSON(url, function (data) {
$.each(data.response.venue.tips.groups, function (index, value) {
$.each(this.items, function () {
console.log(this.text);
});
});
});
In the JSON you specified, the last one would be:
$.getJSON(url, function (data) {
// Get the 'items' from the first group.
var items = data.response.venue.tips.groups[0].items;
// Find the last index and the last item.
var lastIndex = items.length - 1;
var lastItem = items[lastIndex];
console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
console.log("Date: " + lastItem.createdAt);
console.log("Text: " + lastItem.text);
});
This would give you:
User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti
Regarding WMI and Registry:
There are three WMI event classes concerning registry:
But you need to be aware of these limitations:
With RegistryTreeChangeEvent and RegistryKeyChangeEvent there is no way of directly telling which values or keys actually changed. To do this, you would need to save the registry state before the event and compare it to the state after the event.
You can't use these classes with HKEY_CLASSES_ROOT or HKEY_CURRENT_USER hives. You can overcome this by creating a WMI class to represent the registry key to monitor:
Defining a Registry Class With Qualifiers
and use it with __InstanceOperationEvent derived classes.
So using WMI to monitor the Registry is possible, but less then perfect. The advantage is that it is possible to monitor the changes in 'real time'. Another advantage could be WMI permanent event subscription:
a method to monitor the Registry 'at all times', ie. event if your application is not running.
A couple solutions for async loading:
//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}
If you've already got jQuery on the page, just use:
$.getScript(url, successCallback)
*
Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready
before events can be bound to the elements.
It's not possible to tell specifically what your issue is without seeing the code.
The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.
If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).
* scripts loaded with $.getScript
will likely not be cached
For anyone who can use modern features such as the Promise
object, the loadScript
function has become significantly simpler:
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
Be aware that this version no longer accepts a callback
argument as the returned promise will handle callback. What previously would have been loadScript(src, callback)
would now be loadScript(src).then(callback)
.
This has the added bonus of being able to detect and handle failures, for example one could call...
loadScript(cdnSource)
.catch(loadScript.bind(null, localSource))
.then(successCallback, failureCallback);
...and it would handle CDN outages gracefully.
Netbeans here is a plugin for Netbeans dead code detector.
It would be better if it could link to and highlight the unused code. You can vote and comment here: Bug 181458 - Find unused public classes, methods, fields
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
More ad-hoc benchmark results:
$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'
real 2m10.397s
user 2m10.220s
sys 0m0.025s
$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'
real 2m1.724s
user 2m1.635s
sys 0m0.009s
$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'
real 1m21.000s
user 1m20.964s
sys 0m0.007s
IIS v10 (but this should be the same also for IIS 7.x)
Quick addition for people which are looking for respective max values
Max for maxAllowedContentLength
is: UInt32.MaxValue
4294967295 bytes
: ~4GB
Max for maxRequestLength
is: Int32.MaxValue
2147483647 bytes
: ~2GB
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!-- ~ 2GB -->
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- ~ 4GB -->
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Well I can see two solutions here:
1) Follow the Docs-Tkinter install for Python (for Windows):
Tkinter (and, since Python 3.1, ttk) are included with all standard Python distributions. It is important that you use a version of Python supporting Tk 8.5 or greater, and ttk. We recommend installing the "ActivePython" distribution from ActiveState, which includes everything you'll need.
In your web browser, go to Activestate.com, and follow along the links to download the Community Edition of ActivePython for Windows. Make sure you're downloading a 3.1 or newer version, not a 2.x version.
Run the installer, and follow along. You'll end up with a fresh install of ActivePython, located in, e.g. C:\python32
. From a Windows command prompt, or the Start Menu's "Run..." command, you should then be able to run a Python shell via:
% C:\python32\python
This should give you the Python command prompt. From the prompt, enter these two commands:
>>> import tkinter
>>> tkinter._test()
This should pop up a small window; the first line at the top of the window should say "This is Tcl/Tk version 8.5"; make sure it is not 8.4!
2) Uninstall 64-bit Python and install 32 bit Python.
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths
method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
From Oracle 12c R2 you could use COLLATE operator
:
The COLLATE operator determines the collation for an expression. This operator enables you to override the collation that the database would have derived for the expression using standard collation derivation rules.
The COLLATE operator takes one argument, collation_name, for which you can specify a named collation or pseudo-collation. If the collation name contains a space, then you must enclose the name in double quotation marks.
Demo:
CREATE TABLE tab1(i INT PRIMARY KEY, name VARCHAR2(100));
INSERT INTO tab1(i, name) VALUES (1, 'John');
INSERT INTO tab1(i, name) VALUES (2, 'Joe');
INSERT INTO tab1(i, name) VALUES (3, 'Billy');
--========================================================================--
SELECT /*csv*/ *
FROM tab1
WHERE name = 'jOHN' ;
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI = 'jOHN' ;
/*
"I","NAME"
1,"John"
*/
SELECT /*csv*/ *
FROM tab1
WHERE name LIKE 'j%';
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI LIKE 'j%';
/*
"I","NAME"
1,"John"
2,"Joe"
*/
Like that. Except char hi=hello;
should be char hi=hello.charAt(0)
. (Don't forget your break;
statements).
You can pass your component as a prop and use the same way you would use a component.
function General(props) {
...
return (<props.substitute a={A} b={B} />);
}
function SpecificA(props) { ... }
function SpecificB(props) { ... }
<General substitute=SpecificA />
<General substitute=SpecificB />
I just ran out of stack at work, it was a database and it was running some threads, basically the previous developer had thrown a big array on the stack, and the stack was low anyway. The software was compiled using Microsoft Visual Studio 2015.
Even though the thread had run out of stack, it silently failed and continued on, it only stack overflowed when it came to access the contents of the data on the stack.
The best advice i can give is to not declare arrays on the stack - especially in complex applications and particularly in threads, instead use heap. That's what it's there for ;)
Also just keep in mind it may not fail immediately when declaring the stack, but only on access. My guess is that the compiler declares stack under windows "optimistically", i.e. it will assume that the stack has been declared and is sufficiently sized until it comes to use it and then finds out that the stack isn't there.
Different operating systems may have different stack declaration policies. Please leave a comment if you know what these policies are.
To match anything other than letter or number or letter with diacritics like é
you could try this:
[^\wÀ-úÀ-ÿ]
And to replace:
var str = 'dfj,dsf7é@lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');
Inspired by the top post with support for diacritics
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find
to check the output string output
.
If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t
directly, you could set the output separator and it will be included automatically:
< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'
I also had problem understanding next() , but this helped
var app = require("express")();
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write("Hello");
next(); //remove this and see what happens
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write(" World !!!");
httpResponse.end();
});
app.listen(8080);
Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.
Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.
Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.
EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.
@Entity
is useful with model classes to denote that this is the entity or table
@Table
is used to provide any specific name to your table if you want to provide any different name
Note: if you don't use @Table
then hibernate consider that @Entity
is your table name by default and @Entity
must
@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable
{
}
This post fixed my issue. It's all about adding the following line in Application_Start()
in Global.asax
:
Database.SetInitializer<Models.YourDbContext>(null);
However it cause database recreation for every edit in your model and you may loose your data.
absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
If you really need to be sure that now()
has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update
but last_update
hasn't been updated yet)
you could do something like:
mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;
anyway I think that mysql is clever enough to ask for now()
only once per query.
To add a Visual Studio GUI reference, you can find the DropDownStyle
options under the Properties of the selected ComboBox:
Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent()
, like so:
this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
You can also cast a random value:
using System;
enum Test {
Value1,
Value2,
Value3
}
class Program {
public static void Main (string[] args) {
var max = Enum.GetValues(typeof(Test)).Length;
var value = (Test)new Random().Next(0, max - 1);
Console.WriteLine(value);
}
}
But you should use a better randomizer like the one in this library of mine.
WeakReference: objects that are only weakly referenced are collected at every GC cycle (minor or full).
SoftReference: when objects that are only softly referenced are collected depends on:
-XX:SoftRefLRUPolicyMSPerMB=N flag (default value is 1000, aka 1 second)
Amount of free memory in the heap.
Example:
Then object which is referenced only by SoftReference will be collected if last time when it was accessed is greater then 10 seconds.
NO 1+=2!=2
it means
you are going to add 1+2
.
But this will give you a syntax error.
Assume if a variable is int type int a=1
;
then
a+=2
; means a=1+2
; and increase the value of a from 1 to 3.
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
To stop or start mysql on most linux systems the following should work:
/etc/init.d/mysqld stop
/etc/init.d/mysqld start
The other answers look good for accessing the mysql client from the command line.
Good luck!
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
Annoying error. I solved it by plugging the cable directly into the iPad. For some reason the process would never finish if I had the iPad in Apple's pass-through stand.
Use the following will help
keytool -import -v -trustcacerts -alias keyAlias -file server.cer -keystore cacerts.jks -keypass changeit
function function_one()_x000D_
{_x000D_
alert("The function called 'function_one' has been called.")_x000D_
//Here u would like to call function_two._x000D_
function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
Here is an example of passing mode as optional parameter
void myfunc(int blah, int mode = 0)
{
if (mode == 0)
do_something();
else
do_something_else();
}
you can call myfunc in both ways and both are valid
myfunc(10); // Mode will be set to default 0
myfunc(10, 1); // Mode will be set to 1
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
Another option, again assuming that "edit" means you want to modify in place:
void topntail(char *str) {
size_t len = strlen(str);
assert(len >= 2); // or whatever you want to do with short strings
memmove(str, str+1, len-2);
str[len-2] = 0;
}
This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.
There are many ways to do this if you want to write css then add following
.modal-dialog{
display: table
}
In case if you want to add inline
<div class="modal-dialog" style="display:table;">
//enter code here
</div>
Don't add display:table;
to modal-content class. it done your job but disposition your modal for large size see following screenshots.
first image is if you add style to modal-dialog
if you add style to modal-content. it looks dispositioned.
If your HTML is well formed, I think this is a better solution:
create function dbo.StripHTML( @text varchar(max) ) returns varchar(max) as
begin
declare @textXML xml
declare @result varchar(max)
set @textXML = REPLACE( @text, '&', '' );
with doc(contents) as
(
select chunks.chunk.query('.') from @textXML.nodes('/') as chunks(chunk)
)
select @result = contents.value('.', 'varchar(max)') from doc
return @result
end
go
select dbo.StripHTML('This <i>is</i> an <b>html</b> test')
Add both of those for the theme you use:
<item name="windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
For your information, the python equivalent is:
imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:
create table foo (
bar int[] default '{}'
);
select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
create index on foo using gin (bar); -- allows to use an index in the above query
But as the prior answer suggests, it will be better to normalize properly.
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
The best approach depends on what you want to do:
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
To add to the other answers: If yout want the 0000-00-00
string, you can use noDatetimeStringSync=true
(with the caveat of sacrificing timezone conversion).
The official MySQL bug: https://bugs.mysql.com/bug.php?id=47108.
Also, for history, JDBC used to return NULL
for 0000-00-00
dates but now return an exception by default.
Source
Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.
javascript:location.href=%22googlechrome%22+location.href.substring(4);
Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.
Works for me.
Put this line in activity declaration time in manifest.xml
<android:windowSoftInputMode="adjustPan">
Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions:
method;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification:
method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
With quotes:
cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g'
gives output as:
"CentOS Linux 7 (Core)"
Without quotes:
cat /etc/*-release | grep "PRETTY_NAME" | sed 's/PRETTY_NAME=//g' | sed 's/"//g'
gives output as:
CentOS Linux 7 (Core)
None of the proposed solutions here worked for me, but what eventually got it working was adding the following to elasticsearch.yml
network:
host: 0.0.0.0
http:
port: 9200
After that, I restarted the service and now I can curl
it from both within the VM and externally. For some odd reason, I had to try a few different variants of a curl
call inside the VM before it worked:
curl localhost:9200
curl http://localhost:9200
curl 127.0.0.1:9200
Note: I'm using Elasticsearch 5.5 on Ubuntu 14.04
it's nil
in Ruby, not null
. And it's enough to say if @objectname
to test whether it's not nil. And no then
. You can find more on if
syntax here:
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;