(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...]
like this:
library(gsubfn) # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()
If you only need the first or second component these all work too:
list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()
(Of course, if you only needed one value then functionReturningTwoValues()[[1]]
or functionReturningTwoValues()[[2]]
would be sufficient.)
See the cited r-help thread for more examples.
(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with
:
myfun <- function() list(a = 1, b = 2)
list[a, b] <- myfun()
a + b
# same
with(myfun(), a + b)
(3) attach Another alternative is attach:
attach(myfun())
a + b
ADDED: with
and attach
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
For my case none of the suggestions worked. I'm on Windows and this worked for me:
git remote add foo //SERVERNAME/path/to/copied/git
)git push foo master
. Did it worked? Great! Now delete not-working repo and rename this into whatever it was before. Make sure permissions and share property remains the same. I found the same, I had to add $(SDKROOT)/usr/include/libxml2 for the latest Xcode (4.3.x). ALSO, what kept me circling around for hours is the fact that I was modifying the "TARGET" and not the "PROJECT" (the new UI of Xcode is so intricate that its easy to overlook this). You need to modify the PROJECT!
Actually you can capture Query strings in MVC in two ways.....
public ActionResult CrazyMVC(string knownQuerystring)
{
// This is the known query string captured by the Controller Action Method parameter above
string myKnownQuerystring = knownQuerystring;
// This is what I call the mysterious "unknown" query string
// It is not known because the Controller isn't capturing it
string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];
return Content(myKnownQuerystring + " - " + myUnknownQuerystring);
}
This would capture both query strings...for example:
/CrazyMVC?knownQuerystring=123&unknownQuerystring=456
Output: 123 - 456
Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?
Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.
Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:
using System.Windows.Forms;
using System.Collections.Generic;
using System;
namespace MyTool
{
public class DelayedDelegate
{
static private DelayedDelegate _instance = null;
private Timer _runDelegates = null;
private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();
public DelayedDelegate()
{
}
static private DelayedDelegate Instance
{
get
{
if (_instance == null)
{
_instance = new DelayedDelegate();
}
return _instance;
}
}
public static void Add(MethodInvoker pMethod, int pDelay)
{
Instance.AddNewDelegate(pMethod, pDelay * 1000);
}
public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
{
Instance.AddNewDelegate(pMethod, pDelay);
}
private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
{
if (_runDelegates == null)
{
_runDelegates = new Timer();
_runDelegates.Tick += RunDelegates;
}
else
{
_runDelegates.Stop();
}
_delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));
StartTimer();
}
private void StartTimer()
{
if (_delayedDelegates.Count > 0)
{
int delay = FindSoonestDelay();
if (delay == 0)
{
RunDelegates();
}
else
{
_runDelegates.Interval = delay;
_runDelegates.Start();
}
}
}
private int FindSoonestDelay()
{
int soonest = int.MaxValue;
TimeSpan remaining;
foreach (MethodInvoker invoker in _delayedDelegates.Keys)
{
remaining = _delayedDelegates[invoker] - DateTime.Now;
soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
}
return soonest;
}
private void RunDelegates(object pSender = null, EventArgs pE = null)
{
try
{
_runDelegates.Stop();
List<MethodInvoker> removeDelegates = new List<MethodInvoker>();
foreach (MethodInvoker method in _delayedDelegates.Keys)
{
if (DateTime.Now >= _delayedDelegates[method])
{
method();
removeDelegates.Add(method);
}
}
foreach (MethodInvoker method in removeDelegates)
{
_delayedDelegates.Remove(method);
}
}
catch (Exception ex)
{
}
finally
{
StartTimer();
}
}
}
}
The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.
Try changing the Web Client request authentication part to:
NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;
Then make your call, seems to work fine for me.
If you just use rm
, you will need to follow it up with git add <fileRemoved>
. git rm
does this in one step.
You can also use git rm --cached
which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.
It depends on your purpose. If you program for the Web, avoid indexOf
, it isn't supported by Internet Explorer 6 (lot of them still used!), or do conditional use:
if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);
indexOf
is probably coded in native code, so it is faster than anything you can do in JavaScript (except binary search/dichotomy if the array is appropriate).
Note: it is a question of taste, but I would do a return false;
at the end of your routine, to return a true Boolean...
SQL Server by default uses the mdy
date format and so the below works:
SELECT convert(datetime, '07/23/2009', 111)
and this does not work:
SELECT convert(datetime, '23/07/2009', 111)
I myself have been struggling to come up with a single query that can handle both date formats: mdy
and dmy
.
However, you should be ok with the third date format - ymd
.
You need a private setter, if you want to support the following scenario (not only for this, but this should point out one good reason): You have a Property that is readonly in your class, i.e. only the class itself is allowed to change it, but it may change it after constructing the instance. For bindings you would then need to fire a PropertyChanged-event, preferrably this should be done in the (private) property setter. Actually, you could just fire the PropertyChanged-event from somewhere else in the class, but using the private setter for this is "good citizenship", because you do not distribute your property-change-triggers all over your class but keep it at the property, where it belongs.
I encountered the same error in GitHub Actions. Adding sudo
solved the issue.
sudo gem install bundler
You're looking for is called an IDENTITY column:
create table student (
sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
,sname varchar(30)
,PRIMARY KEY (sid)
);
A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.
I had the same problem and I found this solution working with bindParam :
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
You are looking for System.Environment.NewLine
.
On Windows, this is equivalent to \r\n
though it could be different under another .NET implementation, such as Mono on Linux, for example.
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
Short answer:
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
I'm afraid none of these solutions worked for me. Perhaps because I was using belongs_to
in my create_table migration for a polymorphic association.
I'll add my code below and a link to the solution that helped me in case anyone else stumbles upon when searching for 'Index name is too long' in connection with polymorphic associations.
The following code did NOT work for me:
def change
create_table :item_references do |t|
t.text :item_unique_id
t.belongs_to :referenceable, polymorphic: true
t.timestamps
end
add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end
This code DID work for me:
def change
create_table :item_references do |t|
t.text :item_unique_id
t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }
t.timestamps
end
end
This is the SO Q&A that helped me out: https://stackoverflow.com/a/30366460/3258059
To expand on Ryand's answer, if you're using Bootstrap.ui, this on your modal-instance will do the trick:
modalInstance.rendered.then(function (result) {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
$('.modal .modal-body').css('height', $(window).height() * 0.7);
});
Like the other answers said, sp_reset_connection
indicates that connection pool is being reused. Be aware of one particular consequence!
Jimmy Mays' MSDN Blog said:
sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.
UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.
ref: SQL Server: Isolation level leaks across pooled connections
Here is some additional information:
What does sp_reset_connection do?
Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.
sp_reset_connection resets the following aspects of a connection:
All error states and numbers (like @@error)
Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
Waits for any outstanding I/O operations that is outstanding
Frees any held buffers on the server by the connection
Unlocks any buffer resources that are used by the connection
Releases all allocated memory owned by the connection
Clears any work or temporary tables that are created by the connection
Kills all global cursors owned by the connection
Closes any open SQL-XML handles that are open
Deletes any open SQL-XML related work tables
Closes all system tables
Closes all user tables
Drops all temporary objects
Aborts open transactions
Defects from a distributed transaction when enlisted
Decrements the reference count for users in current database which releases shared database locks
Frees acquired locks
Releases any acquired handles
Resets all SET options to the default values
Resets the @@rowcount value
Resets the @@identity value
Resets any session level trace options using dbcc traceon()
Resets CONTEXT_INFO to
NULL
in SQL Server 2005 and newer [ not part of the original article ]sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when
sp_setapprole
is executed.
Note: I am including the list here as I do not want it to be lost in the ever transient web.
To get the entire contents of a file:
$content = [IO.File]::ReadAllText(".\test.txt")
Number of lines:
([IO.File]::ReadAllLines(".\test.txt")).length
or
(gc .\test.ps1).length
Sort of hackish to include trailing empty line:
[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
Sub test()
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder1 = FSO.GetFolder(FromPath).Files
FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
Workbooks.Add
Set Movenamelist = ActiveWorkbook
For Each fil In folder1
Movenamelist.Activate
Range("A100000").End(xlUp).Offset(1, 0).Value = fil
ActiveCell.Offset(1, 0).Select
Next
End Sub
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
About the version of Android SDK Build-tools, the answer is
By default, the Android SDK uses the most recent downloaded version of the Build Tools.
In Eclipse, you can choose a specific version by using the sdk.buildtools
property in the project.properties
file.
There seems to be no official page explaining all the build tools. Here is what the Android team says about this.
The [build] tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.
Anyway, here is a synthesis of the differences between tools, platform-tools and build-tools:
$ANDROID_HOME/tools
ddms
(for debugging)$ANDROID_HOME/platform-tools
adb
(to manage the state of an emulator or an Android device)$ANDROID_HOME/build-tools/$VERSION/
aapt
(to generate R.java and unaligned, unsigned APKs), dx
(to convert Java bytecode to Dalvik bytecode), and zipalign
(to optimize your APKs)The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014. remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.
what you really need to do is .. log into your google account and open up following address https://www.google.com/settings/security/lesssecureapps and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go.. here is the code which worked fine for me..
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','[email protected]');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
Not able to comment because I just created this account, but I wanted to make sure to point out that @eggrobot78's solution works, but it is exclusive in dart so it doesn't include the last number. If you change the last line to "r = min + rnd.nextInt(max - min + 1);", then it should include the last number as well.
Explanation:
max = 5;
min = 3;
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//max - min is 2
//nextInt is exclusive so nextInt will return 0 through 1
//3 is added so the line will give a number between 3 and 4
//if you add the "+ 1" then it will return a number between 3 and 5
Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.
If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.
I did it with these values within a LinearLayout:
Scale type: fitStart
Layout gravity: fill_horizontal
Layout height: wrap_content
Layout weight: 1
Layout width: fill_parent
Try this:
<style type="text/css">
<?php include("bg-color.php") ?>
</style>
And bg-color.php can be something like:
<?php
//Don't forget to sanitize the input
$colour = $_GET["colour"];
?>
body {
background-color: #<?php echo $colour ?>;
}
Be careful with setup
projects if you're using them; Visual Studio setup projects Primary Output
pulls from the obj
folder rather than the bin
.
I was releasing applications I thought were obfuscated and signed in msi
setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin
folder assemblies and should have been targeting the obj
folder assemblies instead.
This is far from intuitive imho, but the general setup
approach is to use the Primary Output
of the project and this is the obj
folder. I'd love it if someone could shed some light on this btw.
In the HTML I added a class of nav-link to the a tag of each navigation link.
$('.nav-link').click(
function () {
$('.navbar-collapse').removeClass('in');
}
);
For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..
Demo: http://bootply.com/93706
Here are the correct Microsoft Office MIME types for HTTP content streaming:
Extension MIME Type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
.mdb application/vnd.ms-access
For further details check out this TechNet article and this blog post.
Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:
Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);
BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);
@echo $(NDK_PROJECT_PATH) is the good way to do it. I don't think the error comes from there. Generally this error appears when you mistyped the intendation : I think you have spaces where you should have a tab.
You should use $.map
for this:
var array = ["one", "two", "three"];
var el = $.map(array, function(val, i) {
return "<span>" + val + "</span>";
});
$(".element").html(el.join(""));
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
in this link i mentioned before on the comment, read this part :
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.
this "JOIN FETCH" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).
And it is only effect the method of "when the query should happen". And you must also know this:
hibernate have two orthogonal notions : when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.
when is the association fetched --> your "FETCH" type
how is it fetched --> Join/select/Subselect/Batch
In your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:
@OneToMany(fetch = FetchType.LAZY)
private Set<Department> department;
when you use
FROM Employee emp
JOIN FETCH emp.department dep
you will get emp
and emp.dep
. when you didnt use fetch you can still get emp.dep
but hibernate will processing another select to the database to get that set of department.
so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).
Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).
use fetch when :
no large unneeded collection/set inside that entity you about to get
communication from application server to database server too far and need long time
you may need that collection latter when you don't have the access to it(outside of the transactional method/class)
My synopsis of rfc2397 is:
Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64,
" this is similar to the prefixing done in the parenthesis of url()
definition in CSS or in the quoted value of the src
attribute of the img
tag in [X]HTML. You can test the data url in firefox by putting the data:image/...
line into the URL field and pressing enter, it should show your image.
For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.
base64
command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
A note on mime-types:
I would prefer you use one of image/png
image/jpeg
or image/gif
as I can't find the popular image/x-icon
. Should that be image/vnd.microsoft.icon
?
Also the other formats are much shorter.
compare 265 bytes vs 1150 bytes:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=
data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp
See also
Standard SQL syntax is
DROP TABLE table_name;
IF EXISTS
is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is
DROP TABLE IF EXISTS table_name;
The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.
To drop a table, and all the other objects that depend on it, use one of these.
DROP TABLE table_name CASCADE;
DROP TABLE IF EXISTS table_name CASCADE;
Use CASCADE with great care.
An example of an Activity and a Service implementing a LocalBroadcastManager can be found in the developer docs. I personally found it very useful.
EDIT: The link has since then been removed from the site, but the data is the following: https://github.com/carrot-garden/android_maven-android-plugin-samples/blob/master/support4demos/src/com/example/android/supportv4/content/LocalServiceBroadcaster.java
In 32 bit virtual address system we can have 2^32 unique address, since the page size given is 4KB = 2^12, we will need (2^32/2^12 = 2^20) entries in the page table, if each entry is 4Bytes then total size of the page table = 4 * 2^20 Bytes = 4MB
You can learn some tutorials for JSP page direct access database (mysql) here
Notes:
import sql tag library in jsp page
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
then set datasource on page
<sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
Now query what you want on page
<sql:query dataSource="${ds}" var="result"> //ref defined 'ds'
SELECT * from <your-table>;
</sql:query>
Finally you can populate dropdowns on page using c:forEach
tag to iterate result rows in select
element
<c:forEach var="row" items="${result.rows}"> //ref set var 'result'
<option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option>
</c:forEach>
Well there is 2 ways to change the location.href
. Either you can write location.href = "y.html"
, which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.
If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick
. So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick
calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.
var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
var callBacks = [];
var uglyHax = function (){
var done = function (){
uglyHax();
callBacks.forEach(function (cb){
cb();
});
};
win.addEventListener("unload", function unloadListener(){
win.removeEventListener("unload", unloadListener); // Firefox remembers, other browsers don't
setTimeout(function (){
// IE10, IE11, Opera, PhantomJS, Chrome has a complete new document at this point
// Chrome on Karma, Firefox has a loading new document at this point
win.document.readyState; // IE10 and IE11 sometimes fails if I don't access it twice, idk. how or why
if (win.document.readyState === "complete")
done();
else
win.addEventListener("load", function (){
setTimeout(done, 0);
});
}, 0);
});
};
uglyHax();
callBacks.push(function (){
console.log("cb", win.location.href, win.document.readyState);
if (win.location.href !== "http://localhost:4444/y.html")
win.location.href = "http://localhost:4444/y.html";
else
console.log("done");
});
win.location.href = "http://localhost:4444/x.html";
If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:
var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
var callBacks = [];
win.addEventListener("unload", function unloadListener(){
setTimeout(function (){
callBacks.forEach(function (cb){
cb();
});
}, 0);
});
callBacks.push(function (){
console.log("cb", win.location.href, win.document.readyState);
// be aware that the page is in loading readyState,
// so if you rewrite the location here, the actual page will be never loaded, just the new one
if (win.location.href !== "http://localhost:4444/y.html")
win.location.href = "http://localhost:4444/y.html";
else
console.log("done");
});
win.location.href = "http://localhost:4444/x.html";
If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange
and the popstate
events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.
I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
This works:
params.require(:model).permit(filters: [[:name, values: []]])
Try this code:
var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);
Unless I'm misunderstanding, you lost your .ssh
directory containing your private key on your local machine and so you want to remove the public key which was on a server and which allowed key-based login.
In that case, it will be stored in the .ssh/authorized_keys
file in your home directory on the server. You can just edit this file with a text editor and delete the relevant line if you can identify it (even easier if it's the only entry!).
I hope that key wasn't your only method of access to the server and you have some other way of logging in and editing the file. You can either manually add a new public key to authorised_keys
file or use ssh-copy-id
. Either way, you'll need password authentication set up for your account on the server, or some other identity or access method to get to the authorized_keys
file on the server.
ssh-add
adds identities to your SSH agent which handles management of your identities locally and "the connection to the agent is forwarded over SSH remote logins, and the user can thus use the privileges given by the identities anywhere in the network in a secure way." (man page), so I don't think it's what you want in this case. It doesn't have any way to get your public key onto a server without you having access to said server via an SSH login as far as I know.
SELECT *
FROM customer
WHERE joiningdate >= NOW();
Try the below data dictionary views.
tabs
dba_tables
all_tables
user_tables
Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file's still there. I think the remove()
function in the c stdio.h
is what you're looking for there. Not sure about Python.
This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y')
is perpendicular to the line connecting (x1,y1)
and (x2,y2)
. This line has direction (x2-x1,y2-y1)
, or (dx,dy)
.
So,
(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0
The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx)
or (-dy,dx)
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):
#define CHUNK 1024
/* Read the contents of a file into a buffer. Return the size of the file
* and set buf to point to a buffer allocated with malloc that contains
* the file contents.
*/
int read_file(FILE *fp, char **buf)
{
int n, np;
char *b, *b2;
n = CHUNK;
np = n;
b = malloc(sizeof(char)*n);
while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {
n += r;
if (np - n < CHUNK) {
np *= 2; // buffer is too small, the next read could overflow!
b2 = malloc(np*sizeof(char));
memcpy(b2, b, n * sizeof(char));
free(b);
b = b2;
}
}
*buf = b;
return n;
}
This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).
To ensure you obtain the right length you would need to consider unicode types as a special case. See code below.
For further information see: https://msdn.microsoft.com/en-us/library/ms176106.aspx
SELECT
c.name 'Column Name',
t.name,
t.name +
CASE WHEN t.name IN ('char', 'varchar','nchar','nvarchar') THEN '('+
CASE WHEN c.max_length=-1 THEN 'MAX'
ELSE CONVERT(VARCHAR(4),
CASE WHEN t.name IN ('nchar','nvarchar')
THEN c.max_length/2 ELSE c.max_length END )
END +')'
WHEN t.name IN ('decimal','numeric')
THEN '('+ CONVERT(VARCHAR(4),c.precision)+','
+ CONVERT(VARCHAR(4),c.Scale)+')'
ELSE '' END
as "DDL name",
c.max_length 'Max Length in Bytes',
c.precision ,
c.scale ,
c.is_nullable,
ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('YourTableName')
I was facing the same issue with Eclipse JUNO & windows XP. After changing a lot of things in eclipse.ini
still it was not working and then i deleted it, i don't know why its starts working after deleting this init file. You may try for yours
jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.
The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not
).
In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.
var group = $('ul[data-group="Companies"]');
Next, we can look for companies in this set who start with G
var google = $('[data-company^="G"]',group);//google
Or perhaps companies which contain the word soft
var microsoft = $('[data-company*="soft"]',group);//microsoft
It is also possible to get elements whose data attribute's ending matches
var facebook = $('[data-company$="book"]',group);//facebook
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
<li data-company="Microsoft">Microsoft</li>_x000D_
<li data-company="Google">Google</li>_x000D_
<li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
I think you just need to add 2 more options (contentType
and dataType
):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
For all browser support, especially on Android, perhaps you can add this:
try{
blob = new Blob(byteArrays, {type : contentType});
}
catch(e){
// TypeError old Google Chrome and Firefox
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if(e.name == 'TypeError' && window.BlobBuilder){
var bb = new BlobBuilder();
bb.append(byteArrays);
blob = bb.getBlob(contentType);
}
else if(e.name == "InvalidStateError"){
// InvalidStateError (tested on FF13 WinXP)
blob = new Blob(byteArrays, {type : contentType});
}
else{
// We're screwed, blob constructor unsupported entirely
}
}
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
In general, you can the characters of a string from i
until j
with string[i:j]
.
string[:2]
is shorthand for string[0:2]
. This works for arrays as well.
Learn about python's slice notation at the official tutorial
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
As an alternative to using regex you could do it in Sets:
from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
if Set(my_little_sting).issubset(allowed_chars):
# your action
print True
Imagine the string could be reversed. Then it is really easy. Instead of working on the string:
"My little cat" (1)
you work with
"tac elttil yM" (2)
With =LEFT(A1;FIND(" ";A1)-1)
in A2 you get "My"
with (1) and "tac"
with (2), which is reversed "cat"
, the last word in (1).
There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString
.
Install the above as described. Then with your string in A1, e.g., "My little cat"
and this function in A2:
=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
LEN(A1);(FIND(" ";ReverseString(A1))-1))))
you'll see "cat"
in A2.
The method above assumes that words are separated by blanks. The IF
clause is for cells containing single words = no blanks in cell. Note: TRIM
and CLEAN
the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "
). LEFT
picks this word and another string reversal reconstitutes the original order of the word (" cat"
). The -1
at the end of the FIND
statement removes the blank.
The idea is that it is easy to extract the first(!) word in a string with LEFT
and FIND
ing the first blank. However, for the last(!) word the RIGHT
function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.
Therefore the whole string is simply reversed. LEFT
and FIND
work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString
statement in the formula does this job.
From https://golang.org/doc/effective_go.html#composite_literals:
Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
The best for replace \n \t and more: Programmer's File Editor http://www.lancs.ac.uk/staff/steveb/cpaap/pfe/pfefiles.htm
If you are using SDK 28 or higher, you need to migrate to AndroidX library.
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
Microsoft Core Library, ie they are at the heart of everything.
There is a more "massaged" explanation you may prefer:
"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."
From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx
Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.
I'm answering my own question because it provides a better overview of the cause and possible solutions. I've awarded the bonus to @Martin because he pin pointed the cause.
Cause
As suggested by @Martin the cause is the use of multiple threads. The request object is not available in these threads, as mentioned in the Spring Guide:
DispatcherServlet
,RequestContextListener
andRequestContextFilter
all do exactly the same thing, namely bind the HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.
Solution 1
It is possible to make the request object available to other threads, but it places a couple of limitations on the system, which may not be workable in all projects. I got this solution from Accessing request scoped beans in a multi-threaded web application:
I managed to get around this issue. I started using
SimpleAsyncTaskExecutor
instead ofWorkManagerTaskExecutor
/ThreadPoolExecutorFactoryBean
. The benefit is thatSimpleAsyncTaskExecutor
will never re-use threads. That's only half the solution. The other half of the solution is to use aRequestContextFilter
instead ofRequestContextListener
.RequestContextFilter
(as well asDispatcherServlet
) has athreadContextInheritable
property which basically allows child threads to inherit the parent context.
Solution 2
The only other option is to use the session scoped bean inside the request thread. In my case this wasn't possible because:
@Async
;I've been using ClockPick.
Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error
fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported
I solved the problem by changing the line that generated the output file from:
out-file -FilePath GITVersion.h -InputObject $result
to:
out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result
If you work with developers, often get a sliver of code that is formatted as one long line of code, then sql pretty printer add-on for SQL Server management Studio may helps a lot with more than 60+ formatter options. http://www.dpriver.com/sqlpp/ssmsaddin.html
#train_size is 1 - tst_size - vld_size
tst_size=0.15
vld_size=0.15
X_train_test, X_valid, y_train_test, y_valid = train_test_split(df.drop(y, axis=1), df.y, test_size = vld_size, random_state=13903)
X_train_test_V=pd.DataFrame(X_train_test)
X_valid=pd.DataFrame(X_valid)
X_train, X_test, y_train, y_test = train_test_split(X_train_test, y_train_test, test_size=tst_size, random_state=13903)
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
Just in case if anyone is interested in labeling horizontal barplot graph, I modified Sharon's answer as below:
def show_values_on_bars(axs, h_v="v", space=0.4):
def _show_on_single_plot(ax):
if h_v == "v":
for p in ax.patches:
_x = p.get_x() + p.get_width() / 2
_y = p.get_y() + p.get_height()
value = int(p.get_height())
ax.text(_x, _y, value, ha="center")
elif h_v == "h":
for p in ax.patches:
_x = p.get_x() + p.get_width() + float(space)
_y = p.get_y() + p.get_height()
value = int(p.get_width())
ax.text(_x, _y, value, ha="left")
if isinstance(axs, np.ndarray):
for idx, ax in np.ndenumerate(axs):
_show_on_single_plot(ax)
else:
_show_on_single_plot(axs)
Two parameters explained:
h_v
- Whether the barplot is horizontal or vertical. "h"
represents the horizontal barplot, "v"
represents the vertical barplot.
space
- The space between value text and the top edge of the bar. Only works for horizontal mode.
Example:
show_values_on_bars(sns_t, "h", 0.3)
If you don't happen to know if the image will be portrait or landscape (e.g user takes pic with camera), I created another method that takes max width and height parameters.
Lets say you have a UIImage *myLargeImage
which is a 4:3 ratio.
UIImage *myResizedImage = [ImageUtilities imageWithImage:myLargeImage
scaledToMaxWidth:1024
maxHeight:1024];
The resized UIImage will be 1024x768 if landscape; 768x1024 if portrait. This method will also generate higher res images for retina display.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
} else {
UIGraphicsBeginImageContext(size);
}
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height {
CGFloat oldWidth = image.size.width;
CGFloat oldHeight = image.size.height;
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
CGFloat newHeight = oldHeight * scaleFactor;
CGFloat newWidth = oldWidth * scaleFactor;
CGSize newSize = CGSizeMake(newWidth, newHeight);
return [ImageUtilities imageWithImage:image scaledToSize:newSize];
}
This is the easiest way using Kotlin
private const val DATE_FORMAT = "dd/MM/yy hh:mm"
fun millisToDate(millis: Long) : String {
return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
}
You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.
while running:
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(6) # with the port open, the response will be buffered
# so wait a bit longer for response here
# Serial read section
msg = ard.read(ard.inWaiting()) # read everything in the input buffer
print ("Message from arduino: ")
print (msg)
The Python Serial.read
function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.
On the Arduino side, you should consider what happens in your loop
function when no data is available.
void loop()
{
// serial read section
while (Serial.available()) // this will be skipped if no data present, leading to
// the code sitting in the delay function below
{
delay(30); //delay to allow buffer to fill
if (Serial.available() >0)
{
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
}
}
Instead, wait at the start of the loop
function until data arrives:
void loop()
{
while (!Serial.available()) {} // wait for data to arrive
// serial read section
while (Serial.available())
{
// continue as before
EDIT 2
Here's what I get when interfacing with your Arduino app from Python:
>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'
So that seems to be working fine.
In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:
#!/usr/bin/python
import serial
import syslog
import time
#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X
ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino
i = 0
while (i < 4):
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
ard.flush()
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(1) # I shortened this to match the new value in your Arduino code
# Serial read section
msg = ard.read(ard.inWaiting()) # read all characters in buffer
print ("Message from arduino: ")
print (msg)
i = i + 1
else:
print "Exiting"
exit()
Here's the output of the above now:
$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Exiting
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
Another relevant environment variable is:
So, on a 64-bit machine running in 32-bit (WOW64) mode:
- echo %programfiles% ==> C:\Program Files (x86)
- echo %programfiles(x86)% ==> C:\Program Files (x86)
- echo %ProgramW6432% ==> C:\Program Files
From Wikipedia:
The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).
Reference: http://en.wikipedia.org/wiki/Environment_variable
If you are not sure if local db is installed, or not sure which database name you should use to connect to it - try running 'sqllocaldb info' command - it will show you existing localdb databases.
Now, as far as I know, local db should be installed together with Visual Studio 2015. But probably it is not required feature, and if something goes wrong or it cannot be installed for some reason - Visual Studio installation continues still (note that is just my guess). So to be on the safe side don't rely on it will always be installed together with VS.
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
https://play.golang.org/p/JGZ7mN0-U-
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
or
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Go language specs for for
statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
I solved it with window.length
.
But with this solution you can take current error (X-Frame or 404).
iframe.onload = event => {
const isLoaded = event.target.contentWindow.window.length // 0 or 1
}
In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:
Happy coding!
This dumps the file in your temp folder with file name, then after that you can call it and not worry about it. Because it will get deleted if it is in your temp folder for an amount of days.
string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(),".xls"));
File.WriteAllBytes(filename, FileUploadControl.FileBytes);
If your collections object is a list, I would use the sort method, as proposed in the other answers.
However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:
TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);
Yes. This kind of errors are very common and lead to app crash. So I use to add NSDictionary in each project as below:
//.h file code :
@interface NSDictionary (AppDictionary)
- (id)objectForKeyNotNull : (id)key;
@end
//.m file code is as below
#import "NSDictionary+WKDictionary.h"
@implementation NSDictionary (WKDictionary)
- (id)objectForKeyNotNull:(id)key {
id object = [self objectForKey:key];
if (object == [NSNull null])
return nil;
return object;
}
@end
In code you can use as below:
NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT. Maven helps to manage- Builds,Documentation,Reporing,SCMs,Releases,Distribution. - maven repository is a directory of packaged JAR file with pom.xml file. Maven searches for dependencies in the repositories.
Not forgetting
.equalsIgnoreCase(String)
if you're not worried about that sort of thing...
if you have multiple parameters use the syntax as below. I have a bat file with script as below:
start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6
This will open multiple consoles.
Toast toast = Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
I know this is old, but... Another option may be to use the FileSystemWatcher like so:
void SomeMethod()
{
System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
lock (listLock)
{
pathsToUpload.Add(path);
}
}
This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.
I figured it out. I had the arguments in the wrong order. This works:
scp -i mykey.pem somefile.txt [email protected]:/
Rather than contrast DI and IoC directly, it may be helpful to start from the beginning: every non-trivial application depends on other pieces of code.
So I am writing a class, MyClass
, and I need to call a method of YourService
... somehow I need to acquire an instance of YourService
. The simplest, most straightforward way is to instantiate it myself.
YourService service = new YourServiceImpl();
Direct instantiation is the traditional (procedural) way to acquire a dependency. But it has a number of drawbacks, including tight coupling of MyClass
to YourServiceImpl
, making my code difficult to change and difficult to test. MyClass
doesn't care what the implementation of YourService
looks like, so MyClass
doesn't want to be responsible for instantiating it.
I'd prefer to invert that responsibility from MyClass
to something outside MyClass
. The simplest way to do that is just to move the instantiation call (new YourServiceImpl();
) into some other class. I might name this other class a Locator, or a Factory, or any other name; but the point is that MyClass
is no longer responsible for YourServiceImpl
. I've inverted that dependency. Great.
Problem is, MyClass
is still responsible for making the call to the Locator/Factory/Whatever. Since all I've done to invert the dependency is insert a middleman, now I'm coupled to the middleman (even if I'm not coupled to the concrete objects the middleman gives me).
I don't really care where my dependencies come from, so I'd prefer not to be responsible for making the call(s) to retrieve them. Inverting the dependency itself wasn't quite enough. I want to invert control of the whole process.
What I need is a totally separate piece of code that MyClass
plugs into (call it a framework). Then the only responsibility I'm left with is to declare my dependency on YourService
. The framework can take care of figuring out where and when and how to get an instance, and just give MyClass
what it needs. And the best part is that MyClass
doesn't need to know about the framework. The framework can be in control of this dependency wiring process. Now I've inverted control (on top of inverting dependencies).
There are different ways of connecting MyClass
into a framework. Injection is one such mechanism whereby I simply declare a field or parameter that I expect a framework to provide, typically when it instantiates MyClass
.
I think the hierarchy of relationships among all these concepts is slightly more complex than what other diagrams in this thread are showing; but the basic idea is that it is a hierarchical relationship. I think this syncs up with DIP in the wild.
You can input the following command on Linux:
find ./ -name "*." | xargs svn add
You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.
player.setPlaybackQuality(suggestedQuality:String):Void
This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]
items[node.ind] = items[node.ind]._replace(v=node.v)
(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")
I only ever use _GET or _POST. I prefer to have control.
What I don't like about either code fragment in the OP is that they discard the information on which HTTP method was used. And that information is important for input sanitization.
For example, if a script accepts data from a form that's going to be entered into the DB then the form had better use POST (use GET only for idempotent actions). But if the script receives the input data via the GET method then it should (normally) be rejected. For me, such a situation might warrant writing a security violation to the error log since it's a sign somebody is trying something on.
With either code fragment in the OP, this sanitization wouldn't be possible.
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
Your error is because you have:
JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id
You have two instances of the same table, but the database can't determine which is which. To fix this, you need to use table aliases:
JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id
It's good habit to always alias your tables, unless you like writing the full table name all the time when you don't have situations like these.
The next issues to address will be:
SELECT article.* , section.title, category.title, user.name, user.name
1) Never use SELECT *
- always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.
2) You'll get ambiguous column errors relating to the user.name
columns because again, the database can't tell which table instance to pull data from. Using table aliases fixes the issue:
SELECT article.* , section.title, category.title, u.name, u2.name
I used this way to make my project faster:
RichTextBox rcbCatalyst = new RichTextBox()
{
Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();
return text;
RichTextBox.Text will automatically convert your array to a multiline string!
Another tool you can use is registry-cli. For example, this command:
registry.py -l "login:password" -r https://your-registry.example.com --delete
will delete all but the last 10 images.
The accepted answer reflects the rules given by Royal Mail, although there is a typo in the regex. This typo seems to have been in there on the gov.uk site as well (as it is in the XML archive page).
In the format A9A 9AA the rules allow a P character in the third position, whilst the regex disallows this. The correct regex would be:
(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})
Shortening this results in the following regex (which uses Perl/Ruby syntax):
(GIR 0AA)|([A-PR-UWYZ](([0-9]([0-9A-HJKPSTUW])?)|([A-HK-Y][0-9]([0-9ABEHMNPRVWXY])?))\s?[0-9][ABD-HJLNP-UW-Z]{2})
It also includes an optional space between the first and second block.
HEAD^^^ is the same as HEAD~3, selecting the third commit before HEAD
HEAD^2 specifies the second head in a merge commit
You can bulk import all aliases from one keystore to another:
keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks
The last place I had to unbox something was when writing some code that retrieved some data from a database (I wasn't using LINQ to SQL, just plain old ADO.NET):
int myIntValue = (int)reader["MyIntValue"];
Basically, if you're working with older APIs before generics, you'll encounter boxing. Other than that, it isn't that common.
As my previous answer appeared not to be very popular, I will give this another go.
You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst()
.flatMap( Function.identity() );
This will fit all your requirements:
Optional<Result>
this::resolve
lazily as neededthis::resolve
will not be called after first non-empty resultOptional<Result>
The only modification compared to OP initial version was that I removed .map(Optional::get)
before call to .findFirst()
and added .flatMap(o -> o)
as the last call in the chain.
This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.
You can't really go any shorter than this in Java.
The alternative snippet of code using the more conventional for
loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:
this.resolve
, Optional.isPresent
Just to prove that my solution works as advertised, I wrote a small test program:
public class StackOverflow {
public static void main( String... args ) {
try {
final int integer = Stream.of( args )
.peek( s -> System.out.println( "Looking at " + s ) )
.map( StackOverflow::resolve )
.filter( Optional::isPresent )
.findFirst()
.flatMap( o -> o )
.orElseThrow( NoSuchElementException::new )
.intValue();
System.out.println( "First integer found is " + integer );
}
catch ( NoSuchElementException e ) {
System.out.println( "No integers provided!" );
}
}
private static Optional<Integer> resolve( String string ) {
try {
return Optional.of( Integer.valueOf( string ) );
}
catch ( NumberFormatException e )
{
System.out.println( '"' + string + '"' + " is not an integer");
return Optional.empty();
}
}
}
(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)
Executing this on a command line, I got the following results:
$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3
The mPDF docs state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$mpdf->Output('filename.pdf','F');
you can also use the Array.find
feature of es6
. the doc is here
return restaurants.find(item => {
return item.restaurant.food == 'chicken'
})
I made a function of the Trident D'Gao answer.
function print(obj) {
console.log(JSON.stringify(obj, null, 4));
}
How to use it
print(obj);
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
Have you looked at the DateUtils truncate method in Apache Commons Lang?
Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);
will remove the time element.
all you need is to tie the group to a different item in your model
@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")
@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")
I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.
set undofile
set undolevels=1000 " How many undos
set undoreload=10000 " number of lines to save for undo
set backup " enable backups
set swapfile " enable swaps
set undodir=$HOME/.vim/tmp/undo " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap " swap files
" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
call mkdir(expand(&directory), "p")
endif
A click is an event; you can't query an element and ask it whether it's being clicked on or not. How about this:
jQuery('#id').click(function () {
// do some stuff
});
Then if you really wanted to, you could just have a loop that executes every few seconds with your // run function..
EDIT: I noticed a few downvotes and took another look at this Q&A. Most people seem to miss that the OP asked for fields to be dynamically selected based on the caller-provided list of fields. You can't do this with the statically-defined json struct tag.
If what you want is to always skip a field to json-encode, then of course use json:"-"
to ignore the field (also note that this is not required if your field is unexported - those fields are always ignored by the json encoder). But that is not the OP's question.
To quote the comment on the json:"-"
answer:
This [the
json:"-"
answer] is the answer most people ending up here from searching would want, but it's not the answer to the question.
I'd use a map[string]interface{} instead of a struct in this case. You can easily remove fields by calling the delete
built-in on the map for the fields to remove.
That is, if you can't query only for the requested fields in the first place.
Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"
To change the size of a button called button1
you simple call
button1.config( height = WHATEVER, width = WHATEVER2 )
If you know what size you want at initialization these options can be added to the constructor.
button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100)
You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.
You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.
It appears as if all the answers go around the bushes.
In your EditText
, use the property:
android:textCursorDrawable="@drawable/black_cursor"
and add the drawable black_cursor.xml
to your resources, as follows:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<size android:width="1dp" />
<solid android:color="#000000"/>
</shape>
This is also the way to create more diverse cursors, if you need.
Set the opacity of its view it is showed in.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0
Use this in an animation. You can change the alpha in an animation for an duration.
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
Just use this code. What most are forgeting is to specify max-width as the max-width of the image
img {
height: auto;
width: 100%;
max-width: 300px;
}
Check this demonstration http://shorturl.at/nBKVY
I think the lifetime is crucial, and whether the thing being allocated has to be constructed in a complex way. For example, in transaction-driven modeling, you usually have to fill in and pass in a transaction structure with a bunch of fields to operation functions. Look at the OSCI SystemC TLM-2.0 standard for an example.
Allocating these on the stack close to the call to the operation tends to cause enormous overhead, as the construction is expensive. The good way there is to allocate on the heap and reuse the transaction objects either by pooling or a simple policy like "this module only needs one transaction object ever".
This is many times faster than allocating the object on each operation call.
The reason is simply that the object has an expensive construction and a fairly long useful lifetime.
I would say: try both and see what works best in your case, because it can really depend on the behavior of your code.
var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
edit: added i
flag
edit2: you can use /<br[^>]*>/gi
which will match anything between the br
and slash
if you have for example <br class="clear" />
From python tutorial:
Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.
So it is safe to use x[:100]
.
window.location.href
is what you need. But also if you are using react router you might find useful checking out useLocation and useHistory hooks.
Both create an object with a pathname attribute you can read and are useful for a bunch of other stuff. Here's a youtube video explaining react router hooks
Both will give you what you need (without the domain name):
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname
const history = useHistory()
history.location.pathname
This problem happens when xcode-select
developer directory was pointing to /Library/Developer/CommandLineTools
when a full regular Xcode was required (happens when CommandLineTools are installed after Xcode)
Solution:
/Applications
directory (NOT /Users/{user}/Applications
).xcode-select
to the Xcode app Developer directory using the following command:sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
Note: Make sure your Xcode app path is correct.
/Applications/Xcode.app/Contents/Developer
/Applications/Xcode-beta.app/Contents/Developer
According to the LanguageManual, you can use unix_timestamp()
to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp())
.
Hope that helps.
brew switch libfoo mycopy
You can use brew switch
to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/
This will list versions installed ( for example I had Cellar/sdl2/2.0.3
, I've compiled into Cellar/sdl2/2.0.4
)
brew info sdl2
Then to switch between them
brew switch sdl2 2.0.4
brew info
Info now shows *
next to the 2.0.4
To install under Cellar/<packagename>/<version>
from source you can do for example
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
check where it gets installed with
make install -n
if all looks correct
make install
Then from cd $(brew --Cellar)
do the switch between version.
I'm using brew version 0.9.5
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.@all
Whole view.@form
Closest ancestor form of current component.@none
No component.and the standard JSF 2.3+ keywords:
@child(n)
nth child.@composite
Closest composite component ancestor.@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.@namingcontainer
Closest ancestor naming container of current component.@parent
Parent of the current component.@previous
Previous sibling.@next
Next sibling.@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.@widgetVar(name)
Component with given widgetVar.And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
You might not have write permissions to install a node module in the global location such as /usr/local/lib/node_modules
, in which case run npm install -g package as root.
What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:
p = [q.index(v) if v in q else 99999 for v in vm]
When using a list comprehension, you do not call list.append
because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for
keyword, which in this case is q.index(v) if v in q else 99999
. Incidentially, if you do use list.append
inside a comprehension, then you will get a list of None
values because that is what the append
method always returns.
My favorite function for entropy is the following:
def entropy(labels):
prob_dict = {x:labels.count(x)/len(labels) for x in labels}
probs = np.array(list(prob_dict.values()))
return - probs.dot(np.log2(probs))
I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.
On Visual Studio 2017, using the built-in database for development I had problems with the current given solution, I had to change the code to make it work because it threw the error that DATE() was not a built in function.
Here is my solution:
where CAST(TimeCalled AS DATE) = CAST(GETDATE() AS DATE)
I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:
SELECT datekey,
COALESCE(RunningTotal, 0) AS RunningTotal,
COALESCE(RunningCount, 0) AS RunningCount,
COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM document
OUTER APPLY
( SELECT SUM(Amount) AS RunningTotal,
COUNT(1) AS RunningCount,
COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
FROM Document d2
WHERE d2.DateKey <= document.DateKey
) rt;
This can be done in SQL-Server 2012 using the syntax you have suggested:
SELECT datekey,
SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM document
However, use of DISTINCT
is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY
is your best option
I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:
insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt
In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.
Assuming you want to access folder named xzy two folders up your python file. This works for me and platform independent.
".././xyz"
One options will be to show the selected option above (or below) the select list like following:
HTML
<div id="selText"><span> </span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#mySelect").change(function(){
//$("#selText").html($($(this).children("option:selected")[0]).text());
var txt = $($(this).children("option:selected")[0]).text();
$("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
});
});
</script>
PS:- Set height of div#selText otherwise it will keep shifting select list downward.
You could achieve this without having to import traceback:
try:
func1()
except Exception as ex:
trace = []
tb = ex.__traceback__
while tb is not None:
trace.append({
"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno
})
tb = tb.tb_next
print(str({
'type': type(ex).__name__,
'message': str(ex),
'trace': trace
}))
Output:
{
'type': 'ZeroDivisionError',
'message': 'division by zero',
'trace': [
{
'filename': '/var/playground/main.py',
'name': '<module>',
'lineno': 16
},
{
'filename': '/var/playground/main.py',
'name': 'func1',
'lineno': 11
},
{
'filename': '/var/playground/main.py',
'name': 'func2',
'lineno': 7
},
{
'filename': '/var/playground/my.py',
'name': 'test',
'lineno': 2
}
]
}
The key is in the quotes around the colon and &, i.e. rows(variable & ":" & variable).select
Adapt this:
Rows(x & ":" & y).select
where x and y are your variables.
Some other examples that may help you understand
Rows(x & ":" & x).select
Or
Rows((x+1) & ":" (x*3)).select
Or
Rows((x+2) & ":" & (y-3)).select
Hopefully you get the idea.
For those of you looking for a Swift 4 solution to this answer, you can use the following to detect a touch event on a UIImageView.
let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true
You will then need to define your selector as follows:
@objc func imageViewTapped() {
// Image has been tapped
}
USE this , Don't forget to get a google api key from
https://console.developers.google.com/apis/credentials
and replace it
<div id="map" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var myCenter = new google.maps.LatLng(38.224905, 48.252143);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: myCenter, zoom: 16};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({position:myCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=myMap"></script>
Assuming the items override ToString
appropriately:
public void WriteToConsole(IEnumerable items)
{
foreach (object o in items)
{
Console.WriteLine(o);
}
}
(There'd be no advantage in using generics in this loop - we'd end up calling Console.WriteLine(object)
anyway, so it would still box just as it does in the foreach
part in this case.)
EDIT: The answers using List<T>.ForEach
are very good.
My loop above is more flexible in the case where you have an arbitrary sequence (e.g. as the result of a LINQ expression), but if you definitely have a List<T>
I'd say that List<T>.ForEach
is a better option.
One advantage of List<T>.ForEach
is that if you have a concrete list type, it will use the most appropriate overload. For example:
List<int> integers = new List<int> { 1, 2, 3 };
List<string> strings = new List<string> { "a", "b", "c" };
integers.ForEach(Console.WriteLine);
strings.ForEach(Console.WriteLine);
When writing out the integers, this will use Console.WriteLine(int)
, whereas when writing out the strings it will use Console.WriteLine(string)
. If no specific overload is available (or if you're just using a generic List<T>
and the compiler doesn't know what T
is) it will use Console.WriteLine(object)
.
Note the use of Console.WriteLine
as a method group, by the way. This is more concise than using a lambda expression, and actually slightly more efficient (as the delegate will just be a call to Console.WriteLine
, rather than a call to a method which in turn just calls Console.WriteLine
).
I strongly advice NOT to use the code:
process.setMaxListeners(0);
The warning is not there without reason. Most of the time, it is because there is an error hidden in your code. Removing the limit removes the warning, but not its cause, and prevents you from being warned of a source of resource leakage.
If you hit the limit for a legitimate reason, put a reasonable value in the function (the default is 10).
Also, to change the default, it is not necessary to mess with the EventEmitter prototype. you can set the value of defaultMaxListeners attribute like so:
require('events').EventEmitter.defaultMaxListeners = 15;
This topic is confusing because there are 3 terms in use when people think there are just 2, namely:
"bit rate": units are bits per second
"baud": units are symbols per second
"Baud rate": units are bits per second
"Baud rate" is really a marketing term rather than an engineering term. "Baud rate" was used by modem manufactures in a similar way to megapixels is used for digital cameras. So the higher the "Baud rate" the better the modem was perceived to be.
The engineering unit "baud" is already a rate (symbols per second) which distinguishes it from the "Baud rate" term. However, you can see from the answers that people are confusing these 2 terms together such as baud/sec which is wrong.
From an engineering point of view, I recommend people use the term "bit rate" for "RS-232" and consign to history the term "Baud rate". Use the term "baud" for modulation schemes but avoid it for "RS-232".
In other words, "bit rate" and "Baud rate" are the same thing which means how many bits are transmitted along a wire in one second. Note that bits per second (bps) is the low-level line rate and not the information data rate because asynchronous "RS-232" has start and stop bits that frame the 8 data bits of information so bps includes all bits transmitted.
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.
As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.
In the case you have different sample sizes, it may be difficult to compare the distributions with a single y-axis. For example:
import numpy as np
import matplotlib.pyplot as plt
#makes the data
y1 = np.random.normal(-2, 2, 1000)
y2 = np.random.normal(2, 2, 5000)
colors = ['b','g']
#plots the histogram
fig, ax1 = plt.subplots()
ax1.hist([y1,y2],color=colors)
ax1.set_xlim(-10,10)
ax1.set_ylabel("Count")
plt.tight_layout()
plt.show()
In this case, you can plot your two data sets on different axes. To do so, you can get your histogram data using matplotlib, clear the axis, and then re-plot it on two separate axes (shifting the bin edges so that they don't overlap):
#sets up the axis and gets histogram data
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist([y1, y2], color=colors)
n, bins, patches = ax1.hist([y1,y2])
ax1.cla() #clear the axis
#plots the histogram data
width = (bins[1] - bins[0]) * 0.4
bins_shifted = bins + width
ax1.bar(bins[:-1], n[0], width, align='edge', color=colors[0])
ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color=colors[1])
#finishes the plot
ax1.set_ylabel("Count", color=colors[0])
ax2.set_ylabel("Count", color=colors[1])
ax1.tick_params('y', colors=colors[0])
ax2.tick_params('y', colors=colors[1])
plt.tight_layout()
plt.show()
Here is another variation for a file upload that has a nicer looking bootstrap button than the default file upload browse button. This is the html:
<div class="form-group">
@Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "col-md-2 control-label" })
<div class="col-md-1 btn btn-sn btn-primary" id="browseButton" onclick="$(this).parent().find('input[type=file]').click();">browse</div>
<div class="col-md-7">
<input id="fileSpace" name="uploaded_file" type="file" style="display: none;"> @*style="display: none;"*@
@Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control", @id = "modelField"} })
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
</div>
Here is the script:
$('#fileSpace').on("change", function () {
$("#modelField").val($('input[name="uploaded_file"]').val());
@vladima replied to this issue on GitHub:
The way the compiler resolves modules is controlled by moduleResolution option that can be either
node
orclassic
(more details and differences can be found here). If this setting is omitted the compiler treats this setting to benode
if module iscommonjs
andclassic
- otherwise. In your case if you wantclassic
module resolution strategy to be used withcommonjs
modules - you need to set it explicitly by using{ "compilerOptions": { "moduleResolution": "node" } }
I'd suggest <a href='page1.jsp'>Refresh</a>
.
I don't think "have HTTPS connections over proxy servers" means the Man-in-the-Middle attack type of proxy server. I think it's asking whether one can connect to a http proxy server over TLS. And the answer is yes.
Is it possible to have HTTPS connections over proxy servers?
Yes, see my question and answer here. HTTPs proxy server only works in SwitchOmega
If yes, what kind of proxy server allows this?
The kind of proxy server deploys SSL certificates, like how ordinary websites do. But you need a pac
file for the brower to configure proxy connection over SSL.
Use:
tabControl1.TabPages[1].Enabled = false;
By writing this code, the tab page won't be completely disabled (not being able to select), but its internal content will be disabled which I think satisfy your needs.
You should use git pull --rebase
when
Indeed -- why not then? It's more clear, and doesn't impose a logical grouping on your commits.
Ok, I suppose it needs some clarification. In Git, as you probably know, you're encouraged to branch and merge. Your local branch, into which you pull changes, and remote branch are, actually, different branches, and git pull
is about merging them. It's reasonable, since you push not very often and usually accumulate a number of changes before they constitute a completed feature.
However, sometimes--by whatever reason--you think that it would actually be better if these two--remote and local--were one branch. Like in SVN. It is here where git pull --rebase
comes into play. You no longer merge--you actually commit on top of the remote branch. That's what it actually is about.
Whether it's dangerous or not is the question of whether you are treating local and remote branch as one inseparable thing. Sometimes it's reasonable (when your changes are small, or if you're at the beginning of a robust development, when important changes are brought in by small commits). Sometimes it's not (when you'd normally create another branch, but you were too lazy to do that). But that's a different question.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("jdbc:oracle:thin:@machinename:portnum:schemaname","userid","password");
I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress()
:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink()
method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.
I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.
This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.
To call it:
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).
Here's the code:
<?php
function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)
{
if (!isset($dttm))
{
return "";
}
$timepieces = array();
if (is_numeric($dttm))
{
$rettime=$dttm;
}
else
{
$rettime=strtotime($dttm);
if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)
{
$rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
$timepieces[1]="";
}
else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)
{
preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
$rettime=$rettime.".".$timepieces[1];
}
}
if (isset($dtFormat))
{
// RETURN as ANY date format sent
if (strpos($dtFormat,".u")>0) // Deal with milliseconds
{
$rettime=date($dtFormat,$rettime);
$rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];
}
else // NO milliseconds wanted
{
$rettime=date($dtFormat,$rettime);
}
}
else
{
// RETURN Epoch Time (do nothing, we already built Epoch Time)
}
return $rettime;
}
?>
Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).
$utctime1="2018-10-30T06:10:11.2185007-07:00";
$utctime2="2018-10-30T06:10:11.2185007";
$utctime3="2018-10-30T06:10:11.2185007 PDT";
$utctime4="2018-10-30T13:10:11.2185007Z";
$utctime5="2018-10-30T13:10:11Z";
$dttm="10/30/2018 09:10:11 AM EST";
echo "<pre>";
echo "<b>Epoch Time to a standard format</b><br>";
echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
echo "</b><br>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
echo "<hr>";
echo "<hr>";
echo "<b>Returned as whatever datetime format one desires</b>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<p><b>Returned as ISO8601</b>";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
echo "</pre>";
Here's the output:
Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11
Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
Returned as whatever datetime format one desires
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
Returned as ISO8601
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601
The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.
You should be able to do this if you create the column using the GUI in Management Studio. I believe Management studio is actually completely recreating the table, which is why this appears to happen.
As others have mentioned, the order of columns in a table doesn't matter, and if it does there is something wrong with your code.
While adding 'DirectoryIndex index.php' to a .htaccess file may work,
NOTE:
In general, you should never use .htaccess files
This is quoted from http://httpd.apache.org/docs/1.3/howto/htaccess.html
Although this refers to an older version of apache, I believe the principle still applies.
Adding the following to your httpd.conf (if you have access to it) is considered better form, causes less server overhead and has the exact same effect:
<Directory /myapp>
DirectoryIndex index.php
</Directory>
Unless you call some function this is not at all trivial. (And, seriously, there's no real difference in complexity between calling printf and calling a win32 api function.)
Even DOS int 21h is really just a function call, even if its a different API.
If you want to do it without help you need to talk to your video hardware directly, likely writing bitmaps of the letters of "Hello world" into a framebuffer. Even then the video card is doing the work of translating those memory values into DisplayPort/HDMI/DVI/VGA signals.
Note that, really, none of this stuff all the way down to the hardware is any more interesting in ASM than in C. A "hello world" program boils down to a function call. One nice thing about ASM is that you can use any ABI you want fairly easily; you just need to know what that ABI is.
If you assume that values exist for all activities in both years then just do an inner join as follows
select act.activity, t1.amount as "Total 2009", t2.amount as "Total 2008"
from Activities as act,
(select activityid, SUM(Amount) as amount
from Activities, Incomes
where Activities.UnitName = ? AND
Incomes.ActivityId = Activities.ActivityID
GROUP BY Activityid) as t1,
(select activityid, SUM(Amount) as amount
from Activities, Incomes2008
where Activities.UnitName = ? AND
Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activityid) as t2
WHERE t1.activityid= t2.activityid
AND act.activityId = t1.activityId
ORDER BY act.activity
If you can't assume this, then look at doing an outer join
Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
});
t1.start();
or
new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
}).start();
or
new Thread(() -> {
// code goes here.
}).start();
or
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
or
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
This would become a bit more clear if you add a line to both examples:
var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");
The second one:
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
console.log(result.length);
});
console.log("Hello World");
Try running these, and you’ll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line. In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.
That's because in the second example, the database.query
is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length)
is only executed when the database query has completed.
In case you're trying to access an item
from the example structure by id
or name
, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
_.find(data.items, function(item) {
return item.id === 2;
});
// Object {id: 2, name: "bar"}
From my experience, using higher order functions instead of for
or for..in
loops results in code that is easier to reason about, and hence more maintainable.
Just my 2 cents.
Simple example below. Note you should pass in a larger buffer, and test to see if the buffer was large enough or not
void Log(LPCWSTR pFormat, ...)
{
va_list pArg;
va_start(pArg, pFormat);
char buf[1000];
int len = _vsntprintf(buf, 1000, pFormat, pArg);
va_end(pArg);
//do something with buf
}
Please try below:
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
I tried to push to my own hosted bonobo-git server, and did not realise, that the http.postbuffer meant the project directory ...
so just for other confused ones:
why? In my case, I had large zip files with assets and some PSDs pushed as well - to big for the buffer I guess.
How to do this http.postbuffer: execute that command within your project src directory, next to the .git folder, not on the server.
be aware, large temp (chunk) files will be created of that buffer size.
Note: Just check your largest files, then set the buffer.
You can do
$('video').trigger('play');
$('video').trigger('pause');
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii')
.
push()
is for arrays, not objects, so use the right data structure.
var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals()
method. With your example, results.userId.equals(AnotherMongoDocument._id)
. The ObjectID type also has a toString()
method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.
If you use ObjectID = require("mongodb").ObjectID
(requires the mongodb-native library) you can check if results.userId
is a valid identifier with results.userId instanceof ObjectID
.
Etc.
Here's a compact way to do something different in all four cases:
if(empty($youtube)) {
if(empty($link)) {
# both empty
} else {
# only $youtube not empty
}
} else {
if(empty($link)) {
# only $link empty
} else {
# both not empty
}
}
If you want to use an expression instead, you can use ?:
instead:
echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
: ( empty($link) ? 'only $link empty' : 'both not empty' );
There is also a property resourceRef
of JndiObjectFactoryBean
that is, when set to true
, used to automatically prepend the string java:comp/env/
if it is not already present.
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/loc"/>
<property name="resourceRef" value="true"/>
</bean>
function String2Stars($string='',$first=0,$last=0,$rep='*'){
$begin = substr($string,0,$first);
$middle = str_repeat($rep,strlen(substr($string,$first,$last)));
$end = substr($string,$last);
$stars = $begin.$middle.$end;
return $stars;
}
example
$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5); // abcde****************vwxyz
Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.
Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.
You need to have better understanding of the python language and its standard library to translate the expression
cat "$filename": Reads the file cat "$filename"
and dumps the content to stdout
|
: pipe redirects the stdout
from previous command and feeds it to the stdin
of the next command
grep "something": Searches the regular expressionsomething
plain text data file (if specified) or in the stdin and returns the matching lines.
cut -d'"' -f2: Splits the string with the specific delimiter and indexes/splices particular fields from the resultant list
Python Equivalent
cat "$filename" | with open("$filename",'r') as fin: | Read the file Sequentially
| for line in fin: |
-----------------------------------------------------------------------------------
grep 'something' | import re | The python version returns
| line = re.findall(r'something', line)[0] | a list of matches. We are only
| | interested in the zero group
-----------------------------------------------------------------------------------
cut -d'"' -f2 | line = line.split('"')[1] | Splits the string and selects
| | the second field (which is
| | index 1 in python)
import re
with open("filename") as origin_file:
for line in origin_file:
line = re.findall(r'something', line)
if line:
line = line[0].split('"')[1]
print line
Try:
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
This will work for MySQL, Postgres, and probably any other PDO driver that uses the LIMIT
clause.
Notice LIMIT 0
is added for improved performance:
$rs = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
This is how I solved similar problem:
I hope it can help solve your problem too.
This is what you need : ternary operator, please take a look at this
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
Nice you gave me something to play around with
Run
class Sample extends Creator {
}
$a = new Sample ();
$a->role->rolename = 'test';
echo $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo $a->role->rolename , PHP_EOL;
echo $a->role->rolename->am->love->php , PHP_EOL;
Output
test
test
w00
Class Used
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
$this->{$name} = new Value ( $name, $value );
}
}
class Value extends Creator {
private $name;
private $value;
function __construct($name, $value) {
$this->name = $name;
$this->value = $value;
}
function __toString()
{
return (string) $this->value ;
}
}
class Sample extends Creator {
}
$a = new Sample ();
$a->role = array (
"A",
"B",
"C"
);
$a->role[0]->nice = "OK" ;
print ($a->role[0]->nice . PHP_EOL);
$a->role[1]->nice->ok = array("foo","bar","die");
print ($a->role[1]->nice->ok[2] . PHP_EOL);
$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;
print ($a->role[2]->nice->raw->name. PHP_EOL);
Output
Ok die baba
Modified Class
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
}
class Value {
private $name ;
function __construct($name, $value) {
$this->{$name} = $value;
$this->name = $value ;
}
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
if ($name == $this->name) {
return $this->value;
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
public function __toString() {
return (string) $this->name ;
}
}
# . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh
# sqlplus /nolog
SQL> connect sys/password as sysdba
SQL> EXEC DBMS_XDB.SETLISTENERLOCALACCESS(FALSE);
SQL> CONNECT sys/password@hostname:1521 as sysdba
What I do when I wonder something like the question asked here is go to the source.
expect().toBe()
is defined as:
function toBe() {
return {
compare: function(actual, expected) {
return {
pass: actual === expected
};
}
};
}
It performs its test with ===
which means that when used as expect(foo).toBe(true)
, it will pass only if foo
actually has the value true
. Truthy values won't make the test pass.
expect().toBeTruthy()
is defined as:
function toBeTruthy() {
return {
compare: function(actual) {
return {
pass: !!actual
};
}
};
}
A value is truthy if the coercion of this value to a boolean yields the value true
. The operation !!
tests for truthiness by coercing the value passed to expect
to a boolean. Note that contrarily to what the currently accepted answer implies, == true
is not a correct test for truthiness. You'll get funny things like
> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false
Whereas using !!
yields:
> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![]
true
(Yes, empty or not, an array is truthy.)
expect().toBeTrue()
is part of Jasmine-Matchers (which is registered on npm as jasmine-expect
after a later project registered jasmine-matchers
first).
expect().toBeTrue()
is defined as:
function toBeTrue(actual) {
return actual === true ||
is(actual, 'Boolean') &&
actual.valueOf();
}
The difference with expect().toBeTrue()
and expect().toBe(true)
is that expect().toBeTrue()
tests whether it is dealing with a Boolean
object. expect(new Boolean(true)).toBe(true)
would fail whereas expect(new Boolean(true)).toBeTrue()
would pass. This is because of this funny thing:
> new Boolean(true) === true
false
> new Boolean(true) === false
false
At least it is truthy:
> !!new Boolean(true)
true
elem.isDisplayed()
?Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed()
is a promise that resolves to a boolean
. I would take it at face value and use .toBeTrue()
or .toBe(true)
. If I found a case where the implementation returns truthy/falsy values, I would file a bug report.
for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d
pushd %curdir%
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.
<?php
session_start();
session_regenerate_id(true);
?>
In Python 3.x, local timezone can be figured out like this:
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
It's a tricky use of datetime
's code .
For python >= 3.6, you'll need
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo