func viewDidLoad(){
let homeBtn: UIButton = UIButton(type: UIButtonType.custom)
homeBtn.setImage(UIImage(named: "Home.png"), for: [])
homeBtn.addTarget(self, action: #selector(homeAction), for: UIControlEvents.touchUpInside)
homeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let homeButton = UIBarButtonItem(customView: homeBtn)
let backBtn: UIButton = UIButton(type: UIButtonType.custom)
backBtn.setImage(UIImage(named: "back.png"), for: [])
backBtn.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside)
backBtn.frame = CGRect(x: -10, y: 0, width: 30, height: 30)
let backButton = UIBarButtonItem(customView: backBtn)
self.navigationItem.setLeftBarButtonItems([backButton,homeButton], animated: true)
}
}
I had one problem because when I tried to change my NavigationItem title programmatically i was not able to find my family font (tried many things but impossible to make it run correctly) so I found one workaround very nice and easy in storyboard.
Finally you should have something like that in document outline:
And something like that in your ViewController:
Hope it can help.
The only thing you have to do is to add in the cshtml file, in the head, the following line:
@Styles.Render("~/Content/Main.css")
The entire head will look somethink like that:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Page</title>
@Styles.Render("~/Content/main.css")
</head>
Hope it helps!!
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
After watching the DevBytes video (by Roman Nurik) and reading the very last line in the docs, which says:
Note: If you like the auto-hiding behavior of IMMERSIVE_STICKY but need to show your own UI controls as well, just use IMMERSIVE combined with Handler.postDelayed() or something similar to re-enter immersive mode after a few seconds.
the answer, radu122 gave, worked for me. Just setup a handler and your will be good to go.
Here is the code which works for me:
@Override
protected void onResume() {
super.onResume();
executeDelayed();
}
private void executeDelayed() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// execute after 500ms
hideNavBar();
}
}, 500);
}
private void hideNavBar() {
if (Build.VERSION.SDK_INT >= 19) {
View v = getWindow().getDecorView();
v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
Google says "after a few seconds" - but I want to provide this functionality as soon as possible. Maybe I will change the value later, if I have to, I will update this answer.
Snippets:
HideNavigationBarComponent.java
This is for Android 4.4+
Try out immersive mode https://developer.android.com/training/system-ui/immersive.html
Fast snippet (for an Activity class):
private int currentApiVersion;
@Override
@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
currentApiVersion = android.os.Build.VERSION.SDK_INT;
final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
// This work only for android 4.4+
if(currentApiVersion >= Build.VERSION_CODES.KITKAT)
{
getWindow().getDecorView().setSystemUiVisibility(flags);
// Code below is to handle presses of Volume up or Volume down.
// Without this, after pressing volume buttons, the navigation bar will
// show up and won't hide
final View decorView = getWindow().getDecorView();
decorView
.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener()
{
@Override
public void onSystemUiVisibilityChange(int visibility)
{
if((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0)
{
decorView.setSystemUiVisibility(flags);
}
}
});
}
}
@SuppressLint("NewApi")
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if(currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus)
{
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
If you have problems when you press Volume up or Volume down that your navigation bar show. I added code in onCreate
see setOnSystemUiVisibilityChangeListener
Here is another related question:
Immersive mode navigation becomes sticky after volume press or minimise-restore
Instead of creating selector, Best way to create a style.
<style name="AppTheme.BottomBar">
<item name="colorPrimary">@color/colorAccent</item>
</style>
and to change the text size, selected or non selected.
<dimen name="design_bottom_navigation_text_size" tools:override="true">11sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">12sp</dimen>
Enjoy Android!
<color name="blackColorPrimary">#000001</color> (not #000000)
<item name="android:navigationBarColor" tools:targetApi="lollipop">@color/blackColorPrimary</item>
Problem is that android higher version make trasparent for #000000
You can use querySelectorAll()
like this:
var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
This translates to:
get all inputs with the attribute "value" and has the attribute "value" that is not blank.
In this demo, it disables the checkbox with a non-blank value.
Providing you know these vim commands:
1G -> go to first line in file
G -> go to last line in file
then, the following make more sense, are more unitary and easier to remember IMHO:
d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file
Cheers.
Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
As of Python 3.6 (2016) you can use f-strings to substitute variables:
>>> origin = "London"
>>> destination = "Paris"
>>> f"from {origin} to {destination}"
'from London to Paris'
Note the f"
prefix. If you try this in Python 3.5 or earlier, you'll get a SyntaxError
.
See https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings
if you're using SQL Server,
dateadd(DAY,0, datediff(day,0, created))
will return the day created
for example, if the sale created on '2009-11-02 06:12:55.000',
dateadd(DAY,0, datediff(day,0, created))
return '2009-11-02 00:00:00.000'
select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))
Update MyTable
Set Value = (
Select Min( T2.Value )
From MyTable As T2
Where T2.Id <> MyTable.Id
And T2.Name = MyTable.Name
)
Where ( Value Is Null Or Value = '' )
And Exists (
Select 1
From MyTable As T3
Where T3.Id <> MyTable.Id
And T3.Name = MyTable.Name
)
If you are on Mac OS X or Ubuntu, the problem is caused by the symlinks to the JDK. File | Invalidate Caches should help. If it doesn't, specify the JDK path to the direct JDK Home folder, not a symlink.
Invalidate Caches menu item is available under IntelliJ IDEA File menu.
Direct JDK path after the recent Apple Java update is:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
In IDEA you can configure the new JSDK in File | Project Structure, select SDKs on the left, then press [+] button, then specify the above JDK home path, you should get something like this:
A linked list can be used to implement a queue. The canonical real life example would be a line for a cashier.
A linked list can also be used to implement a stack. The cononical real ife example would be one of those plate dispensers at a buffet restaurant where pull the top plate off the top of the stack.
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
or
function createOfferUrlArray($offer) {
foreach ( $offer as &$value ) {
$value = $value[4];
}
unset($value);
return $offer;
}
The \caption
command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:
\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}
The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof
command of the caption package can be used to place a caption outside of a floating environment. It is used like this:
\[ E = m c^2 \]
\captionof{figure}{A famous equation}
This will also produce an entry for the \listoffigures
, if your document has one.
To align parts of an equation, take a look at the eqnarray
environment, or some of the environments of the amsmath package: align, gather, multiline,...
I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:
listing package
The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.
Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.
The following code
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
produces the following image:
minted package
The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with
python --version
and you can install pygments with
sudo apt-get install python-pygments
Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this
pdflatex -shell-escape yourfile.tex
If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.
The following code
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{html}
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{minted}
\end{document}
produces the following image:
In my case, the error message referred to an old filename, which did no longer exist because it was renamed. It turned out that the outdated information did not come from the Makefile, but from files in .deps
directories.
I ran into this error after copying files from one machine to another. In that process, I assume the timestamps got in an inconsistent state, which confused "make" when running multiple jobs in parallel (similar to this bug report).
Sequential builds with make -j 1
were not affected, but it took me a while to realize because I was using an alias (make -j 8
).
To clean up the state, I removed all .deps
files and regenerated the Makefile. These are the commands that I used:
find | grep '.deps' | xargs rm
find | grep '.deps' | xargs rmdir
autoreconf --install # (optional, but my project is using autotools)
./configure
After that, building worked again.
You can try Context.getApplicationInfo().dataDir
if you want the package's persistent data folder.
getFilesDir()
returns a subroot of this.
Something like this should work:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
Rails has a built in way to seed data as explained here.
Another way would be to use a gem for more advanced or easy seeding such as: seedbank.
The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.
Adding an up to date answer as this answer was first on google.
A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.
Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.
An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.
Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.
As of Octoer 2020, the dimensions for Launcher, ActionBar/Tab and Notification icons are:
A very good online tool to generate launcher icons : https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
I found jszip quite useful. I've used so far only for reading, but they have create/edit capabilities as well.
Code wise it looks something like this
var new_zip = new JSZip();
new_zip.load(file);
new_zip.files["doc.xml"].asText() // this give you the text in the file
One thing I noticed is that it seems the file has to be in binary stream format (read using the .readAsArrayBuffer of FileReader(), otherwise I was getting errors saying I might have a corrupt zip file
Edit: Note from the 2.x to 3.0.0 upgrade guide:
The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().
Thanks user2677034
You may want to tackle this as follows:
CREATE TABLE comments (
comment_id int,
body varchar(100),
PRIMARY KEY (comment_id)
);
CREATE TABLE users (
user_id int,
username varchar(20),
PRIMARY KEY (user_id)
);
CREATE TABLE comments_votes (
comment_id int,
user_id int,
vote_type int,
PRIMARY KEY (comment_id, user_id)
);
The composite primary key (comment_id, user_id)
on the intersection table comments_votes
will prevent users from voting multiple times on the same comments.
Let's insert some data in the above schema:
INSERT INTO comments VALUES (1, 'first comment');
INSERT INTO comments VALUES (2, 'second comment');
INSERT INTO comments VALUES (3, 'third comment');
INSERT INTO users VALUES (1, 'user_a');
INSERT INTO users VALUES (2, 'user_b');
INSERT INTO users VALUES (3, 'user_c');
Now let's add some votes for user 1:
INSERT INTO comments_votes VALUES (1, 1, 1);
INSERT INTO comments_votes VALUES (2, 1, 1);
The above means that user 1 gave a vote of type 1 on comments 1 and 2.
If the same user tries to vote again on one of those comments, the database will reject it:
INSERT INTO comments_votes VALUES (1, 1, 1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'
If you will be using the InnoDB storage engine, it will also be wise to use foreign key constraints on the comment_id
and user_id
fields of the intersection table. However note that MyISAM, the default storage engine in MySQL, does not enforce foreign key constraints:
CREATE TABLE comments (
comment_id int,
body varchar(100),
PRIMARY KEY (comment_id)
) ENGINE=INNODB;
CREATE TABLE users (
user_id int,
username varchar(20),
PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE comments_votes (
comment_id int,
user_id int,
vote_type int,
PRIMARY KEY (comment_id, user_id),
FOREIGN KEY (comment_id) REFERENCES comments (comment_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
) ENGINE=INNODB;
These foreign keys guarantee that a row in comments_votes
will never have a comment_id
or user_id
value that doesn't exist in the comments
and users
tables, respectively. Foreign keys aren't required to have a working relational database, but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).
In fact, referential integrity is something that would have been very difficult to enforce if you were to store serialized arrays into a single database field.
This should work:
public static dynamic Cast(dynamic obj, Type castTo)
{
return Convert.ChangeType(obj, castTo);
}
Edit
I've written the following test code:
var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"
It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)
EDIT: This answer was correct until mid-2013, but you may have a more recent version since the big msbuild change. See the answer from Jonny Leeds for more details.
The version under C:\Windows\Microsoft.NET\Framework\v4.0.30319
actually is .NET 4.5. It's a little odd, but certainly mscorlib
there contains AsyncTaskMethodBuilder
etc which are used for async.
.NET 4.5 effectively overwrites .NET 4.
It is a RAM related issue. The documentation is self explanatory:
You are trying to allocate >3GB of RAM to the VM. This requires: (a) a 64 bit host system; and (b) true hardware pass-through ie VT-x.
Fast solution
Allocate less than 3GB for the virtual machine.
Complete solution
Best Option to use text and image in a single view try this:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableBottom="@drawable/ic_launcher"
android:text="TextView" />
You can write a simple one liner with a ternary and if you make use of the builder pattern of the StringBuffer from .getRequestURL()
:
private String getUrlWithQueryParms(final HttpServletRequest request) {
return request.getQueryString() == null ? request.getRequestURL().toString() :
request.getRequestURL().append("?").append(request.getQueryString()).toString();
}
But that is just syntactic sugar.
I have query,
$("#login-button").click(function(e){ alert("hiii");
var username = $("#username-field").val();
var password = $("#username-field").val();
alert(username);
alert("password" + password);
var markers = { "userName" : "admin","password" : "admin123"};
$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("got the data"+data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
I'm posting the the login details in json and getting a string as "Success"
,but I'm not getting the response.
Check this. This image will show for all icon size for different screen sizes
Here are the steps I went through in getting ffmpeg to work on Android:
make
away. You'll need to extract bionic(libc) and zlib(libz) from the Android build as well, as ffmpeg libraries depend on them.Create a dynamic library wrapping ffmpeg functionality using the Android NDK. There's a lot of documentation out there on how to work with the NDK. Basically you'll need to write some C/C++ code to export the functionality you need out of ffmpeg into a library java can interact with through JNI. The NDK allows you to easily link against the static libraries you've generated in step 1, just add a line similar to this to Android.mk: LOCAL_STATIC_LIBRARIES := libavcodec libavformat libavutil libc libz
Use the ffmpeg-wrapping dynamic library from your java sources. There's enough documentation on JNI out there, you should be fine.
Regarding using ffmpeg for playback, there are many examples (the ffmpeg binary itself is a good example), here's a basic tutorial. The best documentation can be found in the headers.
Good luck :)
There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.
Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.
MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits.
By using lambdaj you can sort a collection of your contacts (for example by their name) as it follows
sort(contacts, on(Contact.class).getName());
or by their address:
sort(contacts, on(Contacts.class).getAddress());
and so on. More in general, it offers a DSL to access and manipulate your collections in many ways, like filtering or grouping your contacts based on some conditions, aggregate some of their property values, etc.
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace
method with your Base64String and replace "image/png"
with "image/octet-stream"
:
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {_x000D_
const img = document.getElementById('embedImage');_x000D_
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
'9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
_x000D_
const button = document.getElementById('saveImage');_x000D_
button.addEventListener('click', () => {_x000D_
window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<img id="embedImage" alt="Red dot" />_x000D_
<button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Here's an Add to Calendar service to serve the purpose for adding an event on
The "Add to Calendar" button for events on websites and calendars is easy to install, language independent, time zone and DST compatible. It works perfectly in all modern browsers, tablets and mobile devices, and with Apple Calendar, Google Calendar, Outlook, Outlook.com and Yahoo Calendar.
<div title="Add to Calendar" class="addeventatc">
Add to Calendar
<span class="start">03/01/2018 08:00 AM</span>
<span class="end">03/01/2018 10:00 AM</span>
<span class="timezone">America/Los_Angeles</span>
<span class="title">Summary of the event</span>
<span class="description">Description of the event</span>
<span class="location">Location of the event</span>
</div>
The following function rot(s, n)
encodes a string s
with ROT-n
encoding for any integer n
, with n
defaulting to 13. Both upper- and lowercase letters are supported. Values of n
over 26 or negative values are handled appropriately, e.g., shifting by 27 positions is equal to shifting by one position. Decoding is done with invrot(s, n)
.
import string
def rot(s, n=13):
'''Encode string s with ROT-n, i.e., by shifting all letters n positions.
When n is not supplied, ROT-13 encoding is assumed.
'''
upper = string.ascii_uppercase
lower = string.ascii_lowercase
upper_start = ord(upper[0])
lower_start = ord(lower[0])
out = ''
for letter in s:
if letter in upper:
out += chr(upper_start + (ord(letter) - upper_start + n) % 26)
elif letter in lower:
out += chr(lower_start + (ord(letter) - lower_start + n) % 26)
else:
out += letter
return(out)
def invrot(s, n=13):
'''Decode a string s encoded with ROT-n-encoding
When n is not supplied, ROT-13 is assumed.
'''
return(rot(s, -n))
This is an older post, but I do have a better solution. Create a form containing all of your post values as hidden fields and give the form a name such as:
<form name="RefreshForm" method="post" action="http://yoursite/yourscript">
<input type="hidden" name="postVariable" value="PostData">
</form>
Then all you need to do in your setTimeout
is RefreshForm.submit();
Cheers!
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}
or you could wrap in foreach loop to print each value
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
foreach(XmlNode curr in n) {
Console.WriteLine(curr.InnerText);
}
}
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
This is an example with the non deprecated ArgumentMatchers class
when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<String>>any()))
.thenReturn(responseEntity);
You can index and use a negative sign to drop the 3rd column:
data[,-3]
Or you can list only the first 2 columns:
data[,c("c1", "c2")]
data[,1:2]
Don't forget the comma and referencing data frames works like this: data[row,column]
For anyone running into a problem where build automatically is unchecked but the project is still building. Make sure your project isn't deployed to the server in the server tab and told to stay synchronous.
Heres a good one with NSRegularExpression that's working for me.
[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;
You can insert whatever regex you want but I like being able to do it in one line.
I came up with a utility and hosted on GitHub to clean old versions of libraries in the local Maven repository. The utility, on its default execution removes all older versions of artifacts leaving only the latest ones. Optionally, it can remove all snapshots, sources, javadocs, and also groups or artifacts can be forced / excluded in this process. This cross platform also supports date based removal based on last access / download dates.
The accepted answer is not ideal, so I decided to add my 2 cents
timeStamp.toLocalDateTime().toLocalDate();
is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.
The good solution is
timestamp.toInstant().atZone(zoneId).toLocalDate()
Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC
The general approach should be
In addition to @Bruno's answer, you need to supply the -name
for alias, otherwise Tomcat will throw Alias name tomcat does not identify a key entry
error
Sample Command:
openssl pkcs12 -export -in localhost.crt -inkey localhost.key -out localhost.p12 -name localhost
In my case, the error was valid and it was due to using try with resource
try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
"classpath:application-main-config.xml")) {..
}
It auto closes the stream which should not happen if I want to reuse this context in other beans.
You could use the load()-event in jQuery but it won't always fire if the image is loaded from the browser cache. This plugin https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js can be used to remedy that problem.
catch needs to return an observable.
.catch(e => { console.log(e); return Observable.of(e); })
if you'd like to stop the pipeline after a caught error, then do this:
.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)
this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.
edit:
better way of stopping the pipeline is to do
.catch(e => Observable.empty())
Ubuntu Firefox giving CORS failed error when my request took more than 10 seconds to process.
Nothing to do with CORS. Problem is with ubuntu firefox configuration.
I have updated network.notify.changed to false which made this fix.
Mozilla Bugs Reference:
This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
The accepted answer is great. Just want to point out some things for others coming here. Margins are not necessary in these cases. If you want a centered layout with a specific "Margin", you can add them to the right and left, like so:
.stretched {
position: absolute;
right: 50px; top: 0; bottom: 0; left: 50px;
margin: auto;
}
This is extremely useful.
As a bonus, absolute centering which can be used to get extremely simple centering:
.centered {
height: 100px; width: 100px;
right: 0; top: 0; bottom: 0; left: 0;
margin: auto;
position: absolute;
}
To style for many smartphones with smaller screens, you could write:
@media screen and (max-width:480px) { … }
To block older browsers from seeing an iPhone or Android phone style sheet, you could write:
@media only screen and (max-width: 480px;) { … }
Read this article for more http://webdesign.about.com/od/css3/a/css3-media-queries.htm
With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.
Default parameters in JavaScript can be implemented in mainly two ways:
function myfunc(a, b)
{
// use this if you specifically want to know if b was passed
if (b === undefined) {
// b was not passed
}
// use this if you know that a truthy value comparison will be enough
if (b) {
// b was passed and has truthy value
} else {
// b was not passed or has falsy value
}
// use this to set b to a default value (using truthy comparison)
b = b || "default value";
}
The expression b || "default value"
evaluates the value AND existence of b
and returns the value of "default value"
if b
either doesn't exist or is falsy.
Alternative declaration:
function myfunc(a)
{
var b;
// use this to determine whether b was passed or not
if (arguments.length == 1) {
// b was not passed
} else {
b = arguments[1]; // take second argument
}
}
The special "array" arguments
is available inside the function; it contains all the arguments, starting from index 0
to N - 1
(where N
is the number of arguments passed).
This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!
Although undefined
is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:
b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
this solved my issue, it was working fine with
var value = item[index].id;
$("#select2").val(value);
but not showing selected value, so
$("#select2").val(value).change();
works fine for me.
The error occurs in 'libcurl', which is the underlying protocol for https upload. Solution is to somehow updgrade libcurl. To get more details about the error, set GIT_CURL_VERBOSE=1
https://confluence.atlassian.com/pages/viewpage.action?pageId=306348908
Meaning of error, as per libcurl doc: CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.
an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).
It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio
A good description of all the tools are at AndroidOnRocks.com (site offline now)
However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick
A shorter alternative to the previously mentioned stash approach would be:
Temporarily move the changes to a stash.
git stash
Create and switch to a new branch and then pop the stash to it in just one step.
git stash branch new_branch_name
Then just add
and commit
the changes to this new branch.
These functions should work.
// First, cache your array dimensions so you don't have to
// access them during each iteration of your for loops.
int rowLength = array.length, // array width (# of columns)
colLength = array[0].length; // array height (# of rows)
// This is your function:
// Prints array elements row by row
var rowString = "";
for(int x = 0; x < rowLength; x++){ // x is the column's index
for(int y = 0; y < colLength; y++){ // y is the row's index
rowString += array[x][y];
} System.out.println(rowString)
}
// This is the one you want:
// Prints array elements column by column
var colString = "";
for(int y = 0; y < colLength; y++){ // y is the row's index
for(int x = 0; x < rowLength; x++){ // x is the column's index
colString += array[x][y];
} System.out.println(colString)
}
In the first block, the inner loop iterates over each item in the row before moving to the next column.
In the second block (the one you want), the inner loop iterates over all the columns before moving to the next row.
tl;dr:
Essentially, the for()
loops in both functions are switched. That's it.
I hope this helps you to understand the logic behind iterating over 2-dimensional arrays.
Also, this works whether you have a string[,] or string[][]
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
This will hide your console. Implement these lines in your code first to start hiding your console at first.
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
Update May 2020 :
If you've got trouble on pip install win32con
on Command Prompt, you can simply pip install pywin32
.Then on your python script, execute import win32.lib.win32con as win32con
instead of import win32con
.
To show back your program again win32con.SW_SHOW
works fine:
win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)
The command to modify the column is:
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME TYPE;
And we need to use type = BLOB
Example to modify is as under:-
ALTER TABLE messages MODIFY content BLOB;
I checked that latest mySQL and other databases don't need ''
to use in command on table_name, column_name etc.
Fetch and Save data:
Directly save the chat content to column and to retrieve data, fetch data as byte array (byte[])
from db column and then convert it to string
e.g. (Java code)
new String((byte[]) arr)
Use the autoescape
to turn HTML escaping off:
{% autoescape off %}{{ message }}{% endautoescape %}
Suppose you have two lists:
Id Value
1 A
2 B
3 C
Id ChildValue
1 a1
1 a2
1 a3
2 b1
2 b2
When you Join
the two lists on the Id
field the result will be:
Value ChildValue
A a1
A a2
A a3
B b1
B b2
When you GroupJoin
the two lists on the Id
field the result will be:
Value ChildValues
A [a1, a2, a3]
B [b1, b2]
C []
So Join
produces a flat (tabular) result of parent and child values.
GroupJoin
produces a list of entries in the first list, each with a group of joined entries in the second list.
That's why Join
is the equivalent of INNER JOIN
in SQL: there are no entries for C
. While GroupJoin
is the equivalent of OUTER JOIN
: C
is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null
).
So let the two lists be IEnumerable<Parent>
and IEnumerable<Child>
respectively. (In case of Linq to Entities: IQueryable<T>
).
Join
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }
returning an IEnumerable<X>
where X is an anonymous type with two properties, Value
and ChildValue
. This query syntax uses the Join
method under the hood.
GroupJoin
syntax would be
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
returning an IEnumerable<Y>
where Y is an anonymous type consisting of one property of type Parent
and a property of type IEnumerable<Child>
. This query syntax uses the GroupJoin
method under the hood.
We could just do select g
in the latter query, which would select an IEnumerable<IEnumerable<Child>>
, say a list of lists. In many cases the select with the parent included is more useful.
As said, the statement ...
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:
from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty() // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }
The result is similar to
Value Child
A a1
A a2
A a3
B b1
B b2
C (null)
Note that the range variable c
is reused in the above statement. Doing this, any join
statement can simply be converted to an outer join
by adding the equivalent of into g from c in g.DefaultIfEmpty()
to an existing join
statement.
This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:
parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
.SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )
So a flat outer join
in LINQ is a GroupJoin
, flattened by SelectMany
.
Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id
values in a fixed order. Let's use:
var ids = new[] { 3,7,2,4 };
Now the selected parents must be filtered from the parents list in this exact order.
If we do ...
var result = parents.Where(p => ids.Contains(p.Id));
... the order of parents
will determine the result. If the parents are ordered by Id
, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join
to filter the list. And by using ids
as first list, the order will be preserved:
from id in ids
join p in parents on id equals p.Id
select p
The result is parents 3, 7, 2, 4.
Here's a solution for find/replace in all files of a given directory. Basically I took the answer provided by sepp2k and expanded it.
# First set the files to search/replace in
files = Dir.glob("/PATH/*")
# Then set the variables for find/replace
@original_string_or_regex = /REGEX/
@replacement_string = "STRING"
files.each do |file_name|
text = File.read(file_name)
replace = text.gsub!(@original_string_or_regex, @replacement_string)
File.open(file_name, "w") { |file| file.puts replace }
end
You need to use df.shift
here.
df.shift(i)
shifts the entire dataframe by i
units down.
So, for i = 1
:
Input:
x1 x2
0 206 214
1 226 234
2 245 253
3 265 272
4 283 291
Output:
x1 x2
0 Nan Nan
1 206 214
2 226 234
3 245 253
4 265 272
So, run this script to get the expected output:
import pandas as pd
df = pd.DataFrame({'x1': ['206', '226', '245',' 265', '283'],
'x2': ['214', '234', '253', '272', '291']})
print(df)
df['x2'] = df['x2'].shift(1)
print(df)
I tried std::transform, all i get is abominable stl criptic compilation error that only druids from 200 years ago can understand (cannot convert from to flibidi flabidi flu)
this works fine and can be easily tweaked
string LowerCase(string s)
{
int dif='a'-'A';
for(int i=0;i<s.length();i++)
{
if((s[i]>='A')&&(s[i]<='Z'))
s[i]+=dif;
}
return s;
}
string UpperCase(string s)
{
int dif='a'-'A';
for(int i=0;i<s.length();i++)
{
if((s[i]>='a')&&(s[i]<='z'))
s[i]-=dif;
}
return s;
}
A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.
Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.
Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.
It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!
You might want to use the timeit module instead.
You should set the css property touch-action
to none
as described in this other answer https://stackoverflow.com/a/42288386/1128216
.disable-doubletap-to-zoom {
touch-action: none;
}
This solution is similar to the one from sroy, but with css triangle instead of web font:
.select-wrapper {_x000D_
position: relative;_x000D_
width: 200px;_x000D_
}_x000D_
.select-wrapper:after {_x000D_
content: "";_x000D_
width: 0;_x000D_
height: 0;_x000D_
border-left: 5px solid transparent;_x000D_
border-right: 5px solid transparent;_x000D_
border-top: 6px solid #666;_x000D_
position: absolute;_x000D_
right: 8px;_x000D_
top: 8px;_x000D_
pointer-events: none;_x000D_
}_x000D_
select {_x000D_
background: #eee;_x000D_
border: 0 !important;_x000D_
border-radius: 0;_x000D_
-webkit-appearance:none;_x000D_
-moz-appearance:none;_x000D_
appearance:none;_x000D_
text-indent: 0.01px;_x000D_
text-overflow: "";_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
width: 100%;_x000D_
}_x000D_
select::-ms-expand {_x000D_
display: none;_x000D_
}
_x000D_
<div class="select-wrapper">_x000D_
<select>_x000D_
<option value="1">option 1</option>_x000D_
<option value="2">option 2</option>_x000D_
<option value="3">option 3</option>_x000D_
</select>_x000D_
</div>
_x000D_
From Perlfaq8:
You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.
$exit_status = system("mail-users");
$output_string = `ls`;
There are many ways to execute external commands from Perl. The most commons with their meanings are:
The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.
For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):
#f22
at 0%
(that is the left edge of the element). First color is always assumed to start at 0%
even though the percentage is not mentioned explicitly.0%
to 14.25%
, the color changes from #f22
to #f2f
gradually. The percenatge is set at 14.25
because there are seven color changes and we are looking for equal splits.14.25%
(of the container's size), the color will exactly be #f2f
as per the gradient specified.14.25%
.So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.
.rainbow {_x000D_
background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text
.
(Note that the background-clip: text
is an experimental property and is not supported widely.)
Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:
to right
. If it should be red at right and brown at left then give the direction as to left
.red
as the first color (percentage is assumed to be 0%).50%
the color should be orange
and then the final color would be brown
. The position of the final color is always assumed to be at 100%.Thus the gradient's specification should read as follows:
background-image: linear-gradient(to right, red, orange 50%, brown).
If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.
.red-orange-brown {_x000D_
background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
$('input[name*="date"]').datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
beforeShow: function(input, instance) {
$(input).datepicker('setDate', new Date());
}
});
This works:
$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);
Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :
desired_capabilities['chromeOptions'] = {
"args": ["--disable-extensions"],
"extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)
Use a RelativeLayout
with layout_alignParentLeft
and layout_alignParentRight
:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="@+id/mytextview1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/mytextview2"/>
</RelativeLayout>
Also, you should probably be using dip
(or dp
) rather than sp
in your layout. sp
reflect text settings as well as screen density so they're usually only for sizing text items.
You can't cast an object to a Double
if the object is not a Double.
Check out the API.
particularly note
valueOf(double d);
and
valueOf(String s);
Those methods give you a way of getting a Double
instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.
Finally, keep in mind that Double
instances are immutable -- once created you can't change them.
We actually just upgraded a .NET web service to 4.6 to allow TLS 1.2.
What Artem is saying were the first steps we've done. We recompiled the framework of the web service to 4.6 and we tried change the registry key to enable TLS 1.2, although this didn't work: the connection was still in TLS 1.0. Also, we didn't want to disallow SLL 3.0, TLS 1.0 or TLS 1.1 on the machine: other web services could be using this; we rolled-back our changes on the registry.
We actually changed the Web.Config files to tell IIS: "hey, run me in 4.6 please".
Here's the changes we added in the web.config + recompilation in .NET 4.6:
<system.web>
<compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
<!--Added this httpRuntime -->
<httpRuntime targetFramework="4.6" />
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
And the connection changed to TLS 1.2, because IIS is now running the web service in 4.6 (told explicitly) and 4.6 is using TLS 1.2 by default.
Ok, this is actually four different question. I'll address them one by one:
are both equals for the compiler? (speed, perf...)
Yes. The pointer dereferenciation and decay from type int (*)[100][280]
to int (*)[280]
is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.
is one of these solutions eating more memory than the other?
As a corollary to my first answer, no.
what is the more frequently used by developers?
Definitely the variant without the extra (*pointer)
dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.
what is the best way, the 1st or the 2nd?
That depends on what you optimize for:
Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.
If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *
. Having no array dimension there will feel weird to most programmers.
Try this...
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
2019 Update
I ran the same code as @rjloura on my OSX High Sierra 10.13.6 node version 10.13.0 and these are the results
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Testing Array:
using[]: 117.613ms
using new: 117.168ms
Testing Object:
using{}: 117.205ms
using new: 118.644ms
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
Using with FILEPATH
option might work:
set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)
I have opened a (trivial) bug for this at m2e. Vote for it if you want the warning message to be gone for good...
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
For what its worth, I couldn't get it working on IE7/8/9 and the multiple declaration option didn't make any difference.
The fix for me was as a result of the instructions on the Technical Considerations Page where it highlights...
For best display in IE, make the stylesheet 'link' tag the first element in the HTML 'head' section.
Works across IE7/8/9 for me now.
It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg
. FigureCanvasQTAgg
and NavigationToolbar2QT
are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure
, Navigation
and a single button that draws some random data. I've added comments to explain things.
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
Edit:
Updated to reflect comments and API changes.
NavigationToolbar2QTAgg
changed with NavigationToolbar2QT
Figure
instead of pyplot
ax.hold(False)
with ax.clear()
Resemblence with c# string static method isNullOrWhiteSpace.
def isNullOrWhiteSpace(str):
"""Indicates whether the specified string is null or empty string.
Returns: True if the str parameter is null, an empty string ("") or contains
whitespace. Returns false otherwise."""
if (str is None) or (str == "") or (str.isspace()):
return True
return False
isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("") -> True
isNullOrWhiteSpace(" ") -> True
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
If you are using an implementation of InputStream
, you can check the result of InputStream#markSupported()
that tell you whether or not you can use the method mark()
/ reset()
.
If you can mark the stream when you read, then call reset()
to go back to begin.
If you can't you'll have to open a stream again.
Another solution would be to convert InputStream to byte array, then iterate over the array as many time as you need. You can find several solutions in this post Convert InputStream to byte array in Java using 3rd party libs or not. Caution, if the read content is too big you might experience some memory troubles.
Finally, if your need is to read image, then use :
BufferedImage image = ImageIO.read(new URL("http://www.example.com/images/toto.jpg"));
Using ImageIO#read(java.net.URL)
also allows you to use cache.
One more implementation (in Java). May not be most efficient solution but # of iterations is same as that of Exponential solution.
public static long pow(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
long half = pow(base, exp/2);
return half * half;
}else{
long half = pow(base, (exp -1)/2);
return base * half * half;
}
}
I would use the Dictionary<TKey, TValue>
(so long as each key is unique).
EDIT: Sorry, realised you wanted to add it to a specific position. My bad. You could use a SortedDictionary but this still won't let you insert.
It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
If you have (or create) a single string, you can use np.fromstring:
import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )
Note, x = ','.join(x)
transforms the x array to string '1.1, 2.2, 3.2'
. If you read a line from a txt file, each line will be already a string.
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.
using System;
using System.IO;
class Program
{
static void Main()
{
//
// Write file containing the date with BIN extension
//
string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
DateTime.Now);
File.WriteAllText(n, "abc");
}
}
Output :
C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin
"text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"
text- The first part of the output required Files will all start with text-
{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here
yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem
MM- Prints the month in two digits
dd_ Prints the day in two digits followed by an underscore
hh- Prints the hour in two digits
mm- Prints the minute, also in two digits
ss- As expected, it prints the seconds
tt Prints AM or PM depending on the time of day
$myArray = array(
2 => '3th element',
4 => 'first element',
1 => 'second element',
3 => '4th element'
);
echo min(array_keys($myArray)); // return 1
If you downloaded package that has "setup.py" in root folder, you can install it by running
python setup.py install
If you are developing a project and are wondering what this file is useful for, check Python documentation on writing the Setup Script
Though there have been considerable advancements in Java's GC technology, you still need to be mindful of your references. Numerous cases of seemingly trivial reference patterns that are actually rats nests under the hood come to mind.
From your post it doesn't sound like you're trying to implement a reset method for the purpose of object reuse (true?). Are your objects holding any other type of resources that need to be cleaned up (i.e., streams that must be closed, any pooled or borrowed objects that must be returned)? If the only thing you're worried about is memory dealloc then I would reconsider my object structure and attempt to verify that my objects are self contained structures that will be cleaned up at GC time.
Closing and re-opening VS2015 resolves the issue.
It seems that in some cases, simply reloading the affected project will work.
node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js
C# 4.0 also supports optional parameters, which could be useful in some other situations. See this article.
typeperf "\processor(_total)\% processor time"
does work on Win7, you just need to extract the percent value yourself from the last quoted string.
I had the same problem what i found was that the certificate .crt file i provided missing an intermediate certificate. So I asked all .crt files from my server admin, then concatinated them in reverse order.
Ex. 1. Root.crt 2. Inter.crt 3. myCrt.crt
in windows i executed copy Inter.crt + Root.crt newCertificate.crt
(Here i ignored myCrt.crt)
Then i provided newCertificate.crt file into code via inputstream. Work done.
As the given tag to this question is CSS, I will provide the way I accomplished it.
Create a class in the .css file.
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}
Nav-bar will be like:
NOTE: If you are already setting the style for all Nav-Bar elements using a class, you can cascade the special-case class we created with a white-space after the generic class in the html-tag.
Example: Here, I was already importing my style from a class called 'navList' I created for all list-items . But the special-case styling-attributes are part of class 'activePage'
.CSS file:
a.navList{text-decoration: none; color: gray;}
a.activePage{ color: green; border-bottom: solid; border-width: 3px;}
.HTML file:
<div id="sub-header">
<ul>
<li> <a href="index.php" class= "navList activePage" >Home</a> </li>
<li> <a href="contact.php" class= "navList">Contact Us</a> </li>
<li> <a href="about.php" class= "navList">About Us</a> </li>
</ul>
</div>
Look how I've cascaded one class-name behind other.
In the Terminal app, Preference >> Profiles tab.
Select the Shell tab on the right.
You can choose Never Ask before closing to suppress the warning.
try
a.slice(0,position) + b + a.slice(position)
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.slice(0,position) + b + a.slice(position);_x000D_
_x000D_
console.log(r);
_x000D_
or regexp solution
"I want apple".replace(/^(.{6})/,"$1 an")
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
_x000D_
A stable version of this function looks like this:
// not defined for empty array
function max_index(elements) {
var i = 1;
var mi = 0;
while (i < elements.length) {
if (!(elements[i] < elements[mi]))
mi = i;
i += 1;
}
return mi;
}
When you execute a method (i.e. function assigned to an object), inside it you can use this
variable to refer to this object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
If you assign a method from one object to another, its this
variable refers to the new object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
someProperty: false,_x000D_
someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
The same thing happens when you assign requestAnimationFrame
method of window
to another object. Native functions, such as this, has build-in protection from executing it in other context.
There is a Function.prototype.call()
function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({})
gives TypeError: Illegal invocation
. However, alert.call(window)
works fine, because now alert
is executed in its original scope.
If you use .call()
with your object like that:
support.animationFrame.call(window, function() {});
it works fine, because requestAnimationFrame
is executed in scope of window
instead of your object.
However, using .call()
every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind()
. It has similar effect to .call()
, but instead of calling the function, it creates a new function which will always be called in specified context. For example:
window.someProperty = true;_x000D_
var obj = {_x000D_
someProperty: false,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
The only downside of Function.prototype.bind()
is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.
As you probably already figured out, you can use .bind()
to always execute requestAnimationFrame
in context of window
. Your code could look like this:
var support = {
animationFrame: (window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame).bind(window)
};
Then you can simply use support.animationFrame(function() {});
.
Why don't you just do this
<a href="yoururl.html"><div>...</div></a>
That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.
This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.
If you still want to use ad-hoc transactions, you can always execute
BEGIN TRANSACTION
within SSMS, and than the system waits for you to commit the data.
If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in
Tools -> Options -> Query Execution -> SQL Server -> ANSI
Before using reset think about using revert so you can always go back.
https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
On request
Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
git reset vs git revert sonic0002 2019-02-02 08:26:39
When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that. In this post, we will introduce two major ones used frequently by developers.
What are their differences and corresponding use cases? We will discuss them in detail below. git reset Assuming we have below few commits.
Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want. It's easy to use git reset command.
git reset --hard a0fvf8
After executing above command, the HEAD will point to commit B.
But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.
git push -f
The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.
git revert The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit. For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C.
git revert 5lk4er
git revert 76sdeb
Now it creates two new commit D' and C',
In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.
git revert OLDER_COMMIT^..NEWER_COMMIT
This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option. Now let's take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit.
It's not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again.
From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It's recommended to use git revert instead of git reset in enterprise environment. Reference: https://kknews.cc/news/4najez2.html
I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time
"prob" is not a graphical parameter
I read through ?hist
and found about freq: a logical vector set TRUE by default.
the code that worked for me is
hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)
You don't need the jsp:useBean
to set the model if you already have a controller which prepared the model.
Just access it plain by EL:
<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>
or by JSTL <c:out>
tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:
<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>
Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.
session.setAttribute("questions", questions);
and alter EL accordingly to use ${questions}
.
Also note that you don't have any JSTL tag in your code. It's all plain JSP.
?month
states:
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE
). You have to convert your vector to some datetime class, for instance to POSIXlt
:
library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4
There's also a convenience function dmy
, that can do the same (tip proposed by @Henrik):
month(dmy(some_date))
[1] 2 4
Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:
month(some_date)
[1] 2 4
For a list of formats, see ?strptime
. You'll find that "standard unambiguous format" stands for
The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.
If you are using an http proxy server, revise the following proxy settings in "gradle.properties" file in your project's root folder. If not using proxy server, just delete those entries.
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=UserName
systemProp.http.proxyPassword=Passw0rd
systemProp.https.proxyPassword=Passw0rd
systemProp.https.proxyHost=proxy.abc.com
systemProp.http.proxyHost=proxy.abc.com
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=UserName
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
After hours of work around most of the solutions here, the problem was solved for me just by installing 32-bit JDK.
you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further
use panTo(x,y).This will help u
The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg
which apparently contained the cached keys and profiles.
After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.
I didn't have success with the other approaches.
This question is a bit old - as are the answers (and the tutorial as well)
The current api for setting a popupMenu in Swing is
myComponent.setComponentPopupMenu(myPopupMenu);
This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:
myChild.setInheritsPopupMenu(true);
Since your coordinates belong together as pairs, why not write a struct for them?
struct CoordinatePair
{
int x;
int y;
};
Then you can write an overloaded extraction operator for istreams:
std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
is >> coordinates.x >> coordinates.y;
return is;
}
And then you can read a file of coordinates straight into a vector like this:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
char filename[] = "coordinates.txt";
std::vector<CoordinatePair> v;
std::ifstream ifs(filename);
if (ifs) {
std::copy(std::istream_iterator<CoordinatePair>(ifs),
std::istream_iterator<CoordinatePair>(),
std::back_inserter(v));
}
else {
std::cerr << "Couldn't open " << filename << " for reading\n";
}
// Now you can work with the contents of v
}
try this:
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);
or
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);
The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2)
, it should work
SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table
OR
SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table
The $_GET
variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz
you can get $_GET['foo']
and $_GET['baz']
. So to set these variables, you only have to make a link to that URL.
import java.util.Scanner;
public class Shift {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int array1[] = new int [5];
int i, temp;
for (i=0; i<5; i++) {
System.out.printf("Enter array[%d]: \n", i);
array[i] = input.nextInt(); //Taking input in the array
}
System.out.println("\nEntered datas are: \n");
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
}
temp = array[4]; //We declared the variable "temp" and put the last number of the array there...
System.out.println("\nAfter Shifting: \n");
for(i=3; i>=0; i--) {
array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
}
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array1[i]);
}
input.close();
}
}
mvn -Dschemaname=public liquibase:update
You can also do something like this -
@RequestParam(value= "i", defaultValue = "20") Optional<Integer> i
After upgrading to OSX Lion, I started getting this error on certain (Debian/Ubuntu) servers. The fix is simply to install the “ncurses-term” package which provides the file /usr/share/terminfo/x/xterm-256color.
This worked for me on a Ubuntu server, via Erik Osterman.
Increasing number of max-connections will not solve the problem.
We were experiencing the same situation on our servers. This is what happens
User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.
You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour
SET interactive_timeout=3600
It means that one of the dependent dlls is compiled with a different run-time library.
Project -> Properties -> C/C++ -> Code Generation -> Runtime Library
Go over all the libraries and see that they are compiled in the same way.
More about this error in this link:
warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
There is also a datetime.toordinal()
method that was not mentioned yet:
import datetime
print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal()) # 39
https://docs.python.org/3/library/datetime.html#datetime.date.toordinal
date.
toordinal()Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any
date
object d,date.fromordinal(d.toordinal()) == d
.
Seems well suited for calculating days difference, though not as readable as timedelta.days
.
You need to drop the table and then recreate it and then load it again
There is a way to redirect JVM thread dump output on break signal to separate file with LogVMOutput diagnostic option:
-XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput -XX:LogFile=jvm.log
Are you looking for the PropertyOverrideConfigurer documented here
The PropertyOverrideConfigurer, another bean factory post-processor, is similar to the PropertyPlaceholderConfigurer, but in contrast to the latter, the original definitions can have default values or no values at all for bean properties. If an overriding Properties file does not have an entry for a certain bean property, the default context definition is used.
Pragma
is the HTTP/1.0 implementation and cache-control
is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
To create a label for text:
JLabel label1 = new JLabel("Test");
To change the text in the label:
label1.setText("Label Text");
And finally to clear the label:
label1.setText("");
And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...
This is my solution....
<TextBlock TextWrapping="Wrap" Style="{DynamicResource InstructionStyle}">
<Run Text="This wizard will take you through the purge process in the correct order." FontWeight="Bold"></Run>
<LineBreak></LineBreak>
<Run Text="To Begin, select" FontStyle="Italic"></Run>
<Run x:Name="InstructionSection" Text="'REPLACED AT RUNTIME'" FontWeight="Bold"></Run>
<Run Text="from the menu." FontStyle="Italic"></Run>
</TextBlock>
I am learning... so if anyone has thaughts on the above solution please share! :)
you can reduce the possibility but not eliminate it...
If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff
:
$ pip install webdiff
$ git webdiff
This offers a number of advantages over traditional GUI difftools like tkdiff
in that it can give you syntax highlighting and show image diffs.
Read more about it here.
Perhaps I'm oversimplifying the problem, but this is what I use.
$.fn.extend({
toggleText: function(a, b) {
$.trim(this.html()) == a ? this.html(b) : this.html(a);
}
});
To Select an Option Via Text;
(new SelectElement(driver.FindElement(By.XPath(""))).SelectByText("");
To Select an Option via Value:
(new SelectElement(driver.FindElement(By.XPath(""))).SelectByValue("");
Although I am not sure if this is the result you expect, you can save your DataFrame in png by plotting the DataFrame with Seaborn Heatmap with annotations on, like this:
http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html#seaborn.heatmap
It works right away with a Pandas Dataframe. You can look at this example: Efficiently ploting a table in csv format using Python
You might want to change the colormap so it displays a white background only.
Hope this helps.
Press the Shift key when scrolling the mouse up/down works for me when loggin in Ubuntu using Terminal ssh
in Yosemite.
$.ajax({
url:href,
type:'get',
success: function(data){
console.log($(data));
}
});
This console log gets an array like object: [meta, title, ,], very strange
You can use JavaScript:
var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))
For those using Laravel, this https://github.com/sitepoint-editors/google-laravel-2FA is a nice way to solve this problem.
While it may work on some platforms, be aware that platform.architecture
is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize
on Python 2.6, 2.7, Python 3.x.
$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).
http://connect.microsoft.com/PowerShell/feedback/details/376207/
They suggest using --%
as a way to force PowerShell to stop trying to interpret the text to the right.
For example:
MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
I think this answers your question, because it is like a "for each" loop.
The script below is valid in python (version 3.8):
a=[1,7,77,7777,77777,777777,7777777,765,456,345,2342,4]
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
The provider is bundled with PowerShell>=6.0.
If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.
Snippet code when you receive file path.
Uri fileUri = data.getData();
FilePathHelper filePathHelper = new FilePathHelper();
String path = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if (filePathHelper.getPathnew(fileUri, this) != null) {
path = filePathHelper.getPathnew(fileUri, this).toLowerCase();
} else {
path = filePathHelper.getFilePathFromURI(fileUri, this).toLowerCase();
}
} else {
path = filePathHelper.getPath(fileUri, this).toLowerCase();
}
Bellow is a class which can be accessed by creating new object. you will also need to add to a dependency in gradel implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'
public class FilePathHelper {
public FilePathHelper(){
}
public String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url.replace(" ", ""));
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
public String getFilePathFromURI(Uri contentUri, Context context) {
//copy file and send new file path
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(context.getExternalCacheDir() + File.separator + fileName);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getPath(Uri uri, Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
filePath = generateFromKitkat(uri, context);
}
if (filePath != null) {
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DATA}, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
@TargetApi(19)
private String generateFromKitkat(Uri uri, Context context) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Video.Media.DATA};
String sel = MediaStore.Video.Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
}
public String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String getPathnew(Uri uri, Context context) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Something with exception - " + e.toString());
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
Just a basic example:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);
As you can see, this is what you have to do:
RelativeLayout.LayoutParams
object.addRule(int)
or addRule(int, int)
to set the rules. The first method is used to add rules that don't require values.Adding on to the main response that recommends the usage of WpfAnimatedGif, you must add the following lines in the end if you are swapping an image with a Gif to ensure the animation actually executes:
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);
So your code will look like:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);
If you don't want to mess with ready libraries you can just make a class like this.
public class JsonConverter {
//Your class here, or you can define it in the constructor
Class requestclass = PositionKeeperRequestTest.class;
//Filename
String jsonFileName;
//constructor
public myJson(String jsonFileName){
this.jsonFileName = jsonFileName;
}
//Returns a json object from an input stream
private JSONObject getJsonObject(){
//Create input stream
InputStream inputStreamObject = getRequestclass().getResourceAsStream(jsonFileName);
try {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());
//returns the json object
return jsonObject;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//if something went wrong, return null
return null;
}
private Class getRequestclass(){
return requestclass;
}
}
Then, you can use it like this:
JSONObject jObject = new JsonConverter(FILE_NAME).getJsonObject();
Remove mb4 from charset and collation from config/database.php, then it will execute successfully.
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
This gives you the total amount from another WMI class:
$cs = get-wmiobject -class "Win32_ComputerSystem"
$Mem = [math]::Ceiling($cs.TotalPhysicalMemory / 1024 / 1024 / 1024)
Hope this helps.
Imports System.IO
Public Class Form1
Public line, counter As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter += 1
If TextBox1.Text = "" Then
MsgBox("Enter a DNS address to ping")
Else
'line = ":start" + vbNewLine
'line += "ping " + TextBox1.Text
'MsgBox(line)
Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
StreamToWrite.Write(":start" + vbNewLine + _
"Ping -t " + TextBox1.Text)
StreamToWrite.Close()
Dim p As New System.Diagnostics.Process()
p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
p.Start()
End If
End Sub
End Class
This works as well
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
You can use my code here
//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage;
//here to select the printer attached to user PC
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = pd;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pd.Print();//this will trigger the Print Event handeler PrintPage
}
}
//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
try
{
if (File.Exists(this.ImagePath))
{
//Load the image from the file
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");
//Adjust the size of the image to the page to print the full image without loosing any part of it
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
catch (Exception)
{
}
}
Postgres has a very rich system catalog exposed via SQL tables. PG's statistics collector is a subsystem that supports collection and reporting of information about server activity.
Now to figure out the blocking PIDs you can simply query pg_stat_activity
.
select pg_blocking_pids(pid) as blocked_by
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;
To, get the query corresponding to the blocking PID, you can self-join or use it as a where clause in a subquery.
SELECT query
FROM pg_stat_activity
WHERE pid IN (select unnest(pg_blocking_pids(pid)) as blocked_by from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0);
Note: Since pg_blocking_pids(pid)
returns an Integer[], so you need to unnest
it before you use it in a WHERE pid IN
clause.
Hunting for slow queries can be tedious sometimes, so have patience. Happy hunting.
If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>
Do you have multiple Radio Buttons on the page..
Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button
Javascript may be hooking up to the click-event of the anchor, rather than injecting any href.
For example, jQuery:
$('a.view').click(function() { Alert('anchor without a href was clicked');});
Of course, the javascript can do anything it wants with the click event--such as navigate to some other page (in which case the href is never set, but the anchor still behaves as though it were)
As an addendum, if you are using this technique to define strings in your target, this is how I had to define and use them:
In Build Settings -> Preprocessor Macros, and yes backslashes are critical in the definition:
APPURL_NSString=\@\"www.foobar.org\"
And in the source code:
objectManager.client.baseURL = APPURL_NSString;
I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.
This package is DEPRECATED. Please check it in Github.
root@APPLICATIOSERVER:/var/www/html# php connectiontest.php 61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#
Post declaring the proxy settings in the php script file issue has been fixed.
$proxy = '10.172.123.1:80'; curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port
Check it - You can try this code for your login form design as you ask thank you.
Explain css -
First, we define property font style and width And after that I have defined form id to set background image and the border And after that I have to define the header text in tag and after that I have added new and define by.New to set background properties and width. Thanks
Create a file index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="login_form">
<div class="new"><span>enter login details</span></div>
<!-- This is your header text-->
<form name="f1" method="post" action="login.php" id="f1">
<table>
<tr>
<td class="f1_label">User Name :</td>
<!-- This is your first Input Box Label-->
<td>
<input type="text" name="username" value="" /><!-- This is your first Input Box-->
</td>
</tr>
<tr>
<td class="f1_label">Password :</td>
<!-- This is your Second Input Box Label-->
<td>
<input type="password" name="password" value="" /><!-- This is your Second Input Box -->
</td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Log In" style="font-size:18px; " /><!-- This is your submit button -->
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Create css file style.css
body {
font-style: italic;
width: 50%;
margin: 0px auto;
}
#login_form {}
#f1 {
background-color: #FFF;
border-style: solid;
border-width: 1px;
padding: 23px 1px 20px 114px;
}
.f1_label {
white-space: nowrap;
}
span {
color: white;
}
.new {
background: black;
text-align: center;
}
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d
and Y-m-d H:i:s
satisfy these conditions.
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
…parsed … from a String … time zone is not specified … I want to set a specific time zone
LocalDateTime.parse( "2018-01-23T01:23:45.123456789" ) // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.
As the other correct answers stated, a java.util.Date has no time zone†. It represents UTC/GMT (no time zone offset). Very confusing because its toString
method applies the JVM's default time zone when generating a String representation.
For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.
Instead use the java.time package bundled with Java 8.
The java.time classes can represent a moment on the timeline in three ways:
Instant
)OffsetDateTime
with ZoneOffset
)ZonedDateTime
with ZoneId
)Instant
In java.time, the basic building block is Instant
, a moment on the time line in UTC. Use Instant
objects for much of your business logic.
Instant instant = Instant.now();
OffsetDateTime
Apply an offset-from-UTC to adjust into some locality’s wall-clock time.
Apply a ZoneOffset
to get an OffsetDateTime
.
ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );
ZonedDateTime
Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).
Apply a ZoneId
to an Instant
to get a ZonedDateTime
. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST
or IST
that are neither unique nor standardized.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDateTime
If the input string lacked any indicator of offset or zone, parse as a LocalDateTime
.
If you are certain of the intended time zone, assign a ZoneId
to produce a ZonedDateTime
. See code example above in tl;dr section at top.
Call the toString
method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime
class extends standard format by appending the name of the time zone in brackets.
String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
For other formats use the DateTimeFormatter
class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time
section above instead.
In Joda-Time, a date-time object (DateTime
) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );
Call the toString
method to generate a String in ISO 8601 format.
String output = dateTimeIndia.toString();
Joda-Time also offers rich capabilities for generating all kinds of other String formats.
If required, you can convert from Joda-Time DateTime to a java.util.Date.
Java.util.Date date = dateTimeIndia.toDate();
Search StackOverflow for "joda date" to find many more examples, some quite detailed.
†Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString
method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
I solved this exception by changing the target sdk
version from 19 onwards kitkat version AndroidManifest.xml.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
METHOD 1 ( Recommanded )
Library YouTubeExtractor
Add into your gradle file
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
And dependencies
compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
Add this small code and you done. Demo HERE
public class MainActivity extends AppCompatActivity {
private static final String YOUTUBE_ID = "ea4-5mrpGfE";
private final YouTubeExtractor mExtractor = YouTubeExtractor.create();
private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
@Override
public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
bindVideoResult(response.body());
}
@Override
public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
onError(t);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// For android youtube extractor library com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);
}
private void onError(Throwable t) {
t.printStackTrace();
Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
}
private void bindVideoResult(YouTubeExtractionResult result) {
// Here you can get download url link
Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());
Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
}
}
You can get download link in bindVideoResult() method.
METHOD 2
Using this library android-youtubeExtractor
Add into gradle file
repositories {
maven { url "https://jitpack.io" }
}
compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
Here is the code for getting download url.
String youtubeLink = "http://youtube.com/watch?v=xxxx";
YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
@Override
public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
if (ytFiles != null) {
int itag = 22;
// Here you can get download url
String downloadUrl = ytFiles.get(itag).getUrl();
}
}
};
ytEx.execute(youtubeLink);
If you're going to build complex user interfaces in the browser then you will probably find yourself eventually inventing most of the pieces that make up frameworks like Backbone.js and Sammy.js. So the question is, are you building something complicated enough in the browser to merit using it (so you don't end up inventing the same thing yourself).
If what you plan to build is something where the UI regularly changes how it displays but does not go to the server to get entire new pages then you probably need something like Backbone.js or Sammy.js. The cardinal example of something like that is Google's GMail. If you've ever used it you'll notice that it downloads one big chunk of HTML, CSS, and JavaScript when you first log in and then after that everything happens in the background. It can move between reading an email and processing the inbox and searching and back through all of them again without ever asking for a whole new page to be rendered.
It's that kind of app that these frameworks excel at making easier to develop. Without them you'll either end up glomming together a diverse set of individual libraries to get parts of the functionality (for example, jQuery BBQ for history management, Events.js for events, etc.) or you'll end up building everything yourself and having to maintain and test everything yourself as well. Contrast that with something like Backbone.js that has thousands of people watching it on Github, hundreds of forks where people may be working on it, and hundreds of questions already asked and answered here on Stack Overflow.
But none of it is of any importance if what you plan to build is not complicated enough to be worth the learning curve associated with a framework. If you're still building PHP, Java, or something else sites where the back end server is still doing all the heavy lifting of building the web pages upon request by the user and JavaScript/jQuery is just icing upon that process, you aren't going to need or are not yet ready for Backbone.js.
Use the String.split()
var array = string.split(',');
For future visitors - use this for range: ($A$1:$A$10)
Example
=COUNTIF($G$6:$G$9;J6)>0
I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp
class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.
Depending on your situation an exact requirements, there are two natural replacements for Timestamp
:
Instant
is a point on the time-line. For most purposes I would consider it safest to use this. An Instant
is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.LocalDateTime
is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant
or a LocalDateTime
into your database column of datatype timestamp
. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time
or JSR-310.
It’s easiest to convert your string to LocalDateTime
, so let’s take that first:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String text = "2011-10-02 18:48:05.123";
LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
System.out.println(dateTime);
This prints
2011-10-02T18:48:05.123
If your string was in yyyy-MM-dd format, instead do:
String text = "2009-10-20";
LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
System.out.println(dateTime);
This prints
2009-10-20T00:00
Or still better, take the output from LocalDate.parse()
and store it into a database column of datatype date
.
In both cases the procedure for converting from a LocalDateTime
to an Instant
is:
Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(ts);
I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:
Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();
This should work in almost all browsers:
var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();
Additionally, there's the new Fetch
API:
fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )
In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)
You can do this a couple of ways.
Via the "Solution Explorer"
Via the "Package Manager Console"
Install-Package Newtonsoft.Json
For more info on how to use the "Package Manager Console" check out the nuget docs.
I've just had similar problem but without any branching or merging to cause the problem. My workaround was to:
All seems fine now.