In the HTTP request you need to set Content-Type to: Content-Type: application/json
So if you're using fiddler client add Content-Type: application/json
to the request header
One line of code using jQuery which hides the 2nd column:
$('td:nth-child(2)').hide();
If your table has header(th), use this:
$('td:nth-child(2),th:nth-child(2)').hide();
Source: Hide a Table Column with a Single line of jQuery code
jsFiddle to test the code: http://jsfiddle.net/mgMem/1/
If you want to see a good use case, take a look at my blog post:
Hide a table column and colorize rows based on value with jQuery.
Try this
String[] arr = list.toArray(new String[list.size()]);
Here's a completely free C# library, which lets you export from a DataSet
, DataTable
or List<>
into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
Full source code is provided - free of charge - along with instructions, and a demo application.
After adding this class to your application, you can export your DataSet to Excel in just one line of code:
CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");
It doesn't get much simpler than that...
And it doesn't even require Excel to be present on your server.
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
There is a built in method which would be the fastest method also, calling tolist
on the .values
np array:
df.values.tolist()
[[0.0, 3.61, 380.0, 3.0],
[1.0, 3.67, 660.0, 3.0],
[1.0, 3.19, 640.0, 4.0],
[0.0, 2.93, 520.0, 4.0]]
Just a simple folder drill down.
sub sample()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
I wrote a nifty script for this called Gitter using the REST APIs for GitHub and BitBucket:
https://github.com/dderiso/gitter
BitBucket:
gitter -c -r b -l javascript -n node_app
GitHub:
gitter -c -r g -l javascript -n node_app
-c
= create new repo-r
= repo provider (g = GitHub, b = BitBucket)-n
= name the repo-l
= (optional) set the language of the app in the repoWhat's missing from all the explanations is the fact that Java has a strict rule of class name = file name. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".
Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.
Here is your answer:
Create a file called Include.java. In this file, add this:
public class Include {
public static String MyLongString= "abcdef";
}
Create another file, say, User.java. In this file, put:
import java.io.*;
public class User extends Include {
System.out.println(Include.MyLongString);
}
Although I am upvoting Manish's answer as the fastest and most targeted method, I have also seen naive solutions which just recursively iterate through a view hierarchy and update all elements' typefaces in turn. Something like this:
public static void applyFonts(final View v, Typeface fontToSet)
{
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
applyFonts(child, fontToSet);
}
} else if (v instanceof TextView) {
((TextView)v).setTypeface(fontToSet);
}
} catch (Exception e) {
e.printStackTrace();
// ignore
}
}
You would need to call this function on your views both after inflating layout and in your Activity's onContentChanged()
methods.
Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?
It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/
I've created the boot entry that disables HyperV and it's working
Try:
document.getElementById("foo").onclick = function (){alert('foo');};
java.sql.Date
If your table has a column of type DATE
:
java.lang.String
The method java.sql.Date.valueOf(java.lang.String)
received a string representing a date in the format yyyy-[m]m-[d]d
. e.g.:
ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
java.util.Date
Suppose you have a variable endDate
of type java.util.Date
, you make the conversion thus:
ps.setDate(2, new java.sql.Date(endDate.getTime());
Current
If you want to insert the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
// Since Java 8
ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
java.sql.Timestamp
If your table has a column of type TIMESTAMP
or DATETIME
:
java.lang.String
The method java.sql.Timestamp.valueOf(java.lang.String)
received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]
. e.g.:
ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");
java.util.Date
Suppose you have a variable endDate
of type java.util.Date
, you make the conversion thus:
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
Current
If you require the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
// Since Java 8
ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
You can use each
for objects too and not just for arrays:
var obj = {
foo: "bar",
baz: "quux"
};
jQuery.each(obj, function(name, value) {
alert(name + ": " + value);
});
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
Sorry for the Zombie thread post - just wanted to round out the code for completeness...
# is_number() function - Uses re = regex library
# Should handle all normal and complex numbers
# Does not accept trailing spaces.
# Note: accepts both engineering "j" and math "i" but only the imaginary part "+bi" of a complex number a+bi
# Also accepts inf or NaN
# Thanks to the earlier responders for most the regex fu
import re
ISNUM_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?[ij]?$')
def is_number(str):
#change order if you have a lot of NaN or inf to parse
if ISNUM_REGEXP.match(str) or str == "NaN" or str == "inf":
return True
else:
return False
# A couple test numbers
# +42.42e-42j
# -42.42E+42i
print('Is it a number?', is_number(input('Gimme any number: ')))
Gimme any number: +42.42e-42j
Is it a number? True
Here is a somehow portable hack for Linux for getting time in milliseconds:
#!/bin/sh
read up rest </proc/uptime; t1="${up%.*}${up#*.}"
sleep 3 # your command
read up rest </proc/uptime; t2="${up%.*}${up#*.}"
millisec=$(( 10*(t2-t1) ))
echo $millisec
The output is:
3010
This is a very cheap operation, which works with shell internals and procfs.
if you have installed NDK succesfully then start with it sample application
http://developer.android.com/sdk/ndk/overview.html#samples
if you are interested another ways of this then may this will help
http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html
I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?
here you can see NestedVM
NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.
Example: Cross compile Hello world C program and run it on android
PRIMARY KEY CONSTRAINT
cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.
You should use data.response
in your JS instead of json.response
.
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
The simplest solution is to add this CSS to the children:
.your-child {
pointer-events: none;
}
Able to achieve this by adding a global tap gesture recognizer to the window
property in the AppDelegate
.
This was a very catch all approach and might not be the desired solution for some but it worked for me. Please let me know if there any pitfalls to this solution.
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Globally dismiss the keyboard when the "background" is tapped.
window?.addGestureRecognizer(
UITapGestureRecognizer(
target: window,
action: #selector(UIWindow.endEditing(_:))
)
)
return true
}
}
Fortunately, jQuery selectors allow you much more freedom:
$("div a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
});
...will attach the specified callback to each <a>
contained in a <div>
.
Remove leading + trailing '0':
list = [i.strip('0') for i in listOfNum ]
Remove leading '0':
list = [ i.lstrip('0') for i in listOfNum ]
Remove trailing '0':
list = [ i.rstrip('0') for i in listOfNum ]
Edit
A better way to do this is:
Create your own less file as a main less file ( like bootstrap.less ).
Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less
)
If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };
).
Original
I have the same problem. This is how I fixed it.
Find the media query:
@media (max-width:1200px) ...
Remove it. (I mean the whole thing , not just @media (max-width:1200px)
)
Since the default width of Bootstrap is 940px, you don't need to do anything.
If you want to have your own max-width
, just modify the css rule in the media query that matches your desired width.
Another reason for PHP to return http code 0 is timeout. In my case, I had the following configuration:
curl_setopt($http, CURLOPT_TIMEOUT_MS,500);
It turned out that the request to the endpoint I was pointing to always took more than 500 ms, always timing out and always returning http code 0.
If you remove this setting (CURLOPT_TIMEOUT_MS) or put a higher value (in my case 5000), you'll get the actual http code, in my case a 200 (as expected).
$pos = $name.IndexOf(";")
$leftPart = $name.Substring(0, $pos)
$rightPart = $name.Substring($pos+1)
Internally, PowerShell uses the String class.
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
its python implementation be like
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', 'mykeyhere'),
)
data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
check this link, it will help convert cURl command to python,php and nodejs
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).
Improved with input from @a_horse_with_no_name in the comments below.
You could even use an empty SELECT
list:
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
Since the SELECT
list is not relevant to the outcome of EXISTS
. Only the existence of at least one qualifying row matters.
Many DNS servers refuse ‘ANY’ queries. So the only way is to query for every type individually. Luckily there are sites that make this simpler. For example, https://www.nslookup.io shows the most popular record types by default, and has support for all existing record types.
I had a problem with setting locale programmatically with devices that has Android OS N and higher. For me the solution was writing this code in my base activity:
(if you don't have a base activity then you should make these changes in all of your activities)
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(updateBaseContextLocale(base));
}
private Context updateBaseContextLocale(Context context) {
String language = SharedPref.getInstance().getSavedLanguage();
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResourcesLocale(context, locale);
}
return updateResourcesLocaleLegacy(context, locale);
}
@TargetApi(Build.VERSION_CODES.N)
private Context updateResourcesLocale(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
note that here it is not enough to call
createConfigurationContext(configuration)
you also need to get the context that this method returns and then to set this context in the attachBaseContext
method.
Press Ctl+T
will open a search box. Delete # symbol and enter your file name.
try this instead and because it needs root privileges use sudo
sudo service tomcat7 status
For googlers and completeness sake:
Here's a reference I always use when I need to go through the pain of implementing html email-templates or signatures: http://www.campaignmonitor.com/css/
I'ts a list of CSS support for most, if not all, CSS options, nicely compared between some of the most used email clients.
For centering, feel free to just use CSS (as the align
attribute is deprecated in HTML 4.01
).
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align: center;">
Your Content
</td>
</tr>
</table>
According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.
<?php
// create a "numeric" array
$animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');
//Normarl display
print_r($animals);
echo "<br/><br/>";
//If splice the array
//array_splice($animals, 2, 2);
unset($animals[3]); // you can unset the particular value
print_r($animals);
?>
Instead of using overflow:hidden
, which is a kind of hack, why not simply setting a fixed height, e.g. height:500px
, to the parent division?
Update (as 2019):
cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml
Explanation (from :h pack
ad :h packages
):
runtimepath
. They must be in ~/.vim/pack/whatever/start [you can only change whatever].plugins
dir in runtimepath
are sourced.So this load the plugin on start (hence the name start).
You can also get optional plugin (loaded with :packadd
) if you put them in ~/.vim/pack/bundle/opt
For my case increasing the memory using -Xmx
option was the solution.
I had a 10g file read in java and each time I got the same error. This happened when the value in the RES
column in top
command reached to the value set in -Xmx option. Then by increasing the memory using -Xmx
option everything went fine.
There was another point as well. When I set JAVA_OPTS
or CATALINA_OPTS
in my user account and increased the amount of memory again I got the same error. Then, I printed the value of those environment variables in my code which gave me different values than what I set. The reason was that Tomcat was the root for that process and then as I was not a su-doer I asked the admin to increase the memory in catalina.sh
in Tomcat.
This is working fine:
$('#country').val($("#country option:contains('It\'s Me')").val());
You can try max-height: 70px; See if that works.
Well (a long one) ... if you insist to have $scope
access inside a service, you can:
ngapp.factory('Scopes', function (){
var mem = {};
return {
store: function (key, value) { mem[key] = value; },
get: function (key) { return mem[key]; }
};
});
ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) {
Scopes.store('myCtrl', $scope);
}]);
ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){
// there you are
var $scope = Scopes.get('myCtrl');
}]);
From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/
For some time now, you can also only rely on the data.table
package and its IDate
class plus associated functions. (Check ?as.IDate()
). So, no need to additionally install lubridate
.
require(data.table)
some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
You need to install the following in order to run the current version of MySQL Workbench:
See: dev.mysql.com/doc/workbench/en/wb-requirements-software.html .
Hash map doesn't preserves the insertion order.
Example. Hashmap
If you are inserting keys as
1 3
5 9
4 6
7 15
3 10
It can store it as
4 6
5 9
3 10
1 3
7 15
Linked Hashmap preserves the insertion order.
Example.
If you are inserting keys
1 3
5 9
4 6
7 15
3 10
It will store it as
1 3
5 9
4 6
7 15
3 10
same as we insert.
Tree map stores the vales in Increasing Order Of Keys.
Example.
If you are inserting keys
1 3
5 9
4 6
7 15
3 10
It will store it as
1 3
3 10
4 6
5 9
7 15
Assuming that you do not want to change orig
, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
Or without itertools:
dest = dict(list(orig.items()) + list(extra.items()))
Note that you only need to pass the result of items()
into list()
on Python 3, on 2.x dict.items()
already returns a list so you can just do dict(orig.items() + extra.items())
.
As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:
from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))
You can use a User-defined function or a view instead of a procedure.
A procedure can return multiple result sets, each with its own schema. It's not suitable for using in a SELECT
statement.
How about str.gsub("subString", "")
Check out the Ruby Doc
#include <iostream>
#include <sstream>
int main()
{
unsigned int i = 4967295; // random number
std::string str1, str2;
unsigned int u1, u2;
std::stringstream ss;
Using void pointer:
// INT to HEX
ss << (void*)i; // <- FULL hex address using void pointer
ss >> str1; // giving address value of one given in decimals.
ss.clear(); // <- Clear bits
// HEX to INT
ss << std::hex << str1; // <- Capitals doesn't matter so no need to do extra here
ss >> u1;
ss.clear();
Adding 0x:
// INT to HEX with 0x
ss << "0x" << (void*)i; // <- Same as above but adding 0x to beginning
ss >> str2;
ss.clear();
// HEX to INT with 0x
ss << std::hex << str2; // <- 0x is also understood so need to do extra here
ss >> u2;
ss.clear();
Outputs:
std::cout << str1 << std::endl; // 004BCB7F
std::cout << u1 << std::endl; // 4967295
std::cout << std::endl;
std::cout << str2 << std::endl; // 0x004BCB7F
std::cout << u2 << std::endl; // 4967295
return 0;
}
The array you created by Dim s(0) As String
IS NOT EMPTY
In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.
You should instead try using System.Collections.Specialized.StringCollection
or (even better) System.Collections.Generic.List(Of String)
. They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.
If you really want an empty string array, declare it like this:
Dim s As String()
or
Dim t() As String
In fact, in R, this operation is very easy:
If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:
a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a
If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:
#for a data.frame:
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b
Note the difference is.nan
when it's a matrix vs. is.na
when it's a data frame.
Doing
#...
b[is.nan(b)] <- 0
#...
yields: Error in is.nan(b) : default method not implemented for type 'list'
because b is a data frame.
Note: Edited for small but confusing typos
Sanitizing an Html document involves a lot of tricky things. This package maybe of help: https://github.com/mganss/HtmlSanitizer
Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!
As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.
What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.
Using printf is like using a machine gun to fire one bullet.
File.WriteAllText(path, String.Empty);
Alternatively,
File.Create(path).Close();
TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.
BLOB is used for storing binary data while Text is used to store large string.
BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.
NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
NEW_VAR=${ENV_VAR}
else
NEW_VAR="new value"
fi
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
You could do
alert(document.getElementById('table1').rows[0].cells.length)
fiddle here http://jsfiddle.net/TEZ73/
TL;DR
If you can use iotop
, do so. Else this might help.
Use top
, then use these shortcuts:
d 1 = set refresh time from 3 to 1 second
1 = show stats for each cpu, not cumulated
This has to show values > 1.0 wa
for at least one core - if there are no diskwaits, there is simply no IO load and no need to look further. Significant loads usually start > 15.0 wa
.
x = highlight current sort column
< and > = change sort column
R = reverse sort order
Chose 'S', the process status column. Reverse the sort order so the 'R' (running) processes are shown on top. If you can spot 'D' processes (waiting for disk), you have an indicator what your culprit might be.
For Folder Copy You can Use
robocopy C:\Source D:\Destination /E
For File Copy
copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y
Delete file in some folder last modify date more than some day
forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"
And you can Shedule task in windows perform this task automatically in specific time.
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
php_value upload_max_filesize 30M
is correct.
You will have to contact your hosters -- some don't allow you to change values in php.ini
For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.
#include <gtest/gtest.h>
const bool skip_some_test = true;
bool some_test_was_run = false;
void someTest() {
EXPECT_TRUE(!skip_some_test);
some_test_was_run = true;
}
TEST(BasicTest, Sanity) {
EXPECT_EQ(1, 1);
if(!skip_some_test) {
someTest();
EXPECT_TRUE(some_test_was_run);
}
}
This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.
Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.
As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.
The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.
You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
After looking at the code you're having typos, here is the updated code
var clicks = 0; // should be var not int
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
}
Note: Don't use in-built handlers, as .click()
is javascript function try giving different name like clickME()
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.
You can view the StringUtils API at the previously linked website.
"Don't reinvent the wheel"
Then, as this blog post suggests,
"How to Cure Net::HTTP’s Risky Default HTTPS Behavior"
you might want to install the always_verify_ssl_certificates
gem that allow you to set a default value for ca_file
.
give username as admin
and leave the password empty
Can you predict how long the user input would be?
VARCHAR(X)
Max Length: variable, up to 65,535 bytes (64KB)
Case: user name, email, country, subject, password
TEXT
Max Length: 65,535 bytes (64KB)
Case: messages, emails, comments, formatted text, html, code, images, links
MEDIUMTEXT
Max Length: 16,777,215 bytes (16MB)
Case: large json bodies, short to medium length books, csv strings
LONGTEXT
Max Length: 4,294,967,29 bytes (4GB)
Case: textbooks, programs, years of logs files, harry potter and the goblet of fire, scientific research logging
There's more information on this question.
Go to File > Project Structure
Select app
or mobile
whatever you gave the name from Modules
Choose Signing
tab.
You can add certificate clicking on the + button.
I know this post is kinda old but...
As 'witttness' pointed out.
About Your Own Custom Theme You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.
I see it as Bootstrap has seen over the years that everyone wants something a bit different than the core styles. While you could modify bootstrap.css it might break things and it could make updating to a newer version a real pain and time consuming. Downloading from a 'theme' site means you have to wait on if that creator updates that theme, big if sometimes, right?
Some build their own 'custom.css' file and that's ok, but if you use 'bootstrap-theme.css' a lot of stuff is already built and this allows you to roll your own theme faster 'without' disrupting the core of bootstrap.css. I for one don't like the 3D buttons and gradients most of the time, so change them using bootstrap-theme.css. Add margins or padding, change the radius to your buttons, and so on...
Intent eventIntentMessage =getPackageManager()
.getLaunchIntentForPackage(Telephony.Sms.getDefaultSmsPackage(getApplicationContext));
startActivity(eventIntentMessage);
It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:
You can set the minimum and maximum memory heap size with the
JVM -Xms and -Xmx parameters.
The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use
JAVA_OPTS=-Xms128m -Xmx1024m
You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter
-XX:MaxPermSize=256m
For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.
The following is an example of a setenv.bat file:
set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"
You have to enable access first: Configuring Manager Application Access
simply add + "<br />" +
is enough for a line break
The Python executable might be installed at a location other than /usr/bin, but env
is nearly always present in that location so using /usr/bin/env
is more portable.
In new APIs don't forget about TAG:
notify(String tag, int id, Notification notification)
and correspondingly
cancel(String tag, int id)
instead of:
cancel(int id)
https://developer.android.com/reference/android/app/NotificationManager
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")
Returns: December
Some more info on the Python doc website
[EDIT : great comment from @GiriB] You can also use %b
which returns the short notation for month name.
mydate.strftime("%b")
For the example above, it would return Dec
.
if you really want to get rid of the scrollbar, split the information up into two separate pages.
Usability guidelines on scrollbars by Jakob Nielsen:
There are five essential usability guidelines for scrolling and scrollbars:
- Offer a scrollbar if an area has scrolling content. Don't rely on auto-scrolling or on dragging, which people might not notice.
- Hide scrollbars if all content is visible. If people see a scrollbar, they assume there's additional content and will be frustrated if they can't scroll.
- Comply with GUI standards and use scrollbars that look like scrollbars.
- Avoid horizontal scrolling on Web pages and minimize it elsewhere.
- Display all important information above the fold. Users often decide whether to stay or leave based on what they can see without scrolling. Plus they only allocate 20% of their attention below the fold.
To make your scrollbar only visible when it is needed (i.e. when there is content to scroll down to), use overflow: auto
.
If you are using an <a/>
to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open()
fails, make the default scenario to open a new window via target
(and prevent it if window.open()
succeeds).
HTML
<a href="http://my/url" target="_blank" id="myLink">Link</a>
JS
var spawn = function (e) {
try {
window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
e.preventDefault(); // Or: return false;
} catch(e) {
// Allow the default event handler to take place
}
}
document.getElementById("myLink").onclick = spawn;
This happened to me as well, I just wrote up a quick function rather than worrying about updating my compiler.
string to_string(int number){
string number_string = "";
char ones_char;
int ones = 0;
while(true){
ones = number % 10;
switch(ones){
case 0: ones_char = '0'; break;
case 1: ones_char = '1'; break;
case 2: ones_char = '2'; break;
case 3: ones_char = '3'; break;
case 4: ones_char = '4'; break;
case 5: ones_char = '5'; break;
case 6: ones_char = '6'; break;
case 7: ones_char = '7'; break;
case 8: ones_char = '8'; break;
case 9: ones_char = '9'; break;
default : ErrorHandling("Trouble converting number to string.");
}
number -= ones;
number_string = ones_char + number_string;
if(number == 0){
break;
}
number = number/10;
}
return number_string;
}
If you use divmod, you are immune to different flavors of integer division:
# show time strings for 3800 seconds
# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)
# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(3800,),60,60])
# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
return "%02d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(round(t*1000),),1000,60,60])
print secondsToStr(3800.123)
Prints:
63:20
01:03:20
01:03:20.123
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
Firstly, add path of visual studio common tools (c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools
) into the system path. To learn how to add a path into system path, please check this website:
http://www.computerhope.com/issues/ch000549.htm. You just need to this once.
After that, whenever you need, open a command line and execute vsvars32.bat
to add all required visual studio tools' paths into the system path.
Then, you can call nmake -f makefile.mak
PS: Path of visual studio common tools might be different in your system. Please change it accordingly.
Here is a function I use to execute sql commands. You just have to change $sqlCommand.CommandText to the name of your sproc and $SqlCommand.CommandType to CommandType.StoredProcedure.
function execute-Sql{
param($server, $db, $sql )
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db
$sqlConnection.Open()
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 120
$sqlCommand.Connection = $sqlConnection
$sqlCommand.CommandText= $sql
$text = $sql.Substring(0, 50)
Write-Progress -Activity "Executing SQL" -Status "Executing SQL => $text..."
Write-Host "Executing SQL => $text..."
$result = $sqlCommand.ExecuteNonQuery()
$sqlConnection.Close()
}
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
def insenStringCompare(s1, s2):
""" Method that takes two strings and returns True or False, based
on if they are equal, regardless of case."""
try:
return s1.lower() == s2.lower()
except AttributeError:
print "Please only pass strings into this method."
print "You passed a %s and %s" % (s1.__class__, s2.__class__)
Another example of JSON.parse :
var fs = require('fs');
var file = __dirname + '/config.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});
Hope this will help you..
var list = [];
$(document).ready(function () {
$('#test').click(function () {
var oRows = $('#MainContent_Table1 tr').length;
$('#MainContent_Table1 tr').each(function (index) {
list.push(this.cells[0].innerHTML);
});
});
});
In VS2017, have tried all the above solution but nothing works. We are using Azure devops for versioning.
Select the project which driving you nuts for a long time
Right click the branch or solution > Advanced > get specific version
Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.
The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.
Try this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://domain1.com',
'http://domain2.com',
);
if (in_array($http_origin, $allowed_domains))
{
header("Access-Control-Allow-Origin: $http_origin");
}
If you just want to install PHP no matter what version it is, try PHP7
sudo apt-get install php7.0 php7.0-mcrypt
This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.
.element
{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Well it's the usual url encoding
So they stand for [
, respectively ]
If you have a checkbox with an id checkbox_id.You can set its state with JS with prop('checked', false)
or prop('checked', true)
$('#checkbox_id').prop('checked', false);
I think the easiest way is to use the Tag property in your FormOptions class set the Tag = value you need to pass and after the ShowDialog method read it as
myvalue x=(myvalue)formoptions.Tag;
for me best solotion this is
Thread.CurrentThread.Abort();
and force close app.
The above solutions must work. However you can try this one:
OnClientClick="return SomeMethod();return false;"
and remove return statement from the method.
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
In springboot 2.4.1 im just added annotation @SpringBootTest
in my test, and obviously, setted spring.profiles.active = test
in my src/test/resources/application.yml
Im using @ExtendWith({SpringExtension.class})
and @ContextConfiguration(classes = {RabbitMQ.class, GenericMapToObject.class, ModelMapper.class, StringUtils.class})
for external confs
As far as I can tell this will only work on newer versions of Android, so you will probably have to figure out a different way to do it. This solution works for me on 4.4, but not on 4.0 or 2.3.3, so this will not be a useful way to go about sharing content for an app that's meant to run on any Android device.
In manifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.myapp.SharingActivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Take careful note of how you specify the authorities. You must specify the activity from which you will create the URI and launch the share intent, in this case the activity is called SharingActivity. This requirement is not obvious from Google's docs!
file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="just_a_name" path=""/>
</paths>
Be careful how you specify the path. The above defaults to the root of your private internal storage.
In SharingActivity.java:
Uri contentUri = FileProvider.getUriForFile(getActivity(),
"com.mydomain.myapp.SharingActivity", myFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share with"));
In this example we are sharing a JPEG image.
Finally it is probably a good idea to assure yourself that you have saved the file properly and that you can access it with something like this:
File myFile = getActivity().getFileStreamPath("mySavedImage.jpeg");
if(myFile != null){
Log.d(TAG, "File found, file description: "+myFile.toString());
}else{
Log.w(TAG, "File not found!");
}
https://stackoverflow.com/a/37672153/2914140 helped me.
I made this layout for an activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/transparent" <- Add transparent color in AppBarLayout.
android:theme="@style/AppTheme.AppBarOverlay"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:theme="@style/ToolbarTheme"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/ToolbarTheme"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
<- Remove app:layout_behavior=...
/>
</android.support.design.widget.CoordinatorLayout>
If this doesn't work, in onCreate()
of the activity write (where toolbar is @+id/toolbar):
toolbar.background.alpha = 0
If you want to set a semi-transparent color (like #30ff00ff), then set toolbar.setBackgroundColor(color)
. Or even set a background color of AppBarLayout
.
In my case styles of AppBarLayout
and Toolbar
didn't play role.
You most likely had the files staged.
git add src/file/to/ignore
To undo the staged files,
git reset HEAD
This will unstage the files allowing for the following git command to execute successfully.
git update-index --assume-unchanged src/file/to/ignore
A little curiosity from the Java Language Specification, chapter 17, section 17.5.4 "Write-protected Fields":
Normally, a field that is final and static may not be modified. However, System.in, System.out, and System.err are static final fields that, for legacy reasons, must be allowed to be changed by the methods System.setIn, System.setOut, and System.setErr. We refer to these fields as being write-protected to distinguish them from ordinary final fields.
Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4
This is the solution implemented as a function:
Class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
}
getInitialState = () => ({
/* state props */
})
resetState = () => {
this.setState(this.getInitialState());
}
}
Check out the examples on Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm
def binary_search(a, key, imin=0, imax=None):
if imax is None:
# if max amount not set, get the total
imax = len(a) - 1
while imin <= imax:
# calculate the midpoint
mid = (imin + imax)//2
midval = a[mid]
# determine which subarray to search
if midval < key:
# change min index to search upper subarray
imin = mid + 1
elif midval > key:
# change max index to search lower subarray
imax = mid - 1
else:
# return index number
return mid
raise ValueError
Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:
function foo(doBar)
{
function bar()
{
console.log( 'bar' );
}
function baz()
{
console.log( 'baz' );
}
window.baz = baz;
if ( doBar ) bar();
}
In this example, the baz function will be available for use after the foo
function has been run, as it's overridden window.baz
. The bar function will not be available to any context other than scopes contained within the foo
function.
as a different example:
function Fizz(qux)
{
this.buzz = function(){
console.log( qux );
};
}
The Fizz
function is designed as a constructor so that, when run, it assigns a buzz
function to the newly created object.
At its simplest:
#include <iostream>
using namespace std;
class A {
public:
A( int x ) : n( x ){}
void print() { cout << n << endl; }
private:
int n;
};
void func( A p ) {
p.print();
}
int main () {
A a;
func ( a );
}
Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.
Adding my 2 cents .If you are using scala and sbt and scala-logging as dependency ;then this can happen because scala-logging's earlier version had the name scala-logging-api.So;essentially the dependency resolutions do not happen because of different names leading to runtime errors while launching the scala application.
All the previous answers are correct. Since no one have hinted out how to turn off all errors in PHP, I would like to mention it here:
error_reporting(0); // Turn off warning, deprecated,
// notice everything except error
Somebody might find it useful...
You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:
def log_test(message)
Rails.logger.info(message)
puts message
end
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
Just do it: Add the class at your div
:
.modal {
margin: auto;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
height: 240px;
}
And read this article for an explanation. Note: Height
is necessary.
SQL Locator (free) has worked great for me. It comes with a lot of options and it's fairly easy to use.
Microsoft Common Object Runtime Library.
See http://www.danielmoth.com/Blog/mscorlibdll.aspx and What does 'Cor' stand for?
to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
In Alpine linux you should do:
apk add curl-dev python3-dev libressl-dev
The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):
SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
FROM dbo.tableZ AS t
ORDER BY t.A;
Not sure what the variables in your question are supposed to represent (they don't match).
First you may check query
when the target column is type bool
(PS: about how to use it please check link )
df.query('BoolCol')
Out[123]:
BoolCol
10 True
40 True
50 True
After we filter the original df by the Boolean column we can pick the index .
df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')
Also pandas have nonzero
, we just select the position of True
row and using it slice the DataFrame
or index
df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')
The ":PATH" part in the accepted answer can be omitted. This syntax may be more memorable:
cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install
...as used in the answers here.
I am using Ubuntu 18.04.1 LTS. In my case I had to open the file:
/home/[username]/netbeans-8.2/etc/netbeans.conf
And change the jdk location to:
netbeans_jdkhome="/opt/jdk/jdk1.8.0_152"
Then saved the file and re-run Netbeans. It worked for me.
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
This is my code for this problem:
<form id="formoid" action="./demoText.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ), url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, { name: $('#name').val()} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
===
(or !==
)==
in Obj-C (pointer equality).==
(or !=
)isEqual:
in Obj-C behavior.Here I compare three instances (class is a reference type)
class Person {}
let person = Person()
let person2 = person
let person3 = Person()
person === person2 // true
person === person3 // false
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
enctype='multipart/form-data
is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.
If you want to allow a user to upload a file via a form, you must use this enctype.
I had the same problem with Entity Framework database first on all CLOB columns.
As a workaround, I filled the text values with spaces to be at least 4000 in width in insert operations (did not come with any better solution).
you will have to manually set $dirty
to true
and $pristine
to false
for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty
and remove ng-pristine
classes from the element. You can use $setDirty()
on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty()
as you mentioned.
This answer may change in the future as they should add $setDirty()
to inputs, seems logical.
No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.
Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.
Even though this is a pretty old questions with multiple accepted answers, I'd like to share how to resolve an obscure "undefined reference to" error.
I was using an alias to refer to std::filesystem::path
: filesystem is in the standard library since C++17 but my program needed to also compile in C++14 so I decided to use a variable alias:
#if (defined _GLIBCXX_EXPERIMENTAL_FILESYSTEM) //is the included filesystem library experimental? (C++14 and newer: <experimental/filesystem>)
using path_t = std::experimental::filesystem::path;
#elif (defined _GLIBCXX_FILESYSTEM) //not experimental (C++17 and newer: <filesystem>)
using path_t = std::filesystem::path;
#endif
Let's say I have three files: main.cpp, file.h, file.cpp:
Note the different libraries used in main.cpp and file.h. Since main.cpp #include'd "file.h" after <filesystem>, the version of filesystem used there was the C++17 one. I used to compile the program with the following commands:
$ g++ -g -std=c++17 -c main.cpp
-> compiles main.cpp to main.o
$ g++ -g -std=c++17 -c file.cpp
-> compiles file.cpp and file.h to file.o
$ g++ -g -std=c++17 -o executable main.o file.o -lstdc++fs
-> links main.o and file.o
This way any function contained in file.o and used in main.o that required path_t
gave "undefined reference" errors because main.o referred to std::filesystem::path
but file.o to std::experimental::filesystem::path
.
To fix this I just needed to change <experimental::filesystem> in file.h to <filesystem>.
str_replace(
array("search","items"),
array("replace", "items"),
$string
);
Very very very simpely no other modules !!!
import os
p = r"C:\Users\bilal\Documents\face Recognition python\imgs\northon.jpg"
# Get the filename only from the initial file path.
filename = os.path.basename(p)
# Use splitext() to get filename and extension separately.
(file, ext) = os.path.splitext(filename)
# Print outcome.
print("Filename without extension =", file)
print("Extension =", ext)
void itos(int value, char* str, size_t size) {
snprintf(str, size, "%d", value);
}
..works with call by reference. Use it like this e.g.:
int someIntToParse;
char resultingString[length(someIntToParse)];
itos(someIntToParse, resultingString, length(someIntToParse));
now resultingString
will hold your C-'string'.
The char is a fixed-length character data type, the varchar is a variable-length character data type.
Because char is a fixed-length data type, the storage size of the char value is equal to the maximum size for this column. Because varchar is a variable-length data type, the storage size of the varchar value is the actual length of the data entered, not the maximum size for this column.
You can use char when the data entries in a column are expected to be the same size. You can use varchar when the data entries in a column are expected to vary considerably in size.
Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.
Is the result of getElementsByClassName an Array?
No
If not, what is it?
As with all DOM methods that return multiple elements, it is a NodeList, see https://developer.mozilla.org/en/DOM/document.getElementsByClassName
You can also try background:none;border:0px
to buttons.
also the css selectors are div#yes button{..}
and div#no button{..}
. hopes it helps
To find the Unix Timestamp in seconds:
moment().unix()
The documentation is your friend. :)
setTimeout(function(){
},5000);
Place your code inside of the { }
300 = 0.3 seconds
700 = 0.7 seconds
1000 = 1 second
2000= 2 seconds
2200 = 2.2 seconds
3500 = 3.5 seconds
10000 = 10 seconds
etc.
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
Give the first div float: left;
and a fixed width, and give the second div width: 100%;
and float: left;
. That should do the trick. If you want to place items below it you need a clear: both;
on the item you want to place below it.
Just try beeprint
it prints something like this:
instance(Animal):
legs: 2,
name: 'Dog',
color: 'Spotted',
smell: 'Alot',
age: 10,
kids: 0,
I think is exactly what you need.
A problem can be that you try to access you session inside of your controller's __constructor()
function.
From Laravel 5.3+ this is not possible anymore because it is not intended to work anyway, as stated in the upgrade guide.
In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
For more background information also read Taylor his response.
Workaround
If you still want to use this, you can dynamically create a middleware and run it in the constructor, as described in the upgrade guide:
As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class ProjectController extends Controller { /** * All of the current user's projects. */ protected $projects; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware(function ($request, $next) { $this->projects = Auth::user()->projects; return $next($request); }); } }
Chrome://chrome/settings/Privacy/Content settings/JavaScript
and there you can PASTE your website's URL in Manage exceptions..
and change the JavaScript priority from ALLOW to BLOCK.
There is also http v2 which is a wrapper for curl. Can be installed via pecl.
Why do you want to remove it?
If it is to prevent multiple instances being created, then just use the following approach...
$('#myDialog')
.dialog(
{
title: 'Error',
close: function(event, ui)
{
$(this).dialog('close');
}
});
And when the error occurs, you would do...
$('#myDialog').html("Ooops.");
$('#myDialog').dialog('open');
Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:
Ctrl + h to bring up the find replace dialog.
In the Find what:
text box include your regex: .*help.*\r?\n
(where the \r
is optional in case the file doesn't have Windows line endings).
Leave the Replace with:
text box empty.
Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All
and voila! All lines containing your search term help
have been removed.
You can check this
[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{
string url = "https://localhost:44305/Templates/ReportPage.html";
System.Uri uri = new System.Uri(url);
return Redirect(uri);
}
Change the 5
to 5.0
. You're getting integer division.
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
Yes, you can simulate a mouse click by creating an event and dispatching it:
function click(x,y){
var ev = document.createEvent("MouseEvent");
var el = document.elementFromPoint(x,y);
ev.initMouseEvent(
"click",
true /* bubble */, true /* cancelable */,
window, null,
x, y, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
}
Beware of using the click
method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click()
does the right thing but have not confirmed.
A good way to create Public/Global variables is to treat the Form like a class object and declare properties and use Public Property Get [variable] to access property/method. Also you might need to reference or pass a Reference to the instantiated Form module. You will get errors if you call methods to forms/reports that are closed.
Example: pass Me.Form.Module.Parent into sub/function not inside form.
Option Compare Database
Option Explicit
''***********************************''
' Name: Date: Created Date Author: Name
' Current Version: 1.0
' Called by:
''***********************************''
' Notes: Explain Who what when why...
' This code Example requires properties to be filled in
''***********************************''
' Global Variables
Public GlobalData As Variant
''***********************************''
' Private Variables
Private ObjectReference As Object
Private ExampleVariable As Variant
Private ExampleData As Variant
''***********************************''
' Public properties
Public Property Get ObjectVariable() As Object
Set ObjectVariable = ObjectReference
End Property
Public Property Get Variable1() As Variant
'Recommend using variants to avoid data errors
Variable1 = ExampleVariable
End property
''***********************************''
' Public Functions that return values
Public Function DataReturn (Input As Variant) As Variant
DataReturn = ExampleData + Input
End Function
''***********************************''
' Public Sub Routines
Public Sub GlobalMethod()
'call local Functions/Subs outside of form
Me.Form.Refresh
End Sub
''***********************************''
' Private Functions/Subs used not visible outside
''***********************************''
End Code
So in the other module you would be able to access:
Public Sub Method1(objForm as Object)
'read/write data value
objForm.GlobalData
'Get object reference (need to add Public Property Set to change reference object)
objForm.ObjectVariable
'read only (needs Public property Let to change value)
objForm.Variable1
'Gets result of function with input
objForm.DataReturn([Input])
'runs sub/function from outside of normal scope
objForm.GlobalMethod
End Sub
If you use Late Binding like I do always check for Null values and objects that are Nothing before attempting to do any processing.
I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:
from pyspark.sql import SQLContext
# assuming the spark environemnt is set and sc is spark.sparkContext
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")
Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.
More specific:
$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));
I stumbled upon this old listing pondering this same question. My band-aid for this same question was to make my header text into a link. I then changed the color and removed text decoration with CSS. Now to make the entire header picture a link, I expanded the padding of the anchor tag until it reached close to the edge of the header image.... This worked to my satisfaction, and I figured i would share.
Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.
Use Environment.NewLine
whenever you want in any string. An example:
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
text = text.Replace("@", "@" + System.Environment.NewLine);
Migrate to androidX library
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate
to AndroidX from the menu bar.
Source: https://developer.android.com/jetpack/androidx/migrate
Here's a cute trick to deal with directories and make. Instead of using multiline strings, or "cd ;" on each command, define a simple chdir function as so:
CHDIR_SHELL := $(SHELL)
define chdir
$(eval _D=$(firstword $(1) $(@D)))
$(info $(MAKE): cd $(_D)) $(eval SHELL = cd $(_D); $(CHDIR_SHELL))
endef
Then all you have to do is call it in your rule as so:
all:
$(call chdir,some_dir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
You can even do the following:
some_dir/myTest:
$(call chdir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '@angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '@angular/router';
...
this.value = this.route.snapshot.params['key'];
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
I found good explanation for How To Revert The Merge from this link and I copy pasted the explanation below and it would be helpful just in case if below link doesn't work.
How to revert a faulty merge Alan([email protected]) said:
I have a master branch. We have a branch off of that that some developers are doing work on. They claim it is ready. We merge it into the master branch. It breaks something so we revert the merge. They make changes to the code. they get it to a point where they say it is ok and we merge again. When examined, we find that code changes made before the revert are not in the master branch, but code changes after are in the master branch. and asked for help recovering from this situation.
The history immediately after the "revert of the merge" would look like this:
---o---o---o---M---x---x---W
/
---A---B
where A and B are on the side development that was not so good, M is the merge that brings these premature changes into the mainline, x are changes unrelated to what the side branch did and already made on the mainline, and W is the "revert of the merge M" (doesn’t W look M upside down?). IOW, "diff W^..W" is similar to "diff -R M^..M".
Such a "revert" of a merge can be made with:
$ git revert -m 1 M After the developers of the side branch fix their mistakes, the history may look like this:
---o---o---o---M---x---x---W---x
/
---A---B-------------------C---D
where C and D are to fix what was broken in A and B, and you may already have some other changes on the mainline after W.
If you merge the updated side branch (with D at its tip), none of the changes made in A or B will be in the result, because they were reverted by W. That is what Alan saw.
Linus explains the situation:
Reverting a regular commit just effectively undoes what that commit did, and is fairly straightforward. But reverting a merge commit also undoes the data that the commit changed, but it does absolutely nothing to the effects on history that the merge had. So the merge will still exist, and it will still be seen as joining the two branches together, and future merges will see that merge as the last shared state - and the revert that reverted the merge brought in will not affect that at all. So a "revert" undoes the data changes, but it's very much not an "undo" in the sense that it doesn't undo the effects of a commit on the repository history. So if you think of "revert" as "undo", then you're going to always miss this part of reverts. Yes, it undoes the data, but no, it doesn't undo history. In such a situation, you would want to first revert the previous revert, which would make the history look like this:
---o---o---o---M---x---x---W---x---Y
/
---A---B-------------------C---D
where Y is the revert of W. Such a "revert of the revert" can be done with:
$ git revert W This history would (ignoring possible conflicts between what W and W..Y changed) be equivalent to not having W or Y at all in the history:
---o---o---o---M---x---x-------x----
/
---A---B-------------------C---D
and merging the side branch again will not have conflict arising from an earlier revert and revert of the revert.
---o---o---o---M---x---x-------x-------*
/ /
---A---B-------------------C---D
Of course the changes made in C and D still can conflict with what was done by any of the x, but that is just a normal merge conflict.
Here is an adaptation for Luda's answer for Swift:
In the declaration of your UIViewController subclass put
let numberToolbar: UIToolbar = UIToolbar()
in ViewDidLoad put:
numberToolbar.barStyle = UIBarStyle.BlackTranslucent
numberToolbar.items=[
UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "hoopla"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.Bordered, target: self, action: "boopla")
]
numberToolbar.sizeToFit()
textField.inputAccessoryView = numberToolbar //do it for every relevant textfield if there are more than one
and the add the functions hoopla and hoopla (feel free to choose other names, just change the selector names in ViewDidLoad accordingly
func boopla () {
textField.resignFirstResponder()
}
func hoopla () {
textField.text=""
textField.resignFirstResponder()
}
http://railsforzombies.org/ is a nice one. Introducing an all new way to learn Ruby on Rails in the browser with no additional configuration needed.
The other answers will give you a good idea how to accomplish what you have asked for....
However
There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.
That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:
adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4
Screen recording is limited to a maximum of 3 minutes.
Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord
It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.
Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."
I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.
This makes callbacks sound like return statements at the end of methods.
I'm not sure that's what they are.
I think Callbacks are actually a call to a function, as a consequence of another function being invoked and completing.
I also think Callbacks are meant to address the originating invocation, in a kind of "hey! that thing you asked for? I've done it - just thought I would let you know - back over to you".
In our case, the reason was invalid header. As mentioned in Edit 4:
Look for something similar:
HTTP2_SESSION_RECV_INVALID_HEADER
--> error = "Invalid character in header name."
--> header_name = "charset=utf-8"
I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.
Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.
var validations ={
email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
// Check all the input fields of type email. This function will handle all the email addresses validations
$("input[type=email]").change( function(){
// Set the regular expression to validate the email
validation = new RegExp(validations['email'][0]);
// validate the email value against the regular expression
if (!validation.test(this.value)){
// If the validation fails then we show the custom error message
this.setCustomValidity(validations['email'][1]);
return false;
} else {
// This is really important. If the validation is successful you need to reset the custom error message
this.setCustomValidity('');
}
});
})
I know its an old question and the Android world has mostly moved on to RecyclerViews, but for anyone interested, you may find this library very interesting.
It uses the BaseAdapter used with the ListView to detect when the list has been scrolled to the last item or when it is being scrolled away from the last item.
It comes with an example project(barely 100 lines of Activity code) that can be used to quickly understand how it works.
Simple usage:
class Boy{
private String name;
private double height;
private int age;
//Other code
}
An adapter to hold Boy objects would look like:
public class BoysAdapter extends EndlessAdapter<Boy>{
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent
.getContext());
holder = new ViewHolder();
convertView = inflater.inflate(
R.layout.list_cell, parent, false);
holder.nameView = convertView.findViewById(R.id.cell);
// minimize the default image.
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Boy boy = getItem(position);
try {
holder.nameView.setText(boy.getName());
///Other data rendering codes.
} catch (Exception e) {
e.printStackTrace();
}
return super.getView(position,convertView,parent);
}
Notice how the BoysAdapter's getView method returns a call to the EndlessAdapter superclass's getView
method. This is 100% essential.
Now to create the adapter, do:
adapter = new ModelAdapter() {
@Override
public void onScrollToBottom(int bottomIndex, boolean moreItemsCouldBeAvailable) {
if (moreItemsCouldBeAvailable) {
makeYourServerCallForMoreItems();
} else {
if (loadMore.getVisibility() != View.VISIBLE) {
loadMore.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onScrollAwayFromBottom(int currentIndex) {
loadMore.setVisibility(View.GONE);
}
@Override
public void onFinishedLoading(boolean moreItemsReceived) {
if (!moreItemsReceived) {
loadMore.setVisibility(View.VISIBLE);
}
}
};
The loadMore
item is a button or other ui element that may be clicked to fetch more data from the url.
When placed as described in the code, the adapter knows exactly when to show that button and when to disable it. Just create the button in your xml and place it as shown in the adapter code above.
Enjoy.
1) Enter below command on command prompt
npm install -g @angular/cli
2) Make sure that C:\Users\_username_\AppData\Roaming\npm this path is not hidden.
3) Add C:\Users\_username_\AppData\Roaming\npm and
C:\Users\_username_\AppData\Roaming\npm \node_modules@angular\cli\bin to both enviroment variable path.
4) Open new command prompt and type ng help. It will work.
You should be using IHtmlString
instead:
IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>");
Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:
@Html.Raw(str)
Compared to:
@str
Also, I also think it's a bit safer vs. using @Html.Raw()
, as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).
I generally try to avoid using Html.Raw()
whenever possible.
One other thing worth noting, is I'm not sure where you're assigning str
, but a few things that concern me with how you may be implementing this.
First, this should be done in a controller, regardless of your solution (IHtmlString
or Html.Raw
). You should avoid any logic like this in your view, as it doesn't really belong there.
Additionally, you should be using your ViewModel
for getting values to your view (and again, ideally using IHtmlString
as the property type). Seeing something like @Html.Encode(str)
is a little concerning, unless you were doing this just to simplify your example.
simple solution is this:
game.js:
document.addEventListener('click', printMousePos, true);
function printMousePos(e){
cursorX = e.pageX;
cursorY= e.pageY;
$( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}
Building off of ngoozeff
's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:
cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
&>/dev/null
sets the command’s stdout
and stderr
to /dev/null
instead of inheriting them from the parent process. &
makes the shell run the command in the background. disown
removes the “current” job, last one stopped or put in the background, from under the shell’s job control.In some shells you can also use &!
instead of & disown
; they both have the same effect. Bash doesn’t support &!
, though.
Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}"
rather than "${cmd}"
:
cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;
If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.
Here's a function for it:
#!/bin/bash
# Run a command in the background.
_evalBg() {
eval "$@" &>/dev/null & disown;
}
cmd="google-chrome";
_evalBg "${cmd}";
If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:
select filename ,
status ,
max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'
Easy!
Changes all spaces to tab
:%s/\s/\t/g
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
If you want to run your scripts, then
mysql -u root -p < yourscript.sql
You are looking for the window.scrollTop()
function.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > some_number) {
// do something
}
});
You can customize the JsonSerializerSettings
by using the Formatters.JsonFormatter.SerializerSettings
property in the HttpConfiguration
object.
For example, you could do that in the Application_Start() method:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
Here's a slide in/out animation between fragments:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.listFragment, new YourFragment());
transaction.commit();
We are using an objectAnimator.
Here are the two xml files in the animator subfolder.
enter_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="x"
android:valueFrom="2000"
android:valueTo="0"
android:valueType="floatType" />
</set>
exit_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="x"
android:valueFrom="0"
android:valueTo="-2000"
android:valueType="floatType" />
</set>
I hope that would help someone.
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
You can also use =OFFSET([@column];-1;0)
if you are in a named table.
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.