SELECT date1 - date2
FROM some_table
returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So
SELECT (date1 - date2) * 24 * 60 difference_in_minutes
FROM some_table
should be what you're looking for
Please check: http://man7.org/linux/man-pages/man5/proc.5.html
address perms offset dev inode pathname
00400000-00452000 r-xp 00000000 08:02 173521 /usr/bin/dbus-daemon
The address field is the address space in the process that the mapping occupies.
The perms field is a set of permissions:
r = read
w = write
x = execute
s = shared
p = private (copy on write)
The offset field is the offset into the file/whatever;
dev is the device (major:minor);
inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).
The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).
Under Linux 2.0, there is no field giving pathname.
You can apply a centering to any View, including a Layout, by using the XML attribute android:layout_gravity". You probably want to give it the value "center".
You can find a reference of possible values for this option here: http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#attr_android:layout_gravity
you can do this:
<div class="picture1"> </div>
and put this into your css file:
div.picture1 {
width:100px; /*width of your image*/
height:100px; /*height of your image*/
background-image:url('yourimage.file');
margin:0; /* If you want no margin */
padding:0; /*if your want to padding */
}
otherwise, just use them as plain
Simply using sort, use coloumn number based on which you want to sort.
a = np.array([1,1], [1,-1], [-1,1], [-1,-1]])
print (a)
a=a.tolist()
a = np.array(sorted(a, key=lambda a_entry: a_entry[0]))
print (a)
Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.
View State on the other hand is information specific to particular web page. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time - dont give him a clean page every time he posts back. Check this page for more.
Here is a simple program to find the missing numbers in an integer array
ArrayList<Integer> arr = new ArrayList<Integer>();
int a[] = { 1,3,4,5,6,7,10 };
int j = a[0];
for (int i=0;i<a.length;i++)
{
if (j==a[i])
{
j++;
continue;
}
else
{
arr.add(j);
i--;
j++;
}
}
System.out.println("missing numbers are ");
for(int r : arr)
{
System.out.println(" " + r);
}
Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.
Here is my complete, cross browser solution:
In the iframe page:
function printPage() { print(); }
In the main page
function printIframe(id)
{
var iframe = document.frames
? document.frames[id]
: document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!
It is very simple using ES6
const factorial = n => n ? (n * factorial(n-1)) : 1;
See an example here
Firstly you should test your python idle to see if you have tkinter:
import tkinter
tkinter._test()
Trying typing it, copy paste doesn't work.
So after 20 hours of trying every way that recommended on those websites figured out that you can't use "tkinter.py" or any other file name that contains "tkinter..etc.py". If you have the same problem, just change the file name.
Use nssm.exe but remember to set the AppDirectory or any required libraries or resources will not be accessible. By default nssm set the current working directory to the that of the application, java.exe, not the jar. So do this to create a batch script:
pushd <path-to-jar>
nssm.exe install "<service-name>" "<path-to-java.exe>" "-jar <name-of-jar>"
nssm.exe set "<service-name>" AppDirectory "<path-to-jar>"
This should fix the service paused issue.
add_index :table_name, :column_name, unique: true
To index multiple columns together, you pass an array of column names instead of a single column name.
I had this issue when using the history API.
window.history.pushState(null, null, URL);
Even with a local server (localhost), you want to add 'http://' to your URL so that you have something similar to:
http://localhost...
We have two options.
Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.
Set HEADER_SEARCH_PATHS
parameter in build settings on project info. I added "${SRCROOT}"
here without recursion. This setting works well for most projects.
About 2nd option:
Xcode uses Clang which has GCC compatible command set.
GCC has an option -Idir
which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS
in Xcode project build setting.
However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.
But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space
if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}"
.
Or just use .
to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.
The ${SRCROOT}
is predefined value by Xcode. This means source directory. You can find more values in Reference document.
PS. Actually you don't have to use braces {}
. I get same result with $SRCROOT
. If you know the difference, please let me know.
nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size
by sending a 413 response and closing the connection.
Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.
If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue
header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large
response rather than 100 Continue
if Content-Length
exceeds the maximum body size.
def func(a, b, c, d):
return a + b * c % d
map(lambda x: func(*x), [[1,2,3,4], [5,6,7,8]])
By wrapping the function call with a lambda and using the star unpack, you can do map with arbitrary number of arguments.
As already stated ??!??!
is essentially two trigraphs (??!
and ??!
again) mushed together that get replaced-translated to ||
, i.e the logical OR, by the preprocessor.
The following table containing every trigraph should help disambiguate alternate trigraph combinations:
Trigraph Replaces
??( [
??) ]
??< {
??> }
??/ \
??' ^
??= #
??! |
??- ~
Source: C: A Reference Manual 5th Edition
So a trigraph that looks like ??(??)
will eventually map to []
, ??(??)??(??)
will get replaced by [][]
and so on, you get the idea.
Since trigraphs are substituted during preprocessing you could use cpp
to get a view of the output yourself, using a silly trigr.c
program:
void main(){ const char *s = "??!??!"; }
and processing it with:
cpp -trigraphs trigr.c
You'll get a console output of
void main(){ const char *s = "||"; }
As you can notice, the option -trigraphs
must be specified or else cpp
will issue a warning; this indicates how trigraphs are a thing of the past and of no modern value other than confusing people who might bump into them.
As for the rationale behind the introduction of trigraphs, it is better understood when looking at the history section of ISO/IEC 646:
ISO/IEC 646 and its predecessor ASCII (ANSI X3.4) largely endorsed existing practice regarding character encodings in the telecommunications industry.
As ASCII did not provide a number of characters needed for languages other than English, a number of national variants were made that substituted some less-used characters with needed ones.
(emphasis mine)
So, in essence, some needed characters (those for which a trigraph exists) were replaced in certain national variants. This leads to the alternate representation using trigraphs comprised of characters that other variants still had around.
To make it work in Chrome (and bootply) i had to change code in this way:
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<input type="text" class="form-control" placeholder="year" />
<input type="text" class="form-control" placeholder="month" />
<input type="text" class="form-control" placeholder="day" />
</div>
</div>
</div>
</form>
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach
for st in mylist:
if len(st)==max_length:...
Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.
A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).
It's a nit, but enough to cause unit tests to fail.
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
Install Qt
sudo apt-get install build-essential
sudo apt-get install qtcreator
sudo apt-get install qt5-default
Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:
sudo apt-get install qt5-doc
sudo apt-get install qt5-doc-html qtbase5-doc-html
sudo apt-get install qtbase5-examples
Restart Qt Creator to make the documentation available.
Error while loading shared libraries
Problem:
radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory
Reason:
Actually, the libraries have been installed in a place where dynamic linker cannot find it.
Solution:
While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:
sudo /sbin/ldconfig -v
http://www.lucidarme.me/how-install-documentation-for-qt-creator/
https://ubuntuforums.org/showthread.php?t=2199929
You can abstract the time measuring mechanism and have each callable's run time measured with minimal extra code, just by being called through a timer structure. Plus, at compile time you can parametrize the timing type (milliseconds, nanoseconds etc).
Thanks to the review by Loki Astari and the suggestion to use variadic templates. This is why the forwarded function call.
#include <iostream>
#include <chrono>
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F, typename ...Args>
static typename TimeT::rep execution(F&& func, Args&&... args)
{
auto start = std::chrono::steady_clock::now();
std::forward<decltype(func)>(func)(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::steady_clock::now() - start);
return duration.count();
}
};
int main() {
std::cout << measure<>::execution(functor(dummy)) << std::endl;
}
According to the comment by Howard Hinnant it's best not to escape out of the chrono system until we have to. So the above class could give the user the choice to call count
manually by providing an extra static method (shown in C++14)
template<typename F, typename ...Args>
static auto duration(F&& func, Args&&... args)
{
auto start = std::chrono::steady_clock::now();
std::forward<decltype(func)>(func)(std::forward<Args>(args)...);
return std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now()-start);
}
// call .count() manually later when needed (eg IO)
auto avg = (measure<>::duration(func) + measure<>::duration(func)) / 2.0;
and be most useful for clients that
"want to post-process a bunch of durations prior to I/O (e.g. average)"
The complete code can be found here. My attempt to build a benchmarking tool based on chrono is recorded here.
If C++17's std::invoke
is available, the invocation of the callable in execution
could be done like this :
invoke(forward<decltype(func)>(func), forward<Args>(args)...);
to provide for callables that are pointers to member functions.
Since style A
is not allowed in C++ and you don't want style B
then how about using style BX
:
FooBar fb = { /*.foo=*/ 12, /*.bar=*/ 3.4 }; // :)
At least help at some extent.
This works using grep without needing to use perl or find.
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
You can do this using the ResourceManager
:
public bool info(string channel)
{
object o = Properties.Resources.ResourceManager.GetObject(channel);
if (o is Image)
{
channelPic.Image = o as Image;
return true;
}
return false;
}
I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.
After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(
Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.
As others pointed out, it seems like you can't override nested text-decoration styles... BUT you can change the text-decoration-color.
As a hack, I changed the color to be transparent:
text-decoration-color: transparent;
In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
I know its been a while since the original post but I like using CTE's and this worked for me:
WITH cte_table_a
AS
(
SELECT [id] [id]
, MAX([value]) [value]
FROM table_a
GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN cte_table_a
ON table_b.id = cte_table_a.id
The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago
I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.
ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV
Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.
For example:
mcdiff file1 file2
Enjoy!
Since creating a tag per version is the best practice, you may want to partition your changelog per version. In that case, this command could help you:
git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B
For a string of length 1 you can simply perform isdigit()
or isalpha()
If your string length is greater than 1, you can make a function something like..
def isinteger(a):
try:
int(a)
return True
except ValueError:
return False
The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.
When you say modify the page and return the modified page
what do you mean?
Starting in API 21 the notion of weight was added to GridLayout.
To support older android devices, you can use the GridLayout from the v7 support library.
compile 'com.android.support:gridlayout-v7:22.2.1'
The following XML gives an example of how you can use weights to fill the screen width.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:id="@+id/choice_grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:padding="4dp"
grid:alignmentMode="alignBounds"
grid:columnCount="2"
grid:rowOrderPreserved="false"
grid:useDefaultMargins="true">
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile1" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile2" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile3" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile4" />
</android.support.v7.widget.GridLayout>
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c, i) {
return <td key={i}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
This will sove the problem.
1- There is no way to actually destroy an object in javascript, but using delete
, we could remove a reference from an object:
var obj = {};
obj.mypointer = null;
delete obj.mypointer;
2- The important point about the delete
keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete
keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.
3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}]
overriding the value of the array like array = []
would remove the references to the two objects inside the array and those two objects would be marked as collectible.
4- for your solution the easiest way is just this:
var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;
As mentioned above, either setting storage.instance = null
or delete storage.instance
would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null
then the storage object still has a property called instance (with the value null). If you delete storage.instance
then the storage object no longer has a property named instance.
and WHAT ABOUT destroy method ??
the paradoxical point here is if you use instance.destroy
in the destroy function you have no access to the actual instance
pointer, and it won't let you delete it.
The only way is to pass the reference to the destroy function and then delete it:
// Class constructor
var Class = function () {
this.destroy = function (baseObject, refName) {
delete baseObject[refName];
};
};
// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined
BUT if I were you I would simply stick to the first solution and delete the object like this:
storage.instance = null;
// OR
delete storage.instance;
WOW it was too much :)
Put [unowned self]
before (text: String)...
in your closure. This is called a capture list and places ownership instructions on symbols captured in the closure.
Enter "SA" instead of "sa" in the owner textbox. This worked for me.
You can do it in a hackish way. Careful using the sqlcmd
hack. If the data has double quotes or commas you will run into trouble.
You can use a simple script to do it properly:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Data Exporter '
' '
' Description: Allows the output of data to CSV file from a SQL '
' statement to either Oracle, SQL Server, or MySQL '
' Author: C. Peter Chen, http://dev-notes.com '
' Version Tracker: '
' 1.0 20080414 Original version '
' 1.1 20080807 Added email functionality '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr
'''''''''''''''''
' Configuration '
'''''''''''''''''
dbType = "oracle" ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost" ' Hostname of the database server
dbName = "dbname" ' Name of the database/SID
dbUser = "username" ' Name of the user
dbPass = "password" ' Password of the above-named user
outputFile = "c:\output.csv" ' Path and file name of the output CSV file
email = "[email protected]" ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
subj = "Email Subject" ' The subject of your email; required only if you send the CSV over email
body = "Put a message here!" ' The body of your email; required only if you send the CSV over email
smtp = "mail.server.com" ' Name of your SMTP server; required only if you send the CSV over email
smtpPort = 25 ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual" ' SQL statement you wish to execute
'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''
dim fso, conn
'Create filesystem object
set fso = CreateObject("Scripting.FileSystemObject")
'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then
conn.open("Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then
conn.open("Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then
conn.open("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if
' Subprocedure to generate data. Two parameters:
' 1. fPath=where to create the file
' 2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
dim a, showList, intcount
set a = fso.createtextfile(fPath)
set showList = conn.execute(sqlstr)
for intcount = 0 to showList.fields.count -1
if intcount <> showList.fields.count-1 then
a.write """" & showList.fields(intcount).name & ""","
else
a.write """" & showList.fields(intcount).name & """"
end if
next
a.writeline ""
do while not showList.eof
for intcount = 0 to showList.fields.count - 1
if intcount <> showList.fields.count - 1 then
a.write """" & showList.fields(intcount).value & ""","
else
a.write """" & showList.fields(intcount).value & """"
end if
next
a.writeline ""
showList.movenext
loop
showList.close
set showList = nothing
set a = nothing
end sub
' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)
' Close
set fso = nothing
conn.close
set conn = nothing
if email <> "" then
dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Test Email from vbs"
objMessage.From = email
objMessage.To = email
objMessage.TextBody = "Please see attached file."
objMessage.AddAttachment outputFile
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort
objMessage.Configuration.Fields.Update
objMessage.Send
end if
'You're all done!! Enjoy the file created.
msgbox("Data Writer Done!")
Use the -ExpandProperty
flag of Select-Object
$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority
Update to answer the other question:
Note that you can as well just access the property:
$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
So to get multiple of these into variables:
$var=Get-WSManInstance -enumerate wmicimv2/win32_process
$prio = $var.Priority
$pid = $var.ProcessID
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
You should use .Load
and not .LoadXML
"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."
ref : Link
As described here http://developer.android.com/reference/java/util/regex/Pattern.html
Patterns are compiled regular expressions. In many cases, convenience methods such as
String.matches
,String.replaceAll
andString.split
will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
public class RegularExpressionTest {
public static void main(String[] args) {
System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$#@!#$%^&*()("));
System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}
public static String getOnlyDigits(String s) {
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
public static String getOnlyStrings(String s) {
Pattern pattern = Pattern.compile("[^a-z A-Z]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
}
Result
String is = one
Number is = 9196390097
This error also occurs if you create a sub or function in a 'Microsoft Excel Object' (like Sheet1, Sheet2, ...) instead to create it in a Module.
For example:
you create with VBA a button and set .OnAction = 'btn_action'
. And Sub btn_action
you placed into the Sheet object instead into a Module.
For Angular 2 - 5 refer the article Multiple Environment in angular
For Angular 6 use ng serve --configuration=dev
Note: Refer the same article for angular 6 as well. But wherever you find
--env
instead use--configuration
. That's works well for angular 6.
I fixed this bug, I use the commitNow()
replace commit()
.
mFragment.getChildFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment_container,fragment)
.commitNowAllowingStateLoss();
The commitNow
is a sync method, the commit()
method is an async method.
For anyone struggling behind a corporate firewall, as well as issues with SSL (unable to get local issuer certificate), here are some steps you can try:
If you are not concerned about SSL, then you can follow the advice of many previous contributors by setting your proxies and changing the registry to the non-secure version:
npm config set proxy http://username:password@proxyname:port
npm config set https-proxy http://username:password@proxyname:port
npm config set registry http://registry.npmjs.org/
A quick "gotcha" here, my proxy credentials are the same for secured and non-secured requests (notice how I left my protocol as http:// for the https-proxy configuration). This may be the same for you, and it may not.
If you want to keep SSL, and don't want to use strict-ssl=false
, then you have more work to do. For me, I am behind a corporate firewall and we are using self-signed certificates, so I receive the error unable to get local issuer certificate
. If you are in the same boat as me, then you will need to set the cafile=
option in the npm config file. First, you need to create a PEM file which holds information about your self-signed certificates. If you do not know how to do that, here are instructions for a Windows environment without using 3rd party software:
We need to explicitly indicate which certificates should be trusted because we are using self signing certificates. For my example, I navigated to www.google.com using Chrome so I could grab the certificates.
In Chrome, go to Inspect -> Security -> View Certificate. You will see all of the certificates that allow the SSL connection. Notice how these certificates are self signed. The blurred-out part is my company, and we are not a Certified Authority. You can export the full certificate path as a P7B file, or you can export the certificates individually as CER files (base64 encoding). Exporting the full path as P7B doesn't do you much good because you will in-turn need to open this file in a certificate manager and export as individual CER files anyway. In Windows, double-clicking the P7B file will open the Certificate Manager application.
Exporting as CER (Base 64) is really a text file in the following format:
-----BEGIN CERTIFICATE-----
MIIGqzCCBZOgAwIBAgITIwAAABWhFPjwukYhTAADAAAAFTANBgkqhkiG9w0BAQUF
ADBFMRMwEQYKCZImiZPyLGQBGRYDY29tMRYwFAYKCZImiZPyLGQBGRYGaXJ2aW5n
b0pvCkNmjWzaNNUg2hYET+pP5nP75aRu+kPRl9UnlQ....rest of certificate...
-----END CERTIFICATE-----
To create our PEM file, we simply need to stack these certificates on top of each other into a single file and change the extension to .pem. I used notepad to do this.
You stack the certificates in reverse order from the certificate path. So above, I would start with *.google.com then paste Websense below it, then Issuing CA 1 etc. This way the certificates are parsed from the top to the bottom searching for the appropriate Root CA. Simply including the Root CA will not work, but we also do not need to include all the certificates. From the above path, I only need to include those certificates that come before the Websense certificate (Issuing CA 1, Policy CA, Root CA).
Once these self signed certs are saved to a PEM file, we are ready to instruct npm to use these certificates as our trusted CA. Simply set the config file and you should be good to go:
npm config set cafile "C:\yourcerts.pem"
Now, with your proxies set (http and https), and the registry set to https://registry.npmjs.org
, you should be able to install packages behind a corporate firewall with self-signed certificates without nuking the strict-ssl
setting.
Another way is
> length(z[z==TRUE])
[1] 498
While sum(z)
is nice and short, for me length(z[z==TRUE])
is more self explaining. Though, I think with a simple task like this it does not really make a difference...
If it is a large vector, you probably should go with the fastest solution, which is sum(z)
. length(z[z==TRUE])
is about 10x slower and table(z)[TRUE]
is about 200x slower than sum(z)
.
Summing up, sum(z)
is the fastest to type and to execute.
You can't do this cross-browser with the confirm() function or similar. I highly suggest you use something like the jQuery UI dialog feature to create an HTML dialog box instead.
Quite straight. This can be a good starting point
int makeDir(char *fullpath, mode_t permissions){
int i=0;
char *arrDirs[20];
char aggrpaz[255];
arrDirs[i] = strtok(fullpath,"/");
strcpy(aggrpaz, "/");
while(arrDirs[i]!=NULL)
{
arrDirs[++i] = strtok(NULL,"/");
strcat(aggrpaz, arrDirs[i-1]);
mkdir(aggrpaz,permissions);
strcat(aggrpaz, "/");
}
i=0;
return 0;
}
You parse this function a full path plus the permissions you want, i.e S_IRUSR, for a full list of modes go here https://techoverflow.net/2013/04/05/how-to-use-mkdir-from-sysstat-h/
The fullpath string will be split by the "/" character and individual dirs will be appended to the aggrpaz string one at a time. Each loop iteration calls the mkdir function, passing it the aggregate path so far plus the permissions. This example can be improved, I am not checking the mkdir function output and this function only works with absolute paths.
In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.
You need a table variable:
declare @values table
(
Value varchar(1000)
)
insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')
select blah
from foo
where myField in (select value from @values)
this error basically comes when you use the object before using it.
Add Event Listener
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
// - Code to execute when all DOM content is loaded.
// - including fonts, images, etc.
});
</script>
Update March 2017
window.addEventListener('load', function() {
console.log('All assets are loaded')
})
$(window).on('load', function() {
console.log('All assets are loaded')
})
Use HH
for 24 hour hours format:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Or the tt
format specifier for the AM/PM
part:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")
Take a look at the custom Date and Time format strings documentation.
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
This is not possible with a switch
statement in Java. Check for null
before the switch
:
if (i == null) {
doSomething0();
} else {
switch (i) {
case 1:
// ...
break;
}
}
You can't use arbitrary objects in switch
statements*. The reason that the compiler doesn't complain about switch (i)
where i
is an Integer
is because Java auto-unboxes the Integer
to an int
. As assylias already said, the unboxing will throw a NullPointerException
when i
is null
.
* Since Java 7 you can use String
in switch
statements.
More about switch
(including example with null variable) in Oracle Docs - Switch
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"
One of the most simple and understandable solution is:
IF COL_LENGTH('Table_Name','Column_Name') IS NULL
BEGIN
-- Column Not Exists, implement your logic
END
ELSE
BEGIN
-- Column Exists, implement your logic
END
put an overlay on the page
#loading-mask {
background-color: white;
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 9999;
}
and then delete that element in a window.onload
handler or, hide it
window.onload=function() {
document.getElementById('loading-mask').style.display='none';
}
Of course you should use your javascript library (jquery,prototype..) specific onload handler if you are using a library.
I was annoyed that you had to always include the namespace and the folder in the string. I wanted to simplify the access to the embedded resources. This is why I wrote this little class. Feel free to use and improve!
Usage:
using(Stream stream = EmbeddedResources.ExecutingResources.GetStream("filename.txt"))
{
//...
}
Class:
public class EmbeddedResources
{
private static readonly Lazy<EmbeddedResources> _callingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetCallingAssembly()));
private static readonly Lazy<EmbeddedResources> _entryResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetEntryAssembly()));
private static readonly Lazy<EmbeddedResources> _executingResources = new Lazy<EmbeddedResources>(() => new EmbeddedResources(Assembly.GetExecutingAssembly()));
private readonly Assembly _assembly;
private readonly string[] _resources;
public EmbeddedResources(Assembly assembly)
{
_assembly = assembly;
_resources = assembly.GetManifestResourceNames();
}
public static EmbeddedResources CallingResources => _callingResources.Value;
public static EmbeddedResources EntryResources => _entryResources.Value;
public static EmbeddedResources ExecutingResources => _executingResources.Value;
public Stream GetStream(string resName) => _assembly.GetManifestResourceStream(_resources.Single(s => s.Contains(resName)));
}
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('manufacturer');
$products->addFieldToFilter(array(
array('attribute'=>'manufacturer', 'eq'=> $optionId,
));
echo "<li>" . $value . " - (" . $optionId . ") - (Products: ".count($products).")</li>";
}
echo "</ul>";
}
After spending years dealing with this problem in WPF, I finally figured out the standard way of implementing dialogs in WPF. Here are the advantages of this approach:
So what's the key. It is DI + IoC.
Here is how it works. I'm using MVVM Light, but this approach may be extended to other frameworks as well:
Add an interface IDialogService to VM project:
public interface IDialogService
{
void ShowMessage(string msg, bool isError);
bool AskBooleanQuestion(string msg);
string AskStringQuestion(string msg, string default_value);
string ShowOpen(string filter, string initDir = "", string title = "");
string ShowSave(string filter, string initDir = "", string title = "", string fileName = "");
string ShowFolder(string initDir = "");
bool ShowSettings();
}
Expose a public static property of IDialogService
type in your ViewModelLocator
, but leave registration part for the View layer to perform. This is the key.:
public static IDialogService DialogService => SimpleIoc.Default.GetInstance<IDialogService>();
Add an implementation of this interface in the App project.
public class DialogPresenter : IDialogService
{
private static OpenFileDialog dlgOpen = new OpenFileDialog();
private static SaveFileDialog dlgSave = new SaveFileDialog();
private static FolderBrowserDialog dlgFolder = new FolderBrowserDialog();
/// <summary>
/// Displays a simple Information or Error message to the user.
/// </summary>
/// <param name="msg">String text that is to be displayed in the MessageBox</param>
/// <param name="isError">If true, Error icon is displayed. If false, Information icon is displayed.</param>
public void ShowMessage(string msg, bool isError)
{
if(isError)
System.Windows.MessageBox.Show(msg, "Your Project Title", MessageBoxButton.OK, MessageBoxImage.Error);
else
System.Windows.MessageBox.Show(msg, "Your Project Title", MessageBoxButton.OK, MessageBoxImage.Information);
}
/// <summary>
/// Displays a Yes/No MessageBox.Returns true if user clicks Yes, otherwise false.
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public bool AskBooleanQuestion(string msg)
{
var Result = System.Windows.MessageBox.Show(msg, "Your Project Title", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
return Result;
}
/// <summary>
/// Displays Save dialog. User can specify file filter, initial directory and dialog title. Returns full path of the selected file if
/// user clicks Save button. Returns null if user clicks Cancel button.
/// </summary>
/// <param name="filter"></param>
/// <param name="initDir"></param>
/// <param name="title"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public string ShowSave(string filter, string initDir = "", string title = "", string fileName = "")
{
if (!string.IsNullOrEmpty(title))
dlgSave.Title = title;
else
dlgSave.Title = "Save";
if (!string.IsNullOrEmpty(fileName))
dlgSave.FileName = fileName;
else
dlgSave.FileName = "";
dlgSave.Filter = filter;
if (!string.IsNullOrEmpty(initDir))
dlgSave.InitialDirectory = initDir;
if (dlgSave.ShowDialog() == DialogResult.OK)
return dlgSave.FileName;
else
return null;
}
public string ShowFolder(string initDir = "")
{
if (!string.IsNullOrEmpty(initDir))
dlgFolder.SelectedPath = initDir;
if (dlgFolder.ShowDialog() == DialogResult.OK)
return dlgFolder.SelectedPath;
else
return null;
}
/// <summary>
/// Displays Open dialog. User can specify file filter, initial directory and dialog title. Returns full path of the selected file if
/// user clicks Open button. Returns null if user clicks Cancel button.
/// </summary>
/// <param name="filter"></param>
/// <param name="initDir"></param>
/// <param name="title"></param>
/// <returns></returns>
public string ShowOpen(string filter, string initDir = "", string title = "")
{
if (!string.IsNullOrEmpty(title))
dlgOpen.Title = title;
else
dlgOpen.Title = "Open";
dlgOpen.Multiselect = false;
dlgOpen.Filter = filter;
if (!string.IsNullOrEmpty(initDir))
dlgOpen.InitialDirectory = initDir;
if (dlgOpen.ShowDialog() == DialogResult.OK)
return dlgOpen.FileName;
else
return null;
}
/// <summary>
/// Shows Settings dialog.
/// </summary>
/// <returns>true if User clicks OK button, otherwise false.</returns>
public bool ShowSettings()
{
var w = new SettingsWindow();
MakeChild(w); //Show this dialog as child of Microsoft Word window.
var Result = w.ShowDialog().Value;
return Result;
}
/// <summary>
/// Prompts user for a single value input. First parameter specifies the message to be displayed in the dialog
/// and the second string specifies the default value to be displayed in the input box.
/// </summary>
/// <param name="m"></param>
public string AskStringQuestion(string msg, string default_value)
{
string Result = null;
InputBox w = new InputBox();
MakeChild(w);
if (w.ShowDialog(msg, default_value).Value)
Result = w.Value;
return Result;
}
/// <summary>
/// Sets Word window as parent of the specified window.
/// </summary>
/// <param name="w"></param>
private static void MakeChild(System.Windows.Window w)
{
IntPtr HWND = Process.GetCurrentProcess().MainWindowHandle;
var helper = new WindowInteropHelper(w) { Owner = HWND };
}
}
ShowMessage
, AskBooleanQuestion
etc.), others are specific to this project and use custom Window
s. You can add more custom windows in the same fashion. The key is to keep UI-specific elements in the View layer and just expose the returned data using POCOs in the VM layer.Perform IoC Registration your interface in the View layer using this class. You can do this in your main view's constructor (after InitializeComponent()
call):
SimpleIoc.Default.Register<IDialogService, DialogPresenter>();
There you go. You now have access to all your dialog functionality at both VM and View layers. Your VM layer can call these functions like this:
var NoTrump = ViewModelLocator.DialogService.AskBooleanQuestion("Really stop the trade war???", "");
IDialogService
in your Test project and register that class in IoC in the constructor your test class.Microsoft.Win32
to access Open and Save dialogs. I have left them out because there is also a WinForms version of these dialogs available, plus someone might want to create their own version. Also note that some of the identifier used in DialogPresenter
are names of my own windows (e.g. SettingsWindow
). You'll need to either remove them from both the interface and implementation or provide your own windows.DispatcherHelper.Initialize()
early in your application's life cycle.Except for DialogPresenter
which is injected in the View layer, other ViewModals should be registered in ViewModelLocator
and then a public static property of that type should be exposed for the View layer to consume. Something like this:
public static SettingsVM Settings => SimpleIoc.Default.GetInstance<SettingsVM>();
For the most part, your dialogs should not have any code-behind for stuff like binding or setting DataContext etc. You shouldn't even pass things as constructor parameters. XAML can do that all for you, like this:
<Window x:Class="YourViewNamespace.SettingsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:YourViewProject"
xmlns:vm="clr-namespace:YourVMProject;assembly=YourVMProject"
DataContext="{x:Static vm:ViewModelLocator.Settings}"
d:DataContext="{d:DesignInstance Type=vm:SettingsVM}" />
DataContext
this way gives you all kinds of design-time benefits such as Intellisense and auto-completion.Hope that helps everyone.
As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST
contains the port, while SERVER_NAME
does not.
$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'
(At least that's what I've noticed in Apache port-based virtualhosts)
Note that HTTP_HOST
does not contain :443
when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).
As others have noted, the two also differ when using IPv6:
$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'
If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0
CSS:
.parent{
width:100%;
position:relative;
}
#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}
Javascript:
$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );
Please check the permissions for mentioned login name in SQL server management studio make it sysadmin checkbox tick and then make Integrated Security=False
in the .config file.
Fire 2 commands on the client machine
ipconfig /flushdns
klist purge.
install kerbarose configuration manager on the client computer.
Finally, Restart client machine and main SQL server services. Run the application on the client machine. This Works 100% correctly.
something like
position:relative;
top:-5px;
just on the inline element itself works for me. Have to play with the top to get it centered vertically...
For the most accurate rounding, create this function:
function round(value, decimals) {
return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
}
and use it to round to 2 decimal places:
console.log("seeked to " + round(1.005, 2));
> 1.01
Thanks to Razu, this article, and MDN's Math.round reference.
The use case can perhaps be that your occurences are spread throughout your file, but you know your only concern is in the first 10, 20 or 100 lines.
Then simply adressing those lines fixes the issue - even if the wording of the OP regards first only.
sed '1,10s/#include/#include "newfile.h"\n#include/'
Shift-Tab works for me to view the dcoumentation
Another way of doing this is to use ravel
model = forest.fit(train_fold, train_y.values.reshape(-1,))
This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;
ArrayList<String> recordings = new ArrayList<String>();
this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
}
}, 100);
System.Reflection.Assembly.GetAssembly(type).Location
IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO
namespace to get the exact path of the file.
I got the errors to go away by installing the Windows Universal CRT SDK
component, which adds support for legacy Windows SDKs. You can install this using the Visual Studio Installer:
If the problem still persists, you should change the Target SDK in the Visual Studio Project : check whether the Windows SDK version is 10.0.15063.0.
In : Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0.
Then errno.h and other standard files will be found and it will compile.
If you have defined a method inside your class as static, this is actually possible.
class myClass
{
public:
static void saySomething()
{
std::cout << "This is a static method!" << std::endl;
}
};
And from main, you declare a pointer and try to invoke the static method.
myClass * pmyClass;
pmyClass->saySomething();
/*
Output:
This is a static method!
*/
This works fine because static methods do not belong to a specific instance of the class and they are not allocated as a part of any instance of the class.
Read more on static methods here: http://en.wikipedia.org/wiki/Static_method#Static_methods
Thanks Philip this helped me - my use case was I had a form with lot of input fields so I maintained initial state as object and I was not able to update the object state.The above post helped me :)
const [projectGroupDetails, setProjectGroupDetails] = useState({
"projectGroupId": "",
"projectGroup": "DDD",
"project-id": "",
"appd-ui": "",
"appd-node": ""
});
const inputGroupChangeHandler = (event) => {
setProjectGroupDetails((prevState) => ({
...prevState,
[event.target.id]: event.target.value
}));
}
<Input
id="projectGroupId"
labelText="Project Group Id"
value={projectGroupDetails.projectGroupId}
onChange={inputGroupChangeHandler}
/>
How about a CTE?
;WITH Salaries AS
(
SELECT Name, Salary,
DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'SalaryRank'
FROM
dbo.Employees
)
SELECT Name, Salary
FROM Salaries
WHERE SalaryRank = 2
DENSE_RANK()
will give you all the employees who have the second highest salary - no matter how many employees have the (identical) highest salary.
If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:
public static Task<T> RunAsync<T>(Func<T> function)
{
if (function == null) throw new ArgumentNullException(“function”);
var tcs = new TaskCompletionSource<T>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
T result = function();
tcs.SetResult(result);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.
I saw it's also used in the .NET source, e.g. WebClient.cs:
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
{
// Create the task to be returned
var tcs = new TaskCompletionSource<string>(address);
// Setup the callback event handler
UploadStringCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
this.UploadStringCompleted += handler;
// Start the async operation.
try { this.UploadStringAsync(address, method, data, tcs); }
catch
{
this.UploadStringCompleted -= handler;
throw;
}
// Return the task that represents the async operation
return tcs.Task;
}
Finally, I also found the following useful:
I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.
To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).
This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.
Introduction to Async/Await on ASP.NET
If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.
Here is my approach to download JSON with plain node, no packages required.
import https from "https";
function get(url, resolve, reject) {
https.get(url, (res) => {
if(res.statusCode === 301 || res.statusCode === 302) {
return get(res.headers.location, resolve, reject)
}
let body = [];
res.on("data", (chunk) => {
body.push(chunk);
});
res.on("end", () => {
try {
// remove JSON.parse(...) for plain data
resolve(JSON.parse(Buffer.concat(body).toString()));
} catch (err) {
reject(err);
}
});
});
}
async function getData(url) {
return new Promise((resolve, reject) => get(url, resolve, reject));
}
// call
getData("some-url-with-redirect").then((r) => console.log(r));
You can also use lib-auto
xmlns:app="http://schemas.android.com/apk/lib-auto"
As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:
How to pass ctor args in Activator.CreateInstance or use IL?
Did you try using SELECT PostGIS_version();
The lookup module of ansible works fine for me. The yml is:
- hosts: test
vars:
time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"
You can replace any command with date to get result of the command.
As mentioned both select.select()
and socket.settimeout()
will work.
Note you might need to call settimeout
twice for your needs, e.g.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("",0))
sock.listen(1)
# accept can throw socket.timeout
sock.settimeout(5.0)
conn, addr = sock.accept()
# recv can throw socket.timeout
conn.settimeout(5.0)
conn.recv(1024)
I dont want to use like this
That is the syntax for Update
statement in SQL, you have to use that syntax otherwise you will get the exception.
command.Text = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn AND LastName = @ln";
and then add your parameters accordingly.
command.Parameters.AddWithValue("@ln", lastName);
command.Parameters.AddWithValue("@fn", firstName);
command.Parameters.AddWithValue("@add", address);
command.Parameters.AddWithValue("@cit", city);
Easiest solution is:
const todayDate = Date.now();
return new Date(todayDate + 1000 * 60 * 60 * 24 * 30* X);
where X
is the number of months we want to add.
I got it too, for me the problem got resolved after deleting the m2 folder (C:\Users\username.m2) and updating the maven project.
You will find the tomcat-users.xml in \Users\<Name>\AppData\Roaming\Netbeans\
. It exists at least twice on your machine, depending on the number of Tomcat installations you have.
I faced the same issue. I had missed the forms module import tag in the app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,
FormsModule
],
For this specific problem, something like this would work:
$ sed 's/^ *//g' < input.txt > output.txt
It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:
$ sed 's/^[ \t]+//g' < input.txt > output.txt
The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.
Finally, instead of < input.txt > output.txt
you can use the -i
option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.
Yes, it's easy and possible. Define first default colors.
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.Clear()
it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine()
.
Then you can change the colors on each print:
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");
When finish your program, remember reset console colors on finish:
Console.ResetColor();
Console.Clear();
Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.
I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.
https://github.com/deinsoftware/colorify/ and also available as NuGet package
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
Go to the Start Menu
Right Click "Computer"
Select "Properties"
A dialog should pop up with a link on the left called "Advanced system settings". Click it.
In the System Properties dialog, click the button called "Environment Variables".
In the Environment Variables dialog look for "Path" under the System Variables window.
Add ";C:\Python27" to the end of it. The semicolon is the path separator on windows.
Click Ok and close the dialogs.
Now open up a new command prompt and type "python" or if it says error type "py" instead of "python"
Just use .strip(), it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with data_string.splitlines()
:
[s.strip() for s in data_string.splitlines()]
Output:
>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Phone: 555-555-555', 'Other Home: Somewhere Else', 'Notes: Other data', 'Name: Jane Smith', 'Misc: Data with spaces']
You can even inline the splitting on :
as well now:
>>> [s.strip().split(': ') for s in data_string.splitlines()]
[['Name', 'John Smith'], ['Home', 'Anytown USA'], ['Phone', '555-555-555'], ['Other Home', 'Somewhere Else'], ['Notes', 'Other data'], ['Name', 'Jane Smith'], ['Misc', 'Data with spaces']]
At our shop, I introduced the convention of adding recognizably named annotated tags to commits with incorrect messages, and using the annotation as the replacement.
Even though this doesn't help folks who run casual "git log" commands, it does provide us with a way to fix incorrect bug tracker references in the comments, and all my build and release tools understand the convention.
This is obviously not a generic answer, but it might be something folks can adopt within specific communities. I'm sure if this is used on a larger scale, some sort of porcelain support for it may crop up, eventually...
CSS?
td {
padding-top: 2px;
padding-bottom: 2px;
}
protected
can be used by any subclasses from any assembly.
protected internal
is everything that protected
is, plus also anything in the same assembly can access it.
Importantly, it doesn't mean "subclasses in the same assembly" - it is the union of the two, not the intersection.
Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:
Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.
DateTime
is not standard nullable type. If you want assign null to DateTime
type of variable, you have to use DateTime?
type which supports null value.
If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:
if (dateTimeVariable == default(DateTime))
{
//do work for dateTimeVariable == null situation
}
You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
#include <string>
std::string wstrtostr(const std::wstring &wstr)
{
// Convert a Unicode string to an ASCII string
std::string strTo;
char *szTo = new char[wstr.length() + 1];
szTo[wstr.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
strTo = szTo;
delete[] szTo;
return strTo;
}
std::wstring strtowstr(const std::string &str)
{
// Convert an ASCII string to a Unicode String
std::wstring wstrTo;
wchar_t *wszTo = new wchar_t[str.length() + 1];
wszTo[str.size()] = L'\0';
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
wstrTo = wszTo;
delete[] wszTo;
return wstrTo;
}
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.
So you can understand this better:
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
*pX = 10;
}
int main(int argc, char ** argv)
{
int X;
fillXWith10(&X);
return 0;
}
Since $.getJSON
is async, I think your console.log(list.length);
code is firing before your array has been populated. To correct this put your console.log
statement inside your callback:
var list = new Array();
$.getJSON("json.js", function(data) {
$.each(data, function(i, item) {
console.log(item.text);
list.push(item.text);
});
console.log(list.length);
});
I required having count(*) > 1
also. So, I wrote my own query after referring some the above queries
SYNTAX:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;
Example:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;
Right, click on the project. Go to Maven -> Update Project.
The dependencies will automatically be installed.
say you have a dict
with tuples as keys, e.g: labels = {(1,2,0): 'label_1'}
you can modify the elements of the tuple keys as follows:
formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}
Here, we ignore the last elements.
EOF is -1 because that's how it's defined. The name is provided by the standard library headers that you #include
. They make it equal to -1 because it has to be something that can't be mistaken for an actual byte read by getchar()
. getchar()
reports the values of actual bytes using positive number (0 up to 255 inclusive), so -1 works fine for this.
The !=
operator means "not equal". 0 stands for false, and anything else stands for true. So what happens is, we call the getchar()
function, and compare the result to -1 (EOF). If the result was not equal to EOF, then the result is true, because things that are not equal are not equal. If the result was equal to EOF, then the result is false, because things that are equal are not (not equal).
The call to getchar()
returns EOF when you reach the "end of file". As far as C is concerned, the 'standard input' (the data you are giving to your program by typing in the command window) is just like a file. Of course, you can always type more, so you need an explicit way to say "I'm done". On Windows systems, this is control-Z. On Unix systems, this is control-D.
The example in the book is not "wrong". It depends on what you actually want to do. Reading until EOF means that you read everything, until the user says "I'm done", and then you can't read any more. Reading until '\n' means that you read a line of input. Reading until '\0' is a bad idea if you expect the user to type the input, because it is either hard or impossible to produce this byte with a keyboard at the command prompt :)
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
To solve the problem :
You may try using ellipsis by adding the following in CSS:
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631
Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.
Why don't you consider www.cameraftp.com? it supports image upload and online viewer
There is option for tar
program:
-I, --use-compress-program PROG
filter through PROG (must accept -d)
You can use multithread version of archiver or compressor utility.
Most popular multithread archivers are pigz (instead of gzip) and pbzip2 (instead of bzip2). For instance:
$ tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 paths_to_archive
$ tar --use-compress-program=pigz -cf OUTPUT_FILE.tar.gz paths_to_archive
Archiver must accept -d. If your replacement utility hasn't this parameter and/or you need specify additional parameters, then use pipes (add parameters if necessary):
$ tar cf - paths_to_archive | pbzip2 > OUTPUT_FILE.tar.gz
$ tar cf - paths_to_archive | pigz > OUTPUT_FILE.tar.gz
Input and output of singlethread and multithread are compatible. You can compress using multithread version and decompress using singlethread version and vice versa.
For p7zip for compression you need a small shell script like the following:
#!/bin/sh
case $1 in
-d) 7za -txz -si -so e;;
*) 7za -txz -si -so a .;;
esac 2>/dev/null
Save it as 7zhelper.sh. Here the example of usage:
$ tar -I 7zhelper.sh -cf OUTPUT_FILE.tar.7z paths_to_archive
$ tar -I 7zhelper.sh -xf OUTPUT_FILE.tar.7z
Regarding multithreaded XZ support. If you are running version 5.2.0 or above of XZ Utils, you can utilize multiple cores for compression by setting -T
or --threads
to an appropriate value via the environmental variable XZ_DEFAULTS (e.g. XZ_DEFAULTS="-T 0"
).
This is a fragment of man for 5.1.0alpha version:
Multithreaded compression and decompression are not implemented yet, so this option has no effect for now.
However this will not work for decompression of files that haven't also been compressed with threading enabled. From man for version 5.2.2:
Threaded decompression hasn't been implemented yet. It will only work on files that contain multiple blocks with size information in block headers. All files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size is used.
If you build tar from sources, then you can recompile with parameters
--with-gzip=pigz
--with-bzip2=lbzip2
--with-lzip=plzip
After recompiling tar with these options you can check the output of tar's help:
$ tar --help | grep "lbzip2\|plzip\|pigz"
-j, --bzip2 filter the archive through lbzip2
--lzip filter the archive through plzip
-z, --gzip, --gunzip, --ungzip filter the archive through pigz
I struggled understanding how to do this on my first implementation - make sure you have the following:
1) Your device supports vibration (my Samsung tablet did not work so I kept re-checking the code - the original code worked perfectly on my CM Touchpad
2) You have declared above the application level in your AndroidManifest.xml file to give the code permission to run.
3) Have imported both of the following in to your MainActivity.java with the other imports: import android.content.Context; import android.os.Vibrator;
4) Call your vibration (discussed extensively in this thread already) - I did it in a separate function and call this in the code at other points - depending on what you want to use to call the vibration you may need an image (Android: long click on a button -> perform actions) or button listener, or a clickable object as defined in XML (Clickable image - android):
public void vibrate(int duration)
{
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
Instead of GetContentString()
, use GetContentFile() instead. It will save the file instead of returning the string.
downloaded.GetContentFile('images.zip')
Then you can unzip it later with unzip
.
I think the fastest and simplest way would be to use an XmlReader, this will not require any recursion and minimal memory foot print.
Here is a simple example, for compactness I just used a simple string of course you can use a stream from a file etc.
string xml = @"
<parent>
<child>
<nested />
</child>
<child>
<other>
</other>
</child>
</parent>
";
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
Console.WriteLine(rdr.LocalName);
}
}
The result of the above will be
parent
child
nested
child
other
A list of all the elements in the XML document.
I really need to instantiate a T in Foo using a parameter-less constructor
Simple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.
How can one work around Java's limitation?
One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of Foo<T>
. Or you could have a method setBar(T theInstanceofT);
to get your T instead of instantiating in the class it self.
With mouseover
and mouseleave
events you can define a toggle function that implements this logic and react on the value in the rendering.
Check this example:
var vm = new Vue({_x000D_
el: '#app',_x000D_
data: {btn: 'primary'}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">_x000D_
_x000D_
_x000D_
<div id='app'>_x000D_
<button_x000D_
@mouseover="btn='warning'"_x000D_
@mouseleave="btn='primary'"_x000D_
:class='"btn btn-block btn-"+btn'>_x000D_
{{ btn }}_x000D_
</button>_x000D_
</div>
_x000D_
As of today you can throttle your connection natively in Google Chrome Canary 46.0.2489.0
. Simply open up Dev Tools and head over to the Network tab:
Here is an alternative which uses a custom output iterator. This example behaves correctly for the case of an empty list. This example demonstrates how to create a custom output iterator, similar to std::ostream_iterator
.
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>
struct CommaIterator
:
public std::iterator<std::output_iterator_tag, void, void, void, void>
{
std::ostream *os;
std::string comma;
bool first;
CommaIterator(std::ostream& os, const std::string& comma)
:
os(&os), comma(comma), first(true)
{
}
CommaIterator& operator++() { return *this; }
CommaIterator& operator++(int) { return *this; }
CommaIterator& operator*() { return *this; }
template <class T>
CommaIterator& operator=(const T& t) {
if(first)
first = false;
else
*os << comma;
*os << t;
return *this;
}
};
int main () {
// The vector to convert
std::vector<int> v(3,3);
// Convert vector to string
std::ostringstream oss;
std::copy(v.begin(), v.end(), CommaIterator(oss, ","));
std::string result = oss.str();
const char *c_result = result.c_str();
// Display the result;
std::cout << c_result << "\n";
}
Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.
Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.
ssh kev@server1 './test/foo.sh'
Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).
In your css add folllowing
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
And then in you code you can add ng-cloak directive. For example,
<div ng-cloak>
Welcome {{data.name}}
</div>
Thats it!
Use JSON lib E.g. http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}
As an extension to @LennartRegebro's answer:
If you can't tell what encoding your file uses and the solution above does not work (it's not utf8
) and you found yourself merely guessing - there are online tools that you could use to identify what encoding that is. They aren't perfect but usually work just fine. After you figure out the encoding you should be able to use solution above.
EDIT: (Copied from comment)
A quite popular text editor Sublime Text
has a command to display encoding if it has been set...
View
-> Show Console
(or Ctrl+`)view.encoding()
and hope for the best (I was unable to get anything but Undefined
but maybe you will have better luck...)function getKeys(obj){
var keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
}
return keys;
}
Try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
margin-left: 50px;
margin-top: 50px;
margin-right: 50px;
margin-bottom: 50px;
}
.rotate {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
-webkit-transform: rotate(-10deg);
-moz-transform: rotate(-10deg);
-o-transform: rotate(-10deg);
-ms-transform: rotate(-10deg);
-sand-transform: rotate(10deg);
display: block;
position: fixed;
}
</style>
</head>
<body>
<div class="rotate">Alpesh</div>
</body>
</html>
If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:
dotnet %~n0.dll %*
Obviously, this assumes that the machine has .NET Core installed and globally available.
c:\> "path\to\batch\file" -args blah
(This answer is derived from Chet's comment.)
As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.
If Firebug isn't an option for you, then try this simple script:
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".
Here is another nice solution for the Max
functionality using T-SQL and SQL Server
SELECT [Other Fields],
(SELECT Max(v)
FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]
FROM [YourTableName]
Try this:
SELECT *
FROM (SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;
Or TOP:
SELECT TOP 2 * FROM Customers; //But not supported in Oracle
NOTE: I suppose that your internal query is fine. Please share your output of this.
I still found that with the solutions above, it didn't work (for example) with the Rails plugin for TextMate. I got a similar error (when retrieving the database schema).
So what did is, open terminal:
cd /usr/local/lib
sudo ln -s ../mysql-5.5.8-osx10.6-x86_64/lib/libmysqlclient.16.dylib .
Replace mysql-5.5.8-osx10.6-x86_64 with your own path (or mysql).
This makes a symbol link to the lib, now rails runs from the command line, as-well as TextMate plugin(s) like ruby-on-rails-tmbundle.
To be clear: this also fixes the error you get when starting rails server.
Nope - but you could use a template column:
<script runat="server">
TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
object o = DataBinder.Eval(Container.DataItem, field);
if (converter == null) {
return (TResult)o;
}
return converter((T)o);
}
</script>
<asp:TemplateField>
<ItemTemplate>
<%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
</ItemTemplate>
</asp:TemplateField>
A more general solution for sending asynchronous requests using the .ajax()
jQuery API and closures to pass additional parameters to the callback function:
function sendRequest(method, url, content, callback) {
// additional data for the callback
var request = {
method: method,
url: url
};
$.ajax({
type: method,
url: url,
data: content
}).done(function(data, status, xhr) {
if (callback) callback(xhr.status, data, request);
}).fail(function(xhr, status) {
if (callback) callback(xhr.status, xhr.response, request);
});
};
if ( ! $("input").is(':checked') )
Doesn't work?
You might also try iterating over the elements like so:
var iz_checked = true;
$('input').each(function(){
iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
mysqldump -h [domain name/ip] -u [username] -p[password] [databasename] > [filename.sql]
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:
package Bug;
sub print_me
{
my ($self) = @_;
print "ID: $self->{id}\n";
print "$self->{descr}\n";
print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
}
Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
We use
SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';
to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.
pause
command is what you looking for.
If you looking ONLY the case when enter is hit you can abuse the runas
command:
runas /user:# "" >nul 2>&1
the screen will be frozen until enter is hit.What I like more than set/p=
is that if you press other buttons than enter they will be not displayed.
I know nothing about the Android SQLite API, but if you're able to talk to it in SQL directly, you can do this:
create table if not exists mytable (col1 type, col2 type);
Which will ensure that the table is always created and not throw any errors if it already existed.
My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.
I had similar problem with margin collapse because of parent having position
set to relative. Here are list of commands you can use to disable margin collapsing.
Just try to assign any parent-fix*
class to div.container
element, or any class children-fix*
to div.margin
. Pick the one that fits your needs best.
When
div.absolute
with red background will be positioned at the very top of the page.div.absolute
will be positioned at the same Y coordinate as div.margin
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
width: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 50px;_x000D_
right: 50px;_x000D_
height: 100px;_x000D_
border: 5px solid #F00;_x000D_
background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
width: 100%;_x000D_
height: 20px;_x000D_
background-color: #444;_x000D_
margin-top: 50px;_x000D_
color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before { content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
<div class="margin children-fix">margin</div>_x000D_
<div class="absolute"></div>_x000D_
</div>
_x000D_
Here is jsFiddle with example you can edit
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
Do not put both the old sqljdbc.jar and the new sqljdbc4.jar in your classpath - this will make it (more or less) unpredictable which classes are being used, if both of those JARs contain classes with the same qualified names.
You said you put sqljdbc4.jar in your classpath - did you remove the old sqljdbc.jar from the classpath? You said "it didn't work", what does that mean exactly? Are you sure you don't still have the old JAR in your classpath somewhere (maybe not explicitly)?
The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].
The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift()
in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.
Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.
Reproduce code:
function get_arr()
{
return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);
After some time and multiple online threads on the subject I managed to fix my project.
It's mainly taking into consideration the last files (could be images or layouts) that you put in. If you delete them, it will work out, and you can build your project again.
Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.
As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.
There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).
ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.
At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).
Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.
ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.
Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.
So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.
You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).
Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type.
With the following class, you just need to write ConsoleManager.Show()
somewhere before any call to Console.Write
...
[SuppressUnmanagedCodeSecurity]
public static class ConsoleManager
{
private const string Kernel32_DllName = "kernel32.dll";
[DllImport(Kernel32_DllName)]
private static extern bool AllocConsole();
[DllImport(Kernel32_DllName)]
private static extern bool FreeConsole();
[DllImport(Kernel32_DllName)]
private static extern IntPtr GetConsoleWindow();
[DllImport(Kernel32_DllName)]
private static extern int GetConsoleOutputCP();
public static bool HasConsole
{
get { return GetConsoleWindow() != IntPtr.Zero; }
}
/// <summary>
/// Creates a new console instance if the process is not attached to a console already.
/// </summary>
public static void Show()
{
//#if DEBUG
if (!HasConsole)
{
AllocConsole();
InvalidateOutAndError();
}
//#endif
}
/// <summary>
/// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.
/// </summary>
public static void Hide()
{
//#if DEBUG
if (HasConsole)
{
SetOutAndErrorNull();
FreeConsole();
}
//#endif
}
public static void Toggle()
{
if (HasConsole)
{
Hide();
}
else
{
Show();
}
}
static void InvalidateOutAndError()
{
Type type = typeof(System.Console);
System.Reflection.FieldInfo _out = type.GetField("_out",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.FieldInfo _error = type.GetField("_error",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Debug.Assert(_out != null);
Debug.Assert(_error != null);
Debug.Assert(_InitializeStdOutError != null);
_out.SetValue(null, null);
_error.SetValue(null, null);
_InitializeStdOutError.Invoke(null, new object[] { true });
}
static void SetOutAndErrorNull()
{
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
}
}
Errors like that are usually sent to the "standard error" stream, which you can pipe to a file or just make disappear on most commands:
grep pattern * -R -n 2>/dev/null
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
BalusC excellent answer covers most of the patterns for web applications.
Some application may require Chain-of-responsibility_pattern
In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
Use case to use this pattern:
When handler to process a request(command) is unknown and this request can be sent to multiple objects. Generally you set successor to object. If current object can't handle the request or process the request partially and forward the same request to successor object.
Useful SE questions/articles:
Why would I ever use a Chain of Responsibility over a Decorator?
Common usages for chain of responsibility?
chain-of-responsibility-pattern from oodesign
chain_of_responsibility from sourcemaking
An easy way to see all the properties on a particular DOM node in Chrome (I'm on v.69) is to right click on the element, select inspect, and then instead of viewing the "Style" tab click on "Properties".
Inside of the Properties tab you will see all the properties for your particular element.
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
In order to run ssh-add
on Windows one could install git using choco install git
. The ssh-add
command is recognized once C:\Program Files\Git\usr\bin
has been added as a PATH variable and the command prompt has been restarted:
C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)
C:\Users\user\Desktop\repository>
For example if you want to do diferent things depending on the value of a variable:
my_var = 1
for items in range(0,100):
if my_var < 10:
continue
elif my_var == 10:
print("hit")
elif my_var > 10:
print("passed")
my_var = my_var + 1
In the example above if I use break
the interpreter will skip the loop. But with continue
it only skips the if-elif statements and go directly to the next item of the loop.
You want to make filter dynamic then you have to use Lambda like
from django.db.models import Q
brands = ['ABC','DEF' , 'GHI']
queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))
reduce(lambda x, y: x | y, [Q(brand=item) for item in brands])
is equivalent to
Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....
I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.
With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:
|--------|-------------------|
| P(dBm) | P(mW) |
|--------|-------------------|
| 50 | 100000 |
| 40 | 10000 | strong transmitter
| 30 | 1000 | ^
| 20 | 100 | |
| 10 | 10 | |
| 0 | 1 |
| -10 | 0.1 |
| -20 | 0.01 |
| -30 | 0.001 |
| -40 | 0.0001 |
| -50 | 0.00001 | |
| -60 | 0.000001 | |
| -70 | 0.0000001 | v
| -80 | 0.00000001 | sensitive receiver
| -90 | 0.000000001 |
|--------|-------------------|
When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.
When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.
Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
** STRANGE: note that any two values on the first column are not equal in that sense.**
'' == 0 == false // Any two values among these 3 ones are equal with the == operator
'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
'\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
null == undefined // These two "default" values are not-equal to any of the listed values above
NaN // NaN is not equal to any thing, even to itself.
SELECT *
FROM (SELECT * FROM can
UNION
SELECT * FROM employee) as e
WHERE e.id = 1;
For Bootstrap 3 and 4 it's
.collapsing {
-webkit-transition: none;
transition: none;
display: none;
}
*<tr><a href="javascript:void(0);" class="remove">X</a></tr>*
<script type='text/javascript'>
$("table").on('click', '.remove', function () {
$(this).parent().parent('tr').remove();
});
Since the introduction of the DocumentFilter
in Java 1.4, the need to override Document
has been lessoned.
DocumentFilter
provides the means for filtering content been passed to the Document
before it actually reaches it.
These allows the field to continue to maintain what ever document it needs, while providing the means to filter the input from the user.
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class LimitTextField {
public static void main(String[] args) {
new LimitTextField();
}
public LimitTextField() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextField pfPassword = new JTextField(20);
((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(pfPassword);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class LimitDocumentFilter extends DocumentFilter {
private int limit;
public LimitDocumentFilter(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("Limit can not be <= 0");
}
this.limit = limit;
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
int currentLength = fb.getDocument().getLength();
int overLimit = (currentLength + text.length()) - limit - length;
if (overLimit > 0) {
text = text.substring(0, text.length() - overLimit);
}
if (text.length() > 0) {
super.replace(fb, offset, length, text, attrs);
}
}
}
}
Here is how to modify cron a entry without directly editing the cron file (which is frowned upon).
crontab -l -u <user> | sed 's/find/replace/g' | crontab -u <user> -
If you want to remove a cron entry, use this:
crontab -l -u <user> | sed '/find/d' | crontab -u <user> -
I realize this is not what gaurav was asking for, but why not have all the solutions in one place?
My approach. Tricky, but works well for me
<p> </p>
I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.
private ComboBox combo;
private Label label;
public CreateControls()
{
combo = new ComboBox();
label = new Label();
//some initializing code
combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
label.Text = combo.SelectedValue;
}
thanks to lambda expressions you can use it like this:
public CreateControls()
{
ComboBox combo = new ComboBox();
Label label = new Label();
//some initializing code
combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}
Much easier.
Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
All of this works for me:
@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul
Output:
Directory = D:\Users\Thejordster135\Desktop\Code\BAT\
Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"
Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat
Bat File Drive = D:
Full File Name = Path.bat
File Name Without Extension = Path
File Extension = .bat
I ended up using ideas from this post to come up with a solution that is pretty similar to AtZako's version.
jQuery.fn.preventDoubleSubmission = function() {
var last_clicked, time_since_clicked;
$(this).bind('submit', function(event){
if(last_clicked)
time_since_clicked = event.timeStamp - last_clicked;
last_clicked = event.timeStamp;
if(time_since_clicked < 2000)
return false;
return true;
});
};
Using like this:
$('#my-form').preventDoubleSubmission();
I found that the solutions that didn't include some kind of timeout but just disabled submission or disabled form elements caused problems because once the lock-out is triggered you can't submit again until you refresh the page. That causes some problems for me when doing ajax stuff.
This can probably be prettied up a bit as its not that fancy.
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
Wikipedia explains it better then I could
From the article - Top is 1st Tier:
Try this
$("#message span").text("hello world!");
function Errormessage(txt) {
var elem = $("#message");
elem.fadeIn("slow");
// find the span inside the div and assign a text
elem.children("span").text("your text");
elem.children("a.close-notify").click(function() {
elem.fadeOut("slow");
});
}
Here is a simple solution that works for me.
public static bool numResult;
public static bool checkTextisNumber(string numberVal)
{
try
{
if (numberVal.Equals("."))
{
numResult = true;
}
else if (numberVal.Equals(""))
{
numResult = true;
}
else
{
decimal number3 = 0;
bool canConvert = decimal.TryParse(numberVal, out number3);
if (canConvert == true)
{
numResult = true;
}
else
numResult = false;
}
}
catch (System.Exception ex)
{
numResult = false;
}
return numResult;
}
string correctNum;
private void tBox_NumTester_TextChanged(object sender, TextChangedEventArgs e)
{
if(checkTextisNumber(tBox_NumTester.Text))
{
correctNum = tBox_NumTester.Text;
}
else
{
tBox_NumTester.Text = correctNum;
}
}
Bitbucket: Check for Branch permissions in Settings (it may be on 'Deny all'). If that doesn't work, simply clone your branch to a new local branch, push the changes to the remote (a new remote branch will be created), and create a PR.
A simple way is to write:
-std=c++11
in the Other Options section of the compiler flags. You could do this on a per-project basis (Project -> Build Options), and/or set it as a default option in the Settings -> Compilers part.
Some projects may require -std=gnu++11
which is like C++11 but has some GNU extensions enabled.
If using g++ 4.9, you can use -std=c++14
or -std=gnu++14
.
I've created this query:
SELECT
db.name AS [Database Name],
mf.name AS [Logical Name],
mf.type_desc AS [File Type],
mf.physical_name AS [Path],
CAST(
(mf.Size * 8
) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)],
'By '+IIF(
mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
(mf.growth * 8
) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth],
IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
(
CAST(mf.max_size AS BIGINT) * 8
) / 1024 AS VARCHAR(30))+' MB')) AS [MaximumSize]
FROM
sys.master_files AS mf
INNER JOIN sys.databases AS db ON
db.database_id = mf.database_id
You can pass values by using the below .
@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )
Controller:
public ActionResult About(string name)
{
ViewBag.Message = "Your application description page.";
ViewBag.NameTransfer = name;
return View();
}
And the URL looks like
http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay
Simpler with the aggregate function string_agg()
(Postgres 9.0 or later):
SELECT movie, string_agg(actor, ', ') AS actor_list
FROM tbl
GROUP BY 1;
The 1
in GROUP BY 1
is a positional reference and a shortcut for GROUP BY movie
in this case.
string_agg()
expects data type text
as input. Other types need to be cast explicitly (actor::text
) - unless an implicit cast to text
is defined - which is the case for all other character types (varchar
, character
, "char"
), and some other types.
As isapir commented, you can add an ORDER BY
clause in the aggregate call to get a sorted list - should you need that. Like:
SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM tbl
GROUP BY 1;
But it's typically faster to sort rows in a subquery. See:
If you want to check all of your input matches,
>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
if you want to check at least one match,
>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
Could you please try this ?
Create another item in post such as post.link then assign the link to it before send post to the render function.
post.link = '/posts/+ id.toString();
So, the above render function should be following instead.
return <li key={post.id}><a href={post.link}>{post.title}</a></li>
Here is a little work around that I created. I checked it with R and it works correct.
import numpy as np
import statsmodels.api as sm
y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4]
x = [
[4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5],
[4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5],
[4,1,2,5,6,7,8,9,7,8,7,8,7,7,7,7,7,7,6,6,4,4,4]
]
def reg_m(y, x):
ones = np.ones(len(x[0]))
X = sm.add_constant(np.column_stack((x[0], ones)))
for ele in x[1:]:
X = sm.add_constant(np.column_stack((ele, X)))
results = sm.OLS(y, X).fit()
return results
Result:
print reg_m(y, x).summary()
Output:
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.535
Model: OLS Adj. R-squared: 0.461
Method: Least Squares F-statistic: 7.281
Date: Tue, 19 Feb 2013 Prob (F-statistic): 0.00191
Time: 21:51:28 Log-Likelihood: -26.025
No. Observations: 23 AIC: 60.05
Df Residuals: 19 BIC: 64.59
Df Model: 3
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1 0.2424 0.139 1.739 0.098 -0.049 0.534
x2 0.2360 0.149 1.587 0.129 -0.075 0.547
x3 -0.0618 0.145 -0.427 0.674 -0.365 0.241
const 1.5704 0.633 2.481 0.023 0.245 2.895
==============================================================================
Omnibus: 6.904 Durbin-Watson: 1.905
Prob(Omnibus): 0.032 Jarque-Bera (JB): 4.708
Skew: -0.849 Prob(JB): 0.0950
Kurtosis: 4.426 Cond. No. 38.6
pandas
provides a convenient way to run OLS as given in this answer:
In your app.js file:
.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on('$locationChangeStart', function(event, next, current) {
if (!$rootScope.loggedUser == null) {
$state.go('home');
}
});
}])
Just add a background image to all images using css:
img {
background: url('loading.gif') no-repeat;
}
Set the Credentials property before sending the message.
If you like to avoid both changes()=0
and INSERT OR IGNORE
even if you cannot afford deleting the row - You can use this logic;
First, insert (if not exists) and then update by filtering with the unique key.
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);
-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players
SET age=20
WHERE user_name='johnny';
Notice: I haven't tested it to see the which triggers are being called, but I assume the following:
in this way you can have a single SQL command
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Single command to insert or update
INSERT OR REPLACE INTO players
(id, user_name, age)
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
'johnny',
20);
Edit: added option 2.
try following
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Process p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
}
Check if you have the Startup class created in your project. This is an example:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]
namespace AuctionPortal
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
Date and time as String to Long (millis):
String dateTimeString = "2020-12-12T14:34:18.000Z";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime
.parse(dateTimeString, formatter);
Long dateTimeMillis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.
A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.
As an update to the state of the Ruby ecosystem, Date
, DateTime
and Time
now have methods to convert between the various classes. Using Ruby 1.9.2+:
pry
[1] pry(main)> ts = 'Jan 1, 2000 12:01:01'
=> "Jan 1, 2000 12:01:01"
[2] pry(main)> require 'time'
=> true
[3] pry(main)> require 'date'
=> true
[4] pry(main)> ds = Date.parse(ts)
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[5] pry(main)> ds.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[6] pry(main)> ds.to_datetime
=> #<DateTime: 2000-01-01T00:00:00+00:00 (4903089/2,0,2299161)>
[7] pry(main)> ds.to_time
=> 2000-01-01 00:00:00 -0700
[8] pry(main)> ds.to_time.class
=> Time
[9] pry(main)> ds.to_datetime.class
=> DateTime
[10] pry(main)> ts = Time.parse(ts)
=> 2000-01-01 12:01:01 -0700
[11] pry(main)> ts.class
=> Time
[12] pry(main)> ts.to_date
=> #<Date: 2000-01-01 (4903089/2,0,2299161)>
[13] pry(main)> ts.to_date.class
=> Date
[14] pry(main)> ts.to_datetime
=> #<DateTime: 2000-01-01T12:01:01-07:00 (211813513261/86400,-7/24,2299161)>
[15] pry(main)> ts.to_datetime.class
=> DateTime
You can't effectively use Distinct
on a collection of objects (without additional work). I will explain why.
It uses the default equality comparer,
Default
, to compare values.
For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode()
and Equals
methods, it will check on the reference of the object, which are not distinct.
comment Require local from httpd.conf
"#Require local"
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}