I found simple solution to get current date without any parsing error.
Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
The jQuery Audit plugin plugin should let you do this through the normal Chrome Dev Tools. It's not perfect, but it should let you see the actual handler bound to the element/event and not just the generic jQuery handler.
As stated already, running your code through the W3C Validator is great but if your page is complex, you still may not know exactly where to find the open div.
I like using tabs to indent my code. It keeps it visually organized so that these issues are easier to find, children, siblings, parents, etc... they'll appear more obvious.
EDIT: Also, I'll use a few HTML comments to mark closing tags in the complex areas. I keep these to a minimum for neatness.
<body>
<div>
Main Content
<div>
Div #1 content
<div>
Child of div #1
<div>
Child of child of div #1
</div><!--// close of child of child of div #1 //-->
</div><!--// close of child of div #1 //-->
</div><!--// close of div #1 //-->
<div>
Div #2 content
</div>
<div>
Div #3 content
</div>
</div><!--// close of Main Content div //-->
</body>
I guess you are asking why is 1388516401 equal to 2014-01-01...?
There is an historical reason for that. There is a 32-bit integer variable, called time_t
, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t
will be equal to 1388516401.
This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t
will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D
getApplicationContext()
this is used for application level and refer to all activities.
getContext() and getBaseContext()
is most probably same .these are reffered only current activity which is live.
this
is refer current class object always.
Set all the column's (which can be sortable by users) SortMode property to Automatic
dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
.OrderBy(s => s.Apellidos)
.ToList();
foreach(DataGridViewColumn column in dataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
Edit: As your datagridview is bound with a linq query, it will not be sorted. So please go through this [404 dead link, see next section]
which explains how to create a sortable binding list and to then feed it as datasource to datagridview.
Link from above is 404-dead. I recovered the code from the Internet Wayback Machine archive of the page.
public Form1()
{
InitializeComponent();
SortableBindingList<person> persons = new SortableBindingList<person>();
persons.Add(new Person(1, "timvw", new DateTime(1980, 04, 30)));
persons.Add(new Person(2, "John Doe", DateTime.Now));
this.dataGridView1.AutoGenerateColumns = false;
this.ColumnId.DataPropertyName = "Id";
this.ColumnName.DataPropertyName = "Name";
this.ColumnBirthday.DataPropertyName = "Birthday";
this.dataGridView1.DataSource = persons;
}
var times = [1,2,3];
for(var i = 0; i < times.length; i++) {
for(var j = 0; j < times[i];j++) {
// do something
}
}
Using jQuery .each()
$([1,2,3]).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
OR
var x = [1,2,3];
$(x).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
You can do like below with pure JS:
var times = [1,2,3];
times.forEach(function(i) {
// do something
});
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
CSS has a text-align: center
property, and since this is purely a visual thing, not semantic, it should be relegated to CSS, not HTML.
I had pretty much the same question. After some research, I think that if you want to play the default system "notification sound", you pretty much have to display a notification and tell it to use the default sound. And there's something to be said for the argument in some of the other answers that if you're playing a notification sound, you should be presenting some notification message as well.
However, a little tweaking of the notification API and you can get close to what you want. You can display a blank notification and then remove it automatically after a few seconds. I think this will work for me; maybe it will work for you.
I've created a set of convenience methods in com.globalmentor.android.app.Notifications.java
which allow you create a notification sound like this:
Notifications.notify(this);
The LED will also flash and, if you have vibrate permission, a vibration will occur. Yes, a notification icon will appear in the notification bar but will disappear after a few seconds.
At this point you may realize that, since the notification will go away anyway, you might as well have a scrolling ticker message in the notification bar; you can do that like this:
Notifications.notify(this, 5000, "This text will go away after five seconds.");
There are many other convenience methods in this class. You can download the whole library from its Subversion repository and build it with Maven. It depends on the globalmentor-core library, which can also be built and installed with Maven.
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
def get_dict_from_pd(df, key_col, row_col):
result = dict()
for i in set(df[key_col].values):
is_i = df[key_col] == i
result[i] = list(df[is_i][row_col].values)
return result
this is my sloution, a basic loop
I use Octave, but Matlab has the same syntax.
Create 3d matrix:
octave:3> m = ones(2,3,2)
m =
ans(:,:,1) =
1 1 1
1 1 1
ans(:,:,2) =
1 1 1
1 1 1
Now, say I have a 2D matrix that I want to expand in a new dimension:
octave:4> Two_D = ones(2,3)
Two_D =
1 1 1
1 1 1
I can expand it by creating a 3D matrix, setting the first 2D in it to my old (here I have size two of the third dimension):
octave:11> Three_D = zeros(2,3,2)
Three_D =
ans(:,:,1) =
0 0 0
0 0 0
ans(:,:,2) =
0 0 0
0 0 0
octave:12> Three_D(:,:,1) = Two_D
Three_D =
ans(:,:,1) =
1 1 1
1 1 1
ans(:,:,2) =
0 0 0
0 0 0
Probably not exactly what you're looking for since you say it's "dynamic data" but given your example string, this also works:
? "abcdxxx".TrimEnd('x');
"abc"
You can get user input using BufferedReader
.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String
value in accStr
so you have to parse it to an int
using Integer.parseInt
.
int accInt = Integer.parseInt(accStr);
No there actually is no way to prevent a user from doing a particular task. But you can always take measures! The image sharing websites have a huge team of developers working day and night to create such an algorithm where you prevent user from saving the image files.
Try this:
$('img').mousedown(function (e) {
if(e.button == 2) { // right click
return false; // do nothing!
}
}
So the user won't be able to click on the Save Image As... option from the menu and in turn he won't get a chance to save the image.
Other way is to use background-image
. This way, the user won't be able to right click and Save the Image As... But he can still see the resources in the Inspector.
Even I am new to this one, few days ago I was surfing Flickr when I tried to right click, it did not let me do a thing. Which in turn was the first method that I provided you with. Then I tried to go and see the inspector, there I found nothing. Why? Since they were using background-image
and at the same time they were using data:imagesource
as its location.
Which was amazing for me too. You can precvent user from saving image files this way easily.
It is known as Data URI Scheme: http://en.wikipedia.org/wiki/Data_URI_scheme
Please remember brother, when you're letting a user surf your website you're giving him READ permissions on the server side so he can read all the files without any problem. The same is the issue with image files. He can read the image files, and then he can easily save them. He downloads the images on the first place when he is surfing your website. So there is not an issue for him to save them on his disk.
check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
Here's Laravel 5.7, Laravel 5.8, Laravel 6.0, Laravel 7.0, and Laravel 8.0 (note a minor bc change in 6.0 to the email verification route).
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');
// Confirm Password (added in v6.2)
Route::get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm');
Route::post('password/confirm', 'Auth\ConfirmPasswordController@confirm');
// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); // v6.x
/* Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); // v5.x */
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
You can verify these routes here:
Well, I didn't like any of those answers, my solution of the same problem was to add this:<div> </div>
. So in your scheme it would look like this (more or less), no style changes were necessary in my case:
-row-fluid-------------------------------------
+-span6----------+ +----span6----------+
| | | +---div---+ |
| content | | | & nbsp; | |
| that | | +---------+ |
| is tall | | +-----div--------+|
| | | |short content ||
| | | +----------------+|
+----------------+ +-------------------+
-----------------------------------------------
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
As I started to update my old project to Swift 3.2, I just needed to change the method from
respondsToSelector(selector)
to:
responds(to: selector)
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
Basically it checks if the value before the || evaluates to true, if yes, it takes this value, if not, it takes the value after the ||.
Values for which it will take the value after the || (as far as i remember):
You can use another console method:
let name = prompt("what is your name?");
console.log(`story ${name} story`);
Additionally for what was said, if you want integer powers of two, then 1 << x
(or 1L << x
) is a faster way to calculate 2x than Math.pow(2,x)
or a multiplication loop, and is guaranteed to give you an int
(or long
) result.
It only uses the lowest 5 (or 6) bits of x
(i.e. x & 31
(or x & 63
)), though, shifting between 0 and 31 (or 63) bits.
For the people looking for an iOS 10 solution, user-scaleable=no
is disabled in Safari for iOS 10. The reason is that Apple is trying to improve accessibility by allowing people to zoom on web pages.
From release notes:
To improve accessibility on websites in Safari, users can now pinch-to-zoom even when a website sets user-scalable=no in the viewport.
So as far as I understand, we are sh** out of luck.
The reason I was seeing this issue was incorrect http
link on the page instead of https
that should stop the job. All you need to do is to edit onclick
attribute in html page, by following
onclick
attribute to edit its values
to http
to have https
The syntax is almost the same as printf
. With printf
you give the string format and its contents ie:
printf("my %s has %d chars\n", "string format", 30);
With fprintf
it is the same, except now you are also specifying the place to print to:
File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);
Or in your case:
fprintf( stderr, "my %s has %d chars\n", "string format", 30);
Here is a dplyr
way to go about it:
#df[ -c(1,3:6, 12) ] # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6) # with dplyr::select()
I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using -
to remove elements.
I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
Now when you want to add the items to your ComboBox you can do it like this:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.
Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.
Here's the new and improved GenericListItem
class:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
And here is how you would now add Generic items to your ComboBox. In this case an Integer:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
And now the retrieval of the item:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
Keep in mind that the type Integer
can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.
Quote (read [here][1])-
When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.
So, something like this should work-
report := CAST(report_clob AS VARCHAR2(100));
Or better yet use it as CAST(report_clob AS VARCHAR2(100))
where ever you are trying to use the BLOB
as VARCHAR
[1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm
The short answer is: never!
simplifily, use:
pip install -r requirement.txt
it can install all listed in requirement file.
Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.
An example:
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
There are some very good answers here but none of them covered my needs. I built on Glavic's answer to add some extra features that I needed;
You can see a running version of the code here.
function secondsToHumanReadable(int $seconds, int $requiredParts = null)
{
$from = new \DateTime('@0');
$to = new \DateTime("@$seconds");
$interval = $from->diff($to);
$str = '';
$parts = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$includedParts = 0;
foreach ($parts as $key => $text) {
if ($requiredParts && $includedParts >= $requiredParts) {
break;
}
$currentPart = $interval->{$key};
if (empty($currentPart)) {
continue;
}
if (!empty($str)) {
$str .= ', ';
}
$str .= sprintf('%d %s', $currentPart, $text);
if ($currentPart > 1) {
// handle plural
$str .= 's';
}
$includedParts++;
}
return $str;
}
I needed to find the nth last position of a backslash in a folder path. Here is my solution.
/*
http://stackoverflow.com/questions/1024978/find-index-of-last-occurrence-of-a-sub-string-using-t-sql/30904809#30904809
DROP FUNCTION dbo.GetLastIndexOf
*/
CREATE FUNCTION dbo.GetLastIndexOf
(
@expressionToFind VARCHAR(MAX)
,@expressionToSearch VARCHAR(8000)
,@Occurrence INT = 1 -- Find the nth last
)
RETURNS INT
AS
BEGIN
SELECT @expressionToSearch = REVERSE(@expressionToSearch)
DECLARE @LastIndexOf INT = 0
,@IndexOfPartial INT = -1
,@OriginalLength INT = LEN(@expressionToSearch)
,@Iteration INT = 0
WHILE (1 = 1) -- Poor man's do-while
BEGIN
SELECT @IndexOfPartial = CHARINDEX(@expressionToFind, @expressionToSearch)
IF (@IndexOfPartial = 0)
BEGIN
IF (@Iteration = 0) -- Need to compensate for dropping out early
BEGIN
SELECT @LastIndexOf = @OriginalLength + 1
END
BREAK;
END
IF (@Occurrence > 0)
BEGIN
SELECT @expressionToSearch = SUBSTRING(@expressionToSearch, @IndexOfPartial + 1, LEN(@expressionToSearch) - @IndexOfPartial - 1)
END
SELECT @LastIndexOf = @LastIndexOf + @IndexOfPartial
,@Occurrence = @Occurrence - 1
,@Iteration = @Iteration + 1
IF (@Occurrence = 0) BREAK;
END
SELECT @LastIndexOf = @OriginalLength - @LastIndexOf + 1 -- Invert due to reverse
RETURN @LastIndexOf
END
GO
GRANT EXECUTE ON GetLastIndexOf TO public
GO
Here are my test cases which pass
SELECT dbo.GetLastIndexOf('f','123456789\123456789\', 1) as indexOf -- expect 0 (no instances)
SELECT dbo.GetLastIndexOf('\','123456789\123456789\', 1) as indexOf -- expect 20
SELECT dbo.GetLastIndexOf('\','123456789\123456789\', 2) as indexOf -- expect 10
SELECT dbo.GetLastIndexOf('\','1234\6789\123456789\', 3) as indexOf -- expect 5
This article offers a fairly comprehensive explanation:
"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file
The specific difference appears to be that System.Timers.Timer
is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject
property, whereas System.Threading.Timer
is ironically not thread-safe out-of-the-box.
I don't believe that there is a difference between the two as it pertains to how small your intervals can be.
You can also use BreakIterator.getWordInstance
.
Most easy way..
//div[@class="Test"]
Assuming you want to find <div class="Test">
as described.
Try this:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.hasClass("icon-circle-arrow-down"){
icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
}else{
icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
}
})
or even better, as Kevin said:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})
You could use a string stream and read the elements into the vector.
Here are many different examples...
A copy of one of the examples:
std::vector<std::string> split(const std::string& s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while((pos = s.find(seperator, pos)) != std::string::npos)
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
I would suggest hinterland extension.
In other answers I couldn't find the method for how to install it from pip, so this is how you install it.
First, install jupyter contrib nbextensions by running
pip install jupyter_contrib_nbextensions
Next install js and css file for jupyter by running
jupyter contrib nbextension install --user
and at the end run,
jupyter nbextension enable hinterland/hinterland
The output of last command will be
Enabling notebook extension hinterland/hinterland...
- Validating: OK
Use:
git reset HEAD^
That does a "mixed" reset by default, which will do what you asked; put foo.java in unstaged, removing the most recent commit.
This can also be done with the Image
class of the PIL library:
from PIL import Image
import numpy as np
im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())
Note: The .getdata()
might not be needed - np.array(im_frame)
should also work
After opening a file using vi
1) You can press Shift + g to go the end of the file
and
2) Press g twice to go to the beginning of the file
NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)
No, an alt
attribute (it would be an attribute, not a tag) is not allowed for an a
element in any HTML specification or draft. And it does not seem to be recognized by any browser either as having any significance.
It’s a bit mystery why people try to use it, then, but the probable explanation is that they are doing so in analog with alt
attribute for img
elements, expecting to see a “tooltip” on mouseover. There are two things wrong with this. First, each element has attributes of its own, defined in the specs for each element. Second, the “tooltip” rendering of alt
attributes in some ancient browsers is/was a quirk or even a bug, rather than something to be expected; the alt
attribute is supposed to be presented to the user if and only if the image itself is not presented, for whatever reason.
To create a “tooltip”, use the title
attribute instead or, much better, Google for "CSS tooltips" and use CSS-based tooltips of your preference (they can be characterized as hidden “layers” that become visible on mouseover).
Two ways come to mind:
Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that
Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.
Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;
SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;
I finally fixed this using the Google's camera app. It gets the phone's orientation by using a sensor and then sets the EXIF tag appropriately. The JPEG which comes out of the camera is not oriented automatically.
Also, the camera preview works properly only in the landscape mode. If you need your activity layout to be oriented in portrait, you will have to do it manually using the value from the orientation sensor.
If you're a minimalist like me. Say you only want to render a record with a list containing entries.
<div>
{data.map((record) => (
record.list.length > 0
? (<YourRenderComponent record={record} key={record.id} />)
: null
))}
</div>
String.split() works very good but has its own boundaries, like if you wanted to split a string as shown below based on single or double pipe (|) symbol, it doesn't work. In this situation you can use StringTokenizer.
ABC|IJK
assuming you want to have a range between x to y
range(x,y+1)
>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>
use list for 3.x support
I know this is an old question, but nowadays there is a super easy form to do that, which is CCS Grid, so let me put the divs as example:
<div id="full">
<div id="header">Contents of 1</div>
<div id="someid">Contents of 2</div>
</div>
then the CSS code:
.full{
width:/*the width you need*/;
height:/*the height you need*/;
display:grid;
grid-template-rows: minmax(100px,auto) 1fr;
}
And that's it, the second row, scilicet, the someide, will take the rest of the height because of the property 1fr, and the first div will have a min of 100px and a max of whatever it requires.
I must say CSS has advanced a lot to make easier programmers lives.
If you used [STAThread]
to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!
Private void YourFunc(..)
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(delegate()
{
// Call your method YourFunc(..);
}));
}
else
{
///
}
Just run your command line (cmd) as an administrator.
On Linux you can use clock_gettime()
:
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp
// ... do stuff ... //
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // get final time-stamp
double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
(double)(end.tv_nsec - start.tv_nsec);
// subtract time-stamps and
// multiply to get elapsed
// time in ns
Here we go, guys! It helped me
$('.slick-slider').not('.slick-initialized').slick({
infinite: false,
slidesToShow: 1,
slidesToScroll: 1,
dots: true,
arrows: false,
touchThreshold: 9
});
If you changed height of tableView's headerView, just reset headerView's frame, then, reset headerView of tableView:
self.headerView.frame = newFrame;
self.tableView.tableHeaderView = self.headerView;
Change draggable
attribute from
<span draggable="true">Label</span>
to
<span draggable="false">Label</span>
I had already enabled "Allow less secure apps" and my SMPT python program was working perfectly!
But next day it stared giving me "Bad Credentials error (SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted)". I was using the exact same credentials as before and the less secure apps option was also enabled..!
Changed my password again but that also did not help.
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
Note: Had to try multipe times to get this option enabled. Once enabled, I tried connecting after 30mins and it worked..!!!
Hope this helps.
For windows, you can use my PowerShell script to show messages for your app only: https://github.com/AlShevelev/power_shell_logcat
$.ajax({
type: "POST",
url: '/admin/systemgoalssystemgoalupdate?format=html',
data: formdata,
success: function (data) {
console.log(data);
},
dataType: "json"
});
You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)
set 0 where you don't want images
Example for Drawable on the left:
TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.
Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft
In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.
I have found that this works...as an example.
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;
For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .
In my case i do an HTML POST with JSON like so...
{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}
Several GUI tools like Squirrel, SQL Workbench/J, AnySQL, ExecuteQuery can export to Excel files.
Most of those tools are listed in the PostgreSQL wiki:
http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools
If the tables are innodb you can create it like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.
This has been a major pain and feels like it should be simpler. Here's my setup and solution.
I'm using the following HTML helper:
@Html.CheckBoxFor(model => model.ActiveFlag)
Then, in the controller, I am checking the form collection and processing accordingly:
bool activeFlag = collection["ActiveFlag"] == "false" ? false : true;
[modelObject].ActiveFlag = activeFlag;
I also faced with the same problem and "Find all references" for selected class has solved this issue.
This is super old, but I figured I'd add my 2c. DATE_FORMAT
does indeed return a string, but I was looking for the CAST
function, in the situation that I already had a datetime string in the database and needed to pattern match against it:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
Actually, you can achieve this pretty easy. Simply specify the line height as a number:
<p style="line-height:1.5">
<span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
<span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>
The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.
For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.
or you can do like
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread( SampleFunction ).Start();
}
void SampleFunction()
{
// Gets executed on a seperate thread and
// doesn't block the UI while sleeping
for ( int i = 0; i < 5; i++ )
{
this.Invoke( ( MethodInvoker )delegate()
{
textBox1.Text += "hi";
} );
Thread.Sleep( 1000 );
}
}
}
Try this ...
PropertyInfo isreadonly =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");
You can use kill -0
for checking whether a particular pid is running or not.
Assuming, you have list of pid
numbers in a file called pid
in pwd
while true;
do
if [ -s pid ] ; then
for pid in `cat pid`
do
echo "Checking the $pid"
kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
done
else
echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
break
fi
done
If you want to call them like that, you should declare them static.
url
prop is deprecated as of Next.js version 6:
https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md
To get the query parameters, use getInitialProps
:
import Link from 'next/link'
const About = ({query}) => (
<div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)
About.getInitialProps = ({query}) => {
return {query}
}
export default About;
class About extends React.Component {
static getInitialProps({query}) {
return {query}
}
render() {
console.log(this.props.query) // The query is available in the props object
return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
}
}
The query object will be like: url.com?a=1&b=2&c=3
becomes: {a:1, b:2, c:3}
df['col'] = 'str' + df['col'].astype(str)
Example:
>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0
You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini
itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.
For OSX:
I had installed this via Anaconda, and had a hell of a time getting it to work. What helped was adding the Anaconda bin AND pkgs folder to my PATH.
Since I use fishshell, I did it in my ~/.config/fish/config.fish
file like this:
set -g -x PATH $PATH /Users/cbrevik/anaconda/bin /Users/cbrevik/anaconda/pkgs
If you use fishshell like me, this answer will probably save you some trouble later using pandas as well.
Just rename the .war
into .jar
and unzip it using Winrar
(or any other archive manager).
I've created a recursive function based on regex, in case you don't want to install library and understand the logic behind what's happening:
const xmlSample = '<tag>tag content</tag><tag2>another content</tag2><tag3><insideTag>inside content</insideTag><emptyTag /></tag3>';_x000D_
console.log(parseXmlToJson(xmlSample));_x000D_
_x000D_
function parseXmlToJson(xml) {_x000D_
const json = {};_x000D_
for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {_x000D_
const key = res[1] || res[3];_x000D_
const value = res[2] && parseXmlToJson(res[2]);_x000D_
json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null;_x000D_
_x000D_
}_x000D_
return json;_x000D_
}
_x000D_
Regex explanation for each loop:
<tag />
You can check how the regex works here: https://regex101.com/r/ZJpCAL/1
Note: In case json has a key with an undefined value, it is being removed. That's why I've inserted null at the end of line 9.
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.
Have a look at the following document:
https://developers.google.com/maps/documentation/urls/guide
You can use URLs in search, directions, map and street view modes.
For example, to show the marker at specified position you can use the following URL:
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
For further details please read aforementioned documentation.
You can also file feature requests for this API in Google issue tracker.
Hope this helps!
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
Just use the classic ==
operator:
>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False
Lists are equal if elements at the same index are equal. Ordering is taken into account then.
To answer your question
In Sql Server joins syntax OUTER is optional
It is mentioned in msdn article : https://msdn.microsoft.com/en-us/library/ms177634(v=sql.130).aspx
So following list shows join equivalent syntaxes with and without OUTER
LEFT OUTER JOIN => LEFT JOIN
RIGHT OUTER JOIN => RIGHT JOIN
FULL OUTER JOIN => FULL JOIN
Other equivalent syntaxes
INNER JOIN => JOIN
CROSS JOIN => ,
Strongly Recommend Dotnet Mob Artice : Joins in Sql Server
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
On macOS Sierra, creating ~/.mailrc with smtp setup did the trick:
set smtp-use-starttls
set smtp=smtp://smtp.gmail.com:587
set smtp-auth=login
set [email protected]
set smtp-auth-password=yourpass
Then to send mail from CLI:
echo "your message" | mail -s "your subject" [email protected]
Installing maven in Amazon Linux / redhat
--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
-->sudo yum install -y apache-maven
--> mvn --version
Output looks like
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"
*If its thrown error related to java please follow the below step to update java 8 *
Installing java 8 in amazon linux/redhat
--> yum search java | grep openjdk
--> yum install java-1.8.0-openjdk-headless.x86_64
--> yum install java-1.8.0-openjdk-devel.x86_64
--> update-alternatives --config java #pick java 1.8
and press 1
--> update-alternatives --config javac #pick java 1.8
and press 2
Thank You
Top down and bottom up DP are two different ways of solving the same problems. Consider a memoized (top down) vs dynamic (bottom up) programming solution to computing fibonacci numbers.
fib_cache = {}
def memo_fib(n):
global fib_cache
if n == 0 or n == 1:
return 1
if n in fib_cache:
return fib_cache[n]
ret = memo_fib(n - 1) + memo_fib(n - 2)
fib_cache[n] = ret
return ret
def dp_fib(n):
partial_answers = [1, 1]
while len(partial_answers) <= n:
partial_answers.append(partial_answers[-1] + partial_answers[-2])
return partial_answers[n]
print memo_fib(5), dp_fib(5)
I personally find memoization much more natural. You can take a recursive function and memoize it by a mechanical process (first lookup answer in cache and return it if possible, otherwise compute it recursively and then before returning, you save the calculation in the cache for future use), whereas doing bottom up dynamic programming requires you to encode an order in which solutions are calculated, such that no "big problem" is computed before the smaller problem that it depends on.
Necromancing.
It looks you have just as good a schema to work with as me...
Here is how to do it correctly:
In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE @pkDropCommand nvarchar(1000)
--SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT @pkDropCommand
--EXECUTE(@pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
Use cl scr
on the Sql* command line tool to clear all the matter on the screen.
Functional programming is "programming with functions," where a function has some expected mathematical properties, including referential transparency. From these properties, further properties flow, in particular familiar reasoning steps enabled by substitutability that lead to mathematical proofs (i.e. justifying confidence in a result).
It follows that a functional program is merely an expression.
You can easily see the contrast between the two styles by noting the places in an imperative program where an expression is no longer referentially transparent (and therefore is not built with functions and values, and cannot itself be part of a function). The two most obvious places are: mutation (e.g. variables) other side-effects non-local control flow (e.g. exceptions)
On this framework of programs-as-expressions which are composed of functions and values, is built an entire practical paradigm of languages, concepts, "functional patterns", combinators, and various type systems and evaluation algorithms.
By the most extreme definition, almost any language—even C or Java—can be called functional, but usually people reserve the term for languages with specifically relevant abstractions (such as closures, immutable values, and syntactic aids like pattern matching). As far as use of functional programming is concerned it involves use of functins and builds code without any side effects . used to write proofs
I'd refrain from using floats for this sort of thing; I'd rather use inline-block
.
Some more points to consider:
<head>
and <body>
doctype
Here's a better way to format your document:
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
<div id="left">Left Side Menu</div>
<div id="middle">Random Content</div>
<div id="right">Right Side Menu</div>
</div>
</body>
</html>
Here's a jsFiddle for good measure.
The MyKey class must implement Serializable
if you are using @IdClass
You can use 2 methods from the String
class.
String.contains()
which checks if the string contains a specified sequence of char valuesString.indexOf()
which returns the index within the string of the first occurence of the specified character or substring or returns -1 if the character is not found (there are 4 variations of this method)Method 1:
String myString = "foobar";
if (myString.contains("x") {
// Do something.
}
Method 2:
String myString = "foobar";
if (myString.indexOf("x") >= 0 {
// Do something.
}
Links by: Zach Scrivena
I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Parameters
table
: the name of the table you want to querycolumns
: the column names that you want returned. Don't return data that you don't need.selection
: the row data that you want returned from the columns (This is the WHERE clause.)selectionArgs
: This is substituted for the ?
in the selection
String above.groupBy
and having
: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.orderBy
: sort the datalimit
: limit the number of results to return CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
Deploy Flask on a real web server, rather than with the built-in (development) server.
See the Deployment Options chapter of the Flask documentation. Servers like Nginx and Apache both can handle setting up HTTPS servers rather than HTTP servers for your site.
The standalone WSGI servers listed would typically be deployed behind Nginx and Apache in a proxy-forwarding configuration, where the front-end server handles the SSL encryption for you still.
Python has nothing built-in to support this. Do you really need to optimize it so much as I don't think that appending will add that much overhead.
However, you can do something like l = [None] * 1000
.
Alternatively, you could use a generator.
Or you can code it:
int[] colors = {0, 0xFFFF0000, 0}; // red for the example
myList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
myList.setDividerHeight(1);
Hope it helps
for item in array: array2.append (item)
Or, in this case:
array2 += array
try to change the order: right click on you project-> BuildPath->Configure...->Order and Export tab -> move jre7 UP.
At the risk of getting yet another mysterious down-vote...the fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.
Floating-point primitive types are handled by the FPU, which is 80 bits wide.
This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.
Tested in Chrome 60.0.3112.78.
Some of the above methods work, but the easiest in my opinion is:
Open dev tools (Shift+Control+i).
Select the "Elements" tab, and then the "Event Listeners" tab.
Hover over the elements/listener. A "Remove" button will show up.
Click "Remove".
E.g. see photo.
I want to attempt an answer that includes git-flow, and three 'points' or use-cases, the git central repository, the local development and the production machine. This is not well tested.
I am giving incredibly specific commands. Instead of saying <your folder>
, I will say /root/git
. The only place where I am changing the original command is replacing my specific server name with example.com
. I will explain the folders purpose is so you can adjust it accordingly. Please let me know of any confusion and I will update the answer.
The git version on the server is 1.7.1. The server is CentOS 6.3 (Final).
The git version on the development machine is 1.8.1.1. This is Mac OS X 10.8.4.
The central repository and the production machine are on the same machine.
the central repository, which svn users can related to as 'server' is configured as follows. I have a folder /root/git
where I keep all my git repositories. I want to create a git repository for a project I call 'flowers'.
cd /root/git
git clone --bare flowers flowers.git
The git command gave two messages:
Initialized empty Git repository in /root/git/flowers.git/
warning: You appear to have cloned an empty repository.
Nothing to worry about.
On the development machine is configured as follows. I have a folder /home/kinjal/Sites
where I put all my projects. I now want to get the central git repository.
cd /home/kinjal/Sites
git clone [email protected]:/root/git/flowers.git
This gets me to a point where I can start adding stuff to it. I first set up git flow
git flow init -d
By default this is on branch develop
. I add my code here, now. Then I need to commit to the central git repository.
git add .
git commit -am 'initial'
git push
At this point it pushed to the develop branch. I want to also add this to the master branch.
git flow release start v0.0.0 develop
git flow release finish v0.0.0
git push
Note that I did nothing between the release start and release finish. And when I did the release finish I was prompted to edit two files. This pushed the develop branch to master.
On the production site, which is on the same machine as my central git repository, I want put the repository in /var/www/vhosts/example.net
. I already have /var/www/vhosts
.
cd /var/www/vhosts
git clone file:///root/git/flowers.git example.net
If the production machine would also be on a different machine, the git clone
command would look like the one used on the development machine.
In case you don't want to use API 21 as the target API, and thus you don' t want to use the Material Theme, you have to use an older revision belonging to API 19 >
compile "com.android.support:appcompat-v7:19.0.+"
This also helps solving your problem, it only depends on what you want to achieve.
In case the XML store in the CLOB field in the database table. E.g for this XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Awmds>
<General_segment>
<General_segment_id>
<Customs_office_code>000</Customs_office_code>
</General_segment_id>
</General_segment>
</Awmds>
This is the Extract Query:
SELECT EXTRACTVALUE (
xmltype (T.CLOB_COLUMN_NAME),
'/Awmds/General_segment/General_segment_id/Customs_office_code')
AS Customs_office_code
FROM TABLE_NAME t;
According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute
checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess
and other APIs don't. Hope it helps.
See also: same article as .chm.
Try this
function checkForm($fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$field['value'] = "Some error";
}
}
return $field;
}
There are declared arrays and arrays that are not declared, but otherwise created, particularly using new
:
int *p = new int[3];
That array with 3 elements is created dynamically (and that 3
could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p
. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.
Printing declared arrays is easy. You can use sizeof
to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector
. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size
member function:
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
You can, of course, also make this a template to accept vectors of other types.
What you are talking about is the preview image and text that Facebook extracts when you share a link. Facebook uses the Open Graph Protocol to get this data.
Essentially, all you'll have to do is place these og:meta
tags on the URL that you want to share -
<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
<meta property="og:site_name" content="IMDb"/>
<meta property="fb:admins" content="USER_ID"/>
<meta property="og:description"
content="A group of U.S. Marines, under command of
a renegade general, take over Alcatraz and
threaten San Francisco Bay with biological
weapons."/>
As you can see there are both an image property and a description. When you make changes to your pages og:meta
tags, you can test these changes using the Facebook Debugger. It will tell you if you have made any mistakes (and how to fix them!)
I found a simple combo of QoP and speckledcarp's answer using React Hooks and resizing features, with slightly less lines of code:
const [width, setWidth] = useState(window.innerWidth);
const [height, setHeight] = useState(window.innerHeight);
const updateDimensions = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
}
useEffect(() => {
window.addEventListener("resize", updateDimensions);
return () => window.removeEventListener("resize", updateDimensions);
}, []);
Oh yeah make sure that the resize
event is in double quotes, not single. That one got me for a bit ;)
I have a case, where I need to be able to create and change my stylesheets remotely affecting thousands of clients, but due to risk of heavy network load, I'm not turning off cache.
Since I can change the HTML contents remotely, I then link the stylesheet with a hashcode matching the contents of the stylesheet.
https://example.com/contents/stylesheetctrl?id=12345&hash=-1456405808
That said, I also use a client-side javascript function to carefully replace nodes and attributes when HTML contents change, meaning the stylesheet link tag will not be replaced, only the href attribute will change.
This scenario works fine in Chrome, Firefox and Edge on Windows, also Chrome on Android, but doesn't always work in webclients on Android to my surprise. So I'm more or less looking for something to force/trigger the update using javascript - optimally without needing to reload the page.
var a = new String('')
var b = ''
var c = []
function isString(x) {
return x !== null && x !== undefined && x.constructor === String
}
console.log(isString(a))
console.log(isString(b))
console.log(isString(c))
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
I just found this excellent little tutorial. broken link (Cached version)
I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.
As you can see, you don't need configuration files and all that messy stuff.
By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.
To further generalize @Alexander's example, outer
is relevant in cases where a function must compute itself on each pair of vector values:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
outer(vars1,vars2,mult_one)
gives:
> outer(vars1, vars2, mult_one)
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 20 40 60
[3,] 30 60 90
private int user_movie_matrix[][];Th
. should be `private int user_movie_matrix[][];
.
private int user_movie_matrix[][];
should be private static int user_movie_matrix[][];
cfiltering(numberOfUsers, numberOfMovies);
should be new cfiltering(numberOfUsers, numberOfMovies);
Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.
For Mac OS X Mojave and above
To Uninstall Homebrew, run following command:
sudo ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
To Install Homebrew, run following command:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And if you run into Permission denied issue, try running this command followed by install command again:
sudo chown -R $(whoami):admin /usr/local/* && sudo chmod -R g+rwx /usr/local/*
$data = array(
'name' => $_POST['name'] ,
'groupname' => $_POST['groupname'],
'age' => $_POST['age']
);
$this->db->where('id', $_POST['id']);
$this->db->update('tbl_user', $data);
You have to delete the deployment key first if you are going to add the same key under Manage Account SSH Key.
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
If you forget your password for SQL plus 10g then follow the steps :
If it asks your old password then type the one you have given while installing.
Try adding this to the .htaccess
file in that directory.
Options -Indexes
This has more information.
this should serve the purpose
android:textAlignment="textStart"
Pure Bash, use parameter substitution:
string="Hello\ world"
echo ${string//\\/\\\\} | someprog
My problem solved with these :
1- Add this to your head :
<base href="/" />
2- Use this in app.config
$locationProvider.html5Mode(true);
There is a c++ class called _bstr_t
. It has useful methods and a collection of overloaded operators.
For example, you can easily assign from a const wchar_t *
or a const char *
just doing _bstr_t bstr = L"My string";
Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();
. You can even convert it back to a regular char const char * c = bstr.operator char *();
You can then just use the const wchar_t *
or the const char *
to initialize a new std::wstring
oe std::string
.
All you need to do is use getCheckedRadioButtonId()
and isChecked()
method,
if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}
https://developer.android.com/guide/topics/ui/controls/radiobutton.html
I know this is old but in case it is helpful to others:
If you need to run a script and want the terminal to pop up so you can see the results you can do like Abyss Knight said and change the extension to .command. If you double click on it it will open a terminal window and run.
I however needed this to run from automator or appleScript. So to get this to open a new terminal the command I ran from "run shell script" was "open myShellScript.command" and it opened in a new terminal.
The input() function returns a string which may contain a "list of numbers". You should have understood that the numbers[2] operation returns the third element of an iterable. A string is an iterable, but an iterable of characters, which isn't what you want - you want to average the numbers in the input string.
So there are two things you have to do before you can get to the averaging shown by garyprice:
Hint for step 1: you have to split the input string into non-space substrings.
Step 2 (convert string to integer) should be easy to find with google.
HTH
Facelets is a XML based view technology. The &
is a special character in XML representing the start of an entity like &
which ends with the ;
character. You'd need to either escape it, which is ugly:
rendered="#{beanA.prompt == true && beanB.currentBase != null}"
or to use the and
keyword instead, which is preferred as to readability and maintainability:
rendered="#{beanA.prompt == true and beanB.currentBase != null}"
Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true
:
rendered="#{beanA.prompt and beanB.currentBase != null}"
If you want to manage key misses you should use TryGetValue
https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
}
Maybe you can try this way
function myFunction()
{
$("select[id^=myID]").attr("disabled", true);
var txtSelect = $("select[id^=myID] option[selected]").text();
}
This sets the first value of the drop-down as the default and it seems readonly
<script>
setTimeout(function(){
window.location.href = 'form2.html';
}, 5000);
</script>
And for home page add only '/'
<script>
setTimeout(function(){
window.location.href = '/';
}, 5000);
</script>
The variable in the for loop is an integer sequence, and so eventually you do this:
> y=as.integer(60000)*as.integer(60000)
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
whereas in the while loop you are creating a floating point number.
Its also the reason these things are different:
> seq(0,2,1)
[1] 0 1 2
> seq(0,2)
[1] 0 1 2
Don't believe me?
> identical(seq(0,2),seq(0,2,1))
[1] FALSE
because:
> is.integer(seq(0,2))
[1] TRUE
> is.integer(seq(0,2,1))
[1] FALSE
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
I had to puzzle my way through self-signed certificates on Windows by combining bits and pieces from the given answers and further resources. Here is my own (and hopefully complete) walk-through. Hope it will spare you some of my own painful learning curve. It also contains infos on related topics that will pop up sooner or later when you create your own certs.
Don't use makecert.exe. It has been deprecated by Microsoft.
The modern way uses a Powershell command.
Windows 10:
Open Powershell with Administrator privileges:
New-SelfSignedCertificate -DnsName "*.dev.local", "dev.local", "localhost" -CertStoreLocation cert:\LocalMachine\My -FriendlyName "Dev Cert *.dev.local, dev.local, localhost" -NotAfter (Get-Date).AddYears(15)
Windows 8, Windows Server 2012 R2:
In Powershell on these systems the parameters -FriendlyName and -NotAfter do not exist. Simply remove them from the above command line.
Open Powershell with Administrator privileges:
New-SelfSignedCertificate -DnsName "*.dev.local", "dev.local", "localhost" -CertStoreLocation cert:\LocalMachine\My
An alternative is to use the method for older Windows version below, which allows you to use all the features of Win 10 for cert creation...
Older Windows versions:
My recommendation for older Windows versions is to create the cert on a Win 10 machine, export it to a .PFX file using an mmc instance (see "Trust the certificate" below) and import it into the cert store on the target machine with the old Windows OS. To import the cert do NOT right-click it. Although there is an "Import certificate" item in the context menu, it failed all my trials to use it on Win Server 2008. Instead open another mmc instance on the target machine, navigate to "Certificates (Local Computer) / Personal / Certificates", right click into the middle pane and select All tasks ? Import.
Both of the above commands create a certificate for the domains localhost
and *.dev.local
.
The Win10 version additionally has a live time of 15 years and a readable display name of "Dev Cert *.dev.local, dev.local, localhost".
Update: If you provide multiple hostname entries in parameter -DnsName
(as shown above) the first of these entries will become the domain's Subject (AKA Common Name). The complete list of all hostname entries will be stored in the field Subject Alternative Name (SAN) of the certificate. (Thanks to @BenSewards for pointing that out.)
After creation the cert will be immediately available in any HTTPS bindings of IIS (instructions below).
The new cert is not part of any chain of trust and is thus not considered trustworthy by any browsers. To change that, we will copy the cert to the certificate store for Trusted Root CAs on your machine:
Open mmc.exe, File ? Add/Remove Snap-In ? choose "Certificates" in left column ? Add ? choose "Computer Account" ? Next ? "Local Computer..." ? Finish ? OK
In the left column choose "Certificates (Local Computer) / Personal / Certificates".
Find the newly created cert (in Win 10 the column "Friendly name" may help).
Select this cert and hit Ctrl-C to copy it to clipboard.
In the left column choose "Certificates (Local Computer) / Trusted Root CAs / Certificates".
Hit Ctrl-V to paste your certificate to this store.
The certificate should appear in the list of Trusted Root Authorities and is now considered trustworthy.
Now you may go to IIS Manager, select the bindings of a local website ? Add ? https ? enter a host name of the form myname.dev.local
(your cert is only valid for *.dev.local
) and select the new certificate ? OK.
Add to hosts
Also add your host name to C:\Windows\System32\drivers\etc\hosts:
127.0.0.1 myname.dev.local
Happy
Now Chrome and IE should treat the certificate as trustworthy and load your website when you open up https://myname.dev.local
.
Firefox maintains its own certificate store. To add your cert here, you must open your website in FF and add it to the exceptions when FF warns you about the certificate.
For Edge browser there may be more action needed (see further down).
To test your certs, Firefox is your best choice. (Believe me, I'm a Chrome fan-boy myself, but FF is better in this case.)
Here are the reasons:
The certificate is not trusted because it is self-signed.
This warning is correct! As noted above, Firefox does not use the Windows certificate store and will only trust this certificate, if you add an exception for it. The button to do this is right below the warnings.
The certificate is not valid for the name ...
This warning shows, that you did something wrong. The (wildcard) domain of your certificate does not match the domain of your website. The problem must be solved by either changing your website's (sub-)domain or by issuing a new certificate that matches. In fact you could add an exception in FF even if the cert does not match, but you would never get a green padlock symbol in Chrome with such a combination.
Firefox can display many other nice and understandable cert warnings at this place, like expired certs, certs with outdated signing algorithms, etc. I found no other browser that gave me that level of feedback to nail down any problems.
In the above New-SelfSignedCertificate command we used the wildcard domain *.dev.local
.
You may think: Why not use *.local
?
Simple reason: It is illegal as a wildcard domain.
Wildcard certificates must contain at least a second level domain name.
So, domains of the form *.local
are nice to develop HTTP websites. But not so much for HTTPS, because you would be forced to issue a new matching certificate for each new project that you start.
Important side notes:
motör_head.dev.local
to your wildcard pattern *.dev.local
. They will comply when you switch to motoer-head.dev.local
.*.dev.local
matches myname.dev.local
but NOT other.myname.dev.local
! *.*.dev.local
) are NOT possible in certificates.
So other.myname.dev.local
can only be covered by a wildcard of the form *.myname.dev.local
. As a result, it is best not to use a forth level domain part. Put all your variations into the third level part. This way you will get along with a single certificate for all your dev sites.This is not really about self-signed certificates, but still related to the whole process:
After following the above steps, Edge may not show any content when you open up myname.dev.local
.
The reason is a characteristic feature of the network management of Windows 10 for Modern Apps, called "Network Isolation".
To solve that problem, open a command prompt with Administrator privileges and enter the following command once:
CheckNetIsolation LoopbackExempt -a -n=Microsoft.MicrosoftEdge_8wekyb3d8bbwe
More infos about Edge and Network Isolation can be found here: https://blogs.msdn.microsoft.com/msgulfcommunity/2015/07/01/how-to-debug-localhost-on-microsoft-edge/
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
so:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>
If you are looking for single characters, you can use String.IndexOfAny()
.
If you want arbitrary strings, then I'm not aware of a .NET method to achieve that "directly", although a regular expression would work.
Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
//starts with http
}
Guava also has Base64 (among other encodings and incredibly useful stuff)
cout << text << i;
The <<
operator for ostream returns a reference to the ostream, so you can just keep chaining the <<
operations. That is, the above is basically the same as:
cout << text;
cout << i;
You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.
<script>
var to_check=$(this).val();
var cur_string=$("#0").text();
var to_chk = "that";
var cur_str= "that";
if(to_chk.localeCompare(cur_str) == 0){
alert("both are equal");
$("#0").attr("class","correct");
} else {
alert("both are not equal");
$("#0").attr("class","incorrect");
}
</script>
I could be wrong because I've never used Angular, but I believe you are probably using ng-bind
, which will create just a TextNode.
You will want to use ng-bind-html
instead.
http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml
Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'
http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe
Here's a demo:
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
In your apache config file (../bin/apachex.y.z/cong/httpd.conf)
Just change
< Directory "c:/wamp/www/" >
...
...
"Require local" ===> "Require all granted"
< /Directory >
This allows other pc's to access (to read) your web folder.
Of course you can, just use setTimeout
to change a class or something to trigger the transition.
HTML:
<p id="aap">OHAI!</p>
CSS:
p {
opacity:1;
transition:opacity 500ms;
}
p.waa {
opacity:0;
}
JS to run on load or DOMContentReady:
setTimeout(function(){
document.getElementById('aap').className = 'waa';
}, 5000);
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using cv::MatIterator_
cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
std::cout << *_it << std::endl;
}
You can use StringBuffer
StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
You can try this:
this.activatedRoute.paramMap.subscribe(x => {
let id = x.get('id');
console.log(id);
});
f-strings, also called “formatted string literals,” are string literals that have an f
at the beginning; and curly braces containing expressions that will be replaced with their values.
f-strings are evaluated at runtime.
So your code can be re-written as:
string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")
And this will evaluate to:
I will go there
I will go now
great
You can learn more about it here.
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
Also internationalization.
I fooled around with this some a while back. Did this in my model:
[Display(Name = "XXX", ResourceType = typeof(Labels))]
I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.
In there I had key = XXX, value = "meaningful string in that culture."
I just moved to Spring Boot 1.4 and found these properties were renamed:
spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.time-between-eviction-runs-millis=3600000
spring.datasource.dbcp.validation-query=SELECT 1
I was able to set the default value or whatever value using the following:
Template:
<mat-form-field>
<mat-label>Holiday Destination</mat-label>
<mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
<mat-option [value]="nyc">New York</mat-option>
<mat-option [value]="london">London</mat-option>
<mat-option [value]="india">Delhi</mat-option>
<mat-option [value]="Oslo">Oslo</mat-option>
</mat-select>
</mat-form-field>
Component:
export class WhateverComponent implements OnInit{
selectedCity: string;
}
ngOnInit() {
this.selectedCity = 'london';
}
}
If you add your site to "Local Intranet" in
Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.
Add you site URL here and it will work.
Update for New Version of Chrome
Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.
You may want to use the jasypt library (Java Simplified Encryption), which is quite easy to use. ( Also, it's recommended to check against the encrypted password rather than decrypting the encrypted password )
To use jasypt, if you're using maven, you can include jasypt into your pom.xml file as follows:
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.3</version>
<scope>compile</scope>
</dependency>
And then to encrypt the password, you can use StrongPasswordEncryptor
public static String encryptPassword(String inputPassword) {
StrongPasswordEncryptor encryptor = new StrongPasswordEncryptor();
return encryptor.encryptPassword(inputPassword);
}
Note: the encrypted password is different every time you call encryptPassword but the checkPassword method can still check that the unencrypted password still matches each of the encrypted passwords.
And to check the unencrypted password against the encrypted password, you can use the checkPassword method:
public static boolean checkPassword(String inputPassword, String encryptedStoredPassword) {
StrongPasswordEncryptor encryptor = new StrongPasswordEncryptor();
return encryptor.checkPassword(inputPassword, encryptedStoredPassword);
}
The page below provides detailed information on the complexities involved in creating safe encrypted passwords.
Or, just add your binary path into the PATH. At the end of the bashrc:
...
export PATH=$PATH:/home/user/.local/bin/
save the file and run:
source .bashrc
and the command will work.
convert Collection into string as comma seperated in Java 8
listOfString object contains ["A","B","C" ,"D"] elements-
listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))
Output is :- 'A','B','C','D'
And Convert Strings Array to List in Java 8
String string[] ={"A","B","C","D"};
List<String> listOfString = Stream.of(string).collect(Collectors.toList());
you may check this http://coenraets.org/blog/2011/10/sample-application-with-jquery-mobile-and-phonegap/ and you can also check http://mobile.tutsplus.com/category/tutorials/phonegap/ which provide you with a good sample
Here are the primary differences between using System.out
/.err
/.in
and System.console()
:
System.console()
returns null if your application is not run in a terminal (though you can handle this in your application)System.console()
provides methods for reading password without echoing charactersSystem.out
and System.err
use the default platform encoding, while the Console
class output methods use the console encodingThis latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:
public class ConsoleDemo {
public static void main(String[] args) {
String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510",
"\u2502Hello\u2502",
"\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
for (String s : data) {
System.out.println(s);
}
for (String s : data) {
System.console().writer().println(s);
}
}
}
On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:
???????
?Hello?
???????
+-----+
¦Hello¦
+-----+
Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.
According to this message on the GCC mailing list, you can use the file "nul" instead of /dev/null:
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
(Credits to Danny for this code; copy-pasted from his message.)
You can also use this special "nul" file through redirection.
For me, the issue was some plugin in my Visual Studio started forcing my application into x64 64bit mode, so the Oracle driver wasn't being found as I had Oracle 32bit installed.
So if you are having this issue, try running Visual Studio in safemode (devenv /safemode). I could find that it was looking in SYSWOW64 for the ic.dll file by using the ProcMon app by SysInternals/Microsoft.
Update: For me it was the Telerik JustTrace product that was causing the issue, it was probably hooking in and affecting the runtime version somehow to do tracing.
Update2: It's not just JustTrace causing an issue, JustMock is causing the same processor mode issue. JustMock is easier to fix though: Click JustMock-> Disable Profiler and then my web app's oracle driver runs in the correct CPU mode. This might be fixed by Telerik in the future.
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
You can look at the docs for the SlugField
to get to know more about it in more descriptive way.
I just tried the same and came up with following solution:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Inside my Main I get the needed countries-object with
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
which sets currCountry to the last country, in this case Countries.KENTUCKY.
Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.
AppCompat
supportOther answers suspecting if android:tint
will work on only 21+ devices only, AppCompat(v23.2.0 and above) now provides a backward compatible handling of tint attribute.
So, the course of action would be to use AppCompatImageView
and app:srcCompat
(in AppCompat namespace) instead of android:src
(Android namespace).
Here is an example(AndroidX: This is androidx.appcompat.widget.AppCompatImageView ;)):
<android.support.v7.widget.AppCompatImageView
android:id="@+id/credits_material_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:scaleType="fitCenter"
android:tint="#ffd2ee"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/ic_dollar_coin_stack" />
And don't forget to enable vector drawable support in gradle:
vectorDrawables.useSupportLibrary = true
I updated many times, until I couldn't update any more, but I never got a prompt on my screen; I just kept getting the device offline.
My problem was that I was running the ADB command from a different directory to what was actually being updated.
The correct updated directory for the ADB exe is:
C:\Program Files (x86)\Android\android-sdk\platform-tools\
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
lateinit vs lazy
lateinit
i) Use it with mutable variable[var]
lateinit var name: String //Allowed
lateinit val name: String //Not Allowed
ii) Allowed with only non-nullable data types
lateinit var name: String //Allowed
lateinit var name: String? //Not Allowed
iii) It is a promise to compiler that the value will be initialized in future.
NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
lazy
i) Lazy initialization was designed to prevent unnecessary initialization of objects.
ii) Your variable will not be initialized unless you use it.
iii) It is initialized only once. Next time when you use it, you get the value from cache memory.
iv) It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).
v) The variable can only be val.
vi) The variable can only be non-nullable.
We are using DBS of 50 GB+ on our platform. no complains works great. Make sure you are doing everything right! Are you using predefined statements ? *SQLITE 3.7.3
Apply these settings (right after you create the DB)
PRAGMA main.page_size = 4096;
PRAGMA main.cache_size=10000;
PRAGMA main.locking_mode=EXCLUSIVE;
PRAGMA main.synchronous=NORMAL;
PRAGMA main.journal_mode=WAL;
PRAGMA main.cache_size=5000;
Hope this will help others, works great here
It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.
https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.
First, you'll need to install the nc
command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.
Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.
# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]
Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc
, even with the -l
and -k
options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.
# cmd.sh
#! /usr/bin/env bash
while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &
tail -f /dev/null # Or any other command that never exits
I had a similar problem.
Solved it by:
import io
with io.open(filename, 'r', encoding='utf-8') as fn:
lines = fn.readlines()
However, I had another problem. Some html files (in my case) were not utf-8, so I received a similar error. When I excluded those html files, everything worked smoothly.
So, except from fixing the code, check also the files you are reading from, maybe there is an incompatibility there indeed.
use this one line script:
ifconfig | grep "inet " | grep -v 127.0.0.1|awk 'match($0, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/) {print substr($0,RSTART,RLENGTH)}'
mac & linux (tested in ubuntu) both works.
import { readFileSync } from 'fs';
const file = readFileSync('./filename.txt', 'utf-8');
This worked for me.
You may need to wrap the second command in any function or you may need to declare inside a class without keyword const
.
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
Here is an small detector written in Java , just copy and run :)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
public class JarValidator {
public static void main(String[] args) throws IOException {
Path repositoryPath = Paths.get("C:\\Users\\goxr3plus\\.m2");
// Check if the main Repository Exists
if (Files.exists(repositoryPath)) {
// Create a class instance
JarValidator jv = new JarValidator();
List<String> jarReport = new ArrayList<>();
jarReport.add("Repository to process: " + repositoryPath.toString());
// Get all the directory files
List<Path> jarFiles = jv.getFiles(repositoryPath, ".jar");
jarReport.add("Number of jars to process: " + jarFiles.size());
jarReport.addAll(jv.openJars(jarFiles, true));
// Print the report
jarReport.stream().forEach(System.out::println);
} else {
System.out.println("Repository path " + repositoryPath + " does not exist.");
}
}
/**
* Get all the files from the given directory matching the specified extension
*
* @param filePath Absolute File Path
* @param fileExtension File extension
* @return A list of all the files contained in the directory
* @throws IOException
*/
private List<Path> getFiles(Path filePath, String fileExtension) throws IOException {
return Files.walk(filePath).filter(p -> p.toString().endsWith(fileExtension)).collect(Collectors.toList());
}
/**
* Try to open all the jar files
*
* @param jarFiles
* @return A List of Messages for Corrupted Jars
*/
private List<String> openJars(List<Path> jarFiles, boolean showOkayJars) {
int[] badJars = { 0 };
List<String> messages = new ArrayList<>();
// For Each Jar
jarFiles.forEach(path -> {
try (JarFile file = new JarFile(path.toFile())) {
if (showOkayJars)
messages.add("OK : " + path.toString());
} catch (IOException ex) {
messages.add(path.toAbsolutePath() + " threw exception: " + ex.toString());
badJars[0]++;
}
});
messages.add("Total bad jars = " + badJars[0]);
return messages;
}
}
Output
Repository to process: C:\Users\goxr3plus\.m2
Number of jars to process: 4920
C:\Users\goxr3plus\.m2\repository\bouncycastle\isoparser-1.1.18.jar threw exception: java.util.zip.ZipException: zip END header not found
Total bad jars = 1
BUILD SUCCESSFUL (total time: 2 seconds)
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};?
For people who are still struggling, I managed to get this working on all modern browsers IE11 and up.
base64 was no option for me because I wanted to use SASS to generate SVG icons based on any given color. For example: @include svg_icon(heart, #FF0000);
This way I can create a certain icon in any color, and only have to embed the SVG shape once in the CSS. (with base64 you'd have to embed the SVG in every single color you want to use)
There are three things you need be aware of:
URL ENCODE YOUR SVG
As others have suggested, you need to URL encode your entire SVG string for it to work in IE11. In my case, I left out the color values in fields such as fill="#00FF00"
and stroke="#FF0000"
and replaced them with a SASS variable fill="#{$color-rgb}"
so these can be replaced with the color I want. You can use any online converter to URL encode the rest of the string. You'll end up with an SVG string like this:
%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%2041.012%2010.535%2079.541%2028.973%20113.104L3.825%20464.586c345%2012.797%2041.813%2012.797%2015.467%200%2029.872-4.721%2041.813-12.797v158.184z%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E
OMIT THE UTF8 CHARSET IN THE DATA URL When creating your data URL, you need to leave out the charset for it to work in IE11.
NOT background-image: url( data:image/svg+xml;utf-8,%3Csvg%2....)
BUT background-image: url( data:image/svg+xml,%3Csvg%2....)
USE RGB() INSTEAD OF HEX colors Firefox does not like # in the SVG code. So you need to replace your color hex values with RGB ones.
NOT fill="#FF0000"
BUT fill="rgb(255,0,0)"
In my case I use SASS to convert a given hex to a valid rgb value. As pointed out in the comments, it's best to URL encode your RGB string as well (so comma becomes %2C)
@mixin svg_icon($id, $color) {
$color-rgb: "rgb(" + red($color) + "%2C" + green($color) + "%2C" + blue($color) + ")";
@if $id == heart {
background-image: url('data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%204%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E');
}
}
I realize this might not be the best solution for very complex SVG's (inline SVG never is in that case), but for flat icons with only a couple of colors this really works great.
I was able to leave out an entire sprite bitmap and replace it with inline SVG in my CSS, which turned out to only be around 25kb after compression. So it's a great way to limit the amount of requests your site has to do, without bloating your CSS file.
You've instantiated text2 as an Optional (e.g. var text2: String?). This is why you receive Optional("5") in your string. take away the ? and replace with:
var text2: String = ""
Add
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Method
String getUUID(){
TelephonyManager teleManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
String tmSerial = teleManager.getSimSerialNumber();
String tmDeviceId = teleManager.getDeviceId();
String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
if (tmSerial == null) tmSerial = "1";
if (tmDeviceId== null) tmDeviceId = "1";
if (androidId == null) androidId = "1";
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDeviceId.hashCode() << 32) | tmSerial.hashCode());
String uniqueId = deviceUuid.toString();
return uniqueId;
}
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
You can use these string functions,
strstr — Find the first occurrence of a string
stristr — Case-insensitive strstr()
strrchr — Find the last occurrence of a character in a string
strpos — Find the position of the first occurrence of a substring in a string
strpbrk — Search a string for any of a set of characters
If that doesn't help then you should use preg
regular expression
preg_match — Perform a regular expression match
Use the below code to find the count of number of matches that the regex finds in your input
Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);// "regex" here indicates your predefined regex.
Matcher m = p.matcher(pattern); // "pattern" indicates your string to match the pattern against with
boolean b = m.matches();
if(b)
count++;
while (m.find())
count++;
This is a generalized code not specific one though, tailor it to suit your need
Please feel free to correct me if there is any mistake.
If you want to see the difference between the last commit of a single file you can do:
git log -p -1 filename
This will give you the diff of the file in git, is not comparing your local file.
int arsize(int st1[]) {
int i = 0;
for (i; !(st1[i] & (1 << 30)); i++);
return i;
}
This works for me :)
I use the InvokeOnClick()
method. It takes two arguments: Control and EventArgs. If you need the EventArgs, then create an instance of it and pass it in, else use InvokeOnClick(controlToClick, null);
. You can use a variety of Mouse event related arguments that derive from EventArgs such as MouseEventArgs.
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue