I found "git-big-picture" quite useful: https://github.com/esc/git-big-picture
It creates pretty 2D graphs using dot/graphviz instead of the rather linear, "one-dimensional" views gitk and friends produce. With the -i option it shows the branch points and merge commits but leaves out everything in-between.
try this below solution:
exclude:path.resolve(__dirname, "node_modules")
You could try using unidecode
, which is available as a ruby gem and as a perl module on cpan. Essentially, it works as a huge lookup table, where each unicode code point relates to an ascii character or string.
I use the ssh-ident tool for this.
From its man-page:
ssh-ident - Start and use ssh-agent and load identities as necessary.
I've checked DamienG's answer in LinqPad. Instead of
g.Group.Max(s => s.uid)
should be
g.Max(s => s.uid)
Thank you!
It sounds like your printMousePos
function should:
Currently, it does this:
See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.
It seems like you probably don't need that mousemove event at all; I would try something like this:
function printMousePos(e) {
var cursorX = e.pageX;
var cursorY = e.pageY;
document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}
When inplace=True
is passed, the data is renamed in place (it returns nothing), so you'd use:
df.an_operation(inplace=True)
When inplace=False
is passed (this is the default value, so isn't necessary), performs the operation and returns a copy of the object, so you'd use:
df = df.an_operation(inplace=False)
I have an histogram with the variable : group
Here how I calculate my median :
int[] group = new int[nbr];
// -- Fill the group with values---
// sum all data in median
int median = 0;
for (int i =0;i<nbr;i++) median += group[i];
// then divide by 2
median = median / 2;
// find 50% first part
for (int i = 0; i < nbr; i++)
{
median -= group[i];
if (median <= 0)
{
median = i;
break;
}
}
median is the group index of median
I couldn't find a better algorithm..so decided to write one :) Correct me if this is wrong.
class KthLargestBST{
protected static int findKthSmallest(BSTNode root,int k){//user calls this function
int [] result=findKthSmallest(root,k,0);//I call another function inside
return result[1];
}
private static int[] findKthSmallest(BSTNode root,int k,int count){//returns result[]2 array containing count in rval[0] and desired element in rval[1] position.
if(root==null){
int[] i=new int[2];
i[0]=-1;
i[1]=-1;
return i;
}else{
int rval[]=new int[2];
int temp[]=new int[2];
rval=findKthSmallest(root.leftChild,k,count);
if(rval[0]!=-1){
count=rval[0];
}
count++;
if(count==k){
rval[1]=root.data;
}
temp=findKthSmallest(root.rightChild,k,(count));
if(temp[0]!=-1){
count=temp[0];
}
if(temp[1]!=-1){
rval[1]=temp[1];
}
rval[0]=count;
return rval;
}
}
public static void main(String args[]){
BinarySearchTree bst=new BinarySearchTree();
bst.insert(6);
bst.insert(8);
bst.insert(7);
bst.insert(4);
bst.insert(3);
bst.insert(4);
bst.insert(1);
bst.insert(12);
bst.insert(18);
bst.insert(15);
bst.insert(16);
bst.inOrderTraversal();
System.out.println();
System.out.println(findKthSmallest(bst.root,11));
}
}
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
As it solved the problem, I put it as an answer.
Don't use single and double quotes, especially when you define a raw string with r
in front of it.
The correct call is then
path = r"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"
or
path = r'C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1'
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
I received this error after I moved from a 5s to a 6s. I recovered the new 6s from a backup of the old iPhone. Because of this on the new iPhone the old app was installed.
The old app did not show up in the 6s "Installed Apps" list! I manually deleted this old app from the 6s and everything was fine.
If the id
column has no default value, but has NOT NULL
constraint, then you have to provide a value yourself
INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())
To summarize Laryx Decidua's answer:
define and use a function like the following
plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
if (is.null(ylim))
ylim <- c(min(y-err), max(y+err))
plot(x, y, ylim=ylim, pch=19, ...)
arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}
where one can override the automatic ylim, and also pass extra parameters such as main, xlab, ylab.
create directive with this code:
$scope.$watch($http.pendingRequests, toggleLoader);
function toggleLoader(status){
if(status.length){
element.addClass('active');
} else {
element.removeClass('active');
}
}
I was trying to run a .net core 3.1 site from IIS 10 on windows 10 pro box, and got this error. Did the following to resolve it.
First turn on the following iis feature on.
Then follow the link below.
Install the .net core hosting bundle.
The direct link is
I have installed the .net core sdk and run time as well. But this did not resolve the issue.
What made the difference is the .net core hosting bundle.
A disabled
element is, (self-explaining) disabled and thereby logically not editable, so:
set the disabled attribute [...] changes the editable attribute too
Is an intended and well-defined behaviour.
The real problem here seems to be you're trying to set disabled
to false
via setAttribute()
which doesn't do what you're expecting. an element is disabled if the disabled
-attribute is set, independent of it's value (so, disabled="true"
, disabled="disabled"
and disabled="false"
all do the same: the element gets disabled). you should instead remove the complete attribute:
element.removeAttribute("disabled");
or set that property directly:
element.disabled = false;
Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:
require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
uri.query_values['param1']
=> 'value1'
(It also apparently handles param encoding/decoding, unlike URI)
Abstract:
The reason why you are getting this error
message is because you are trying to call a method on an int
type of a variable. This would work if would have called len()
function on a list
type of a variable. Let's examin the two cases:
Fail:
num = 10
print(len(num))
The above will produce an error similar to yours due to calling len()
function on an int
type of a variable;
Success:
data = [0, 4, 8, 9, 12]
print(len(data))
The above will work since you are calling a function on a list
type of a variable;
FragmentActivity
gives you all of the functionality of Activity
plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.
If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity
and use the native Fragments introduced in v11 without issue. FragmentActivity
was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.
I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.
Just checked IE 7, Firefox 3.6.8 Mac, Firefox 3.6.8 Windows, and Safari:
word-wrap: break-word;
works for long links inside of a div with a set width and no overflow declared in the css:
#consumeralerts_leftcol{
float:left;
width: 250px;
margin-bottom:10px;
word-wrap: break-word;
}
I don't see any incompatibility issues
I usually find that ProgrammableWeb is a good place to go when looking for APIs.
If you know the arrays are of the same size it is provably faster to sort then compare
Arrays.sort(array1)
Arrays.sort(array2)
return Arrays.equals(array1, array2)
If you do not want to change the order of the data in the arrays then do a System.arraycopy
first.
Seems like you just forgot the comma to separate the classes. So based on your configuration the following will work:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
Alternatively you could also define it as follow:
spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
spring.autoconfigure.exclude[1]=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.autoconfigure.exclude[2]=org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
spring.autoconfigure.exclude[3]=org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
Here is some code to convert either IPV4 or IPv6 in varchar format to binary(16) and back. This is the smallest form I could think of. It should index well and provide a relatively easy way to filter on subnets. Requires SQL Server 2005 or later. Not sure it's totally bulletproof. Hope this helps.
-- SELECT dbo.fn_ConvertIpAddressToBinary('2002:1ff:6c2::1ff:6c2')
-- SELECT dbo.fn_ConvertIpAddressToBinary('10.4.46.2')
-- SELECT dbo.fn_ConvertIpAddressToBinary('bogus')
ALTER FUNCTION dbo.fn_ConvertIpAddressToBinary
(
@ipAddress VARCHAR(39)
)
RETURNS BINARY(16) AS
BEGIN
DECLARE
@bytes BINARY(16), @vbytes VARBINARY(16), @vbzone VARBINARY(2)
, @colIndex TINYINT, @prevColIndex TINYINT, @parts TINYINT, @limit TINYINT
, @delim CHAR(1), @token VARCHAR(4), @zone VARCHAR(4)
SELECT
@delim = '.'
, @prevColIndex = 0
, @limit = 4
, @vbytes = 0x
, @parts = 0
, @colIndex = CHARINDEX(@delim, @ipAddress)
IF @colIndex = 0
BEGIN
SELECT
@delim = ':'
, @limit = 8
, @colIndex = CHARINDEX(@delim, @ipAddress)
WHILE @colIndex > 0
SELECT
@parts = @parts + 1
, @colIndex = CHARINDEX(@delim, @ipAddress, @colIndex + 1)
SET @colIndex = CHARINDEX(@delim, @ipAddress)
IF @colIndex = 0
RETURN NULL
END
SET @ipAddress = @ipAddress + @delim
WHILE @colIndex > 0
BEGIN
SET @token = SUBSTRING(@ipAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1)
IF @delim = ':'
BEGIN
SET @zone = RIGHT('0000' + @token, 4)
SELECT
@vbzone = CAST('' AS XML).value('xs:hexBinary(sql:variable("@zone"))', 'varbinary(2)')
, @vbytes = @vbytes + @vbzone
IF @token = ''
WHILE @parts + 1 < @limit
SELECT
@vbytes = @vbytes + @vbzone
, @parts = @parts + 1
END
ELSE
BEGIN
SET @zone = SUBSTRING('' + master.sys.fn_varbintohexstr(CAST(@token AS TINYINT)), 3, 2)
SELECT
@vbzone = CAST('' AS XML).value('xs:hexBinary(sql:variable("@zone"))', 'varbinary(1)')
, @vbytes = @vbytes + @vbzone
END
SELECT
@prevColIndex = @colIndex
, @colIndex = CHARINDEX(@delim, @ipAddress, @colIndex + 1)
END
SET @bytes =
CASE @delim
WHEN ':' THEN @vbytes
ELSE 0x000000000000000000000000 + @vbytes
END
RETURN @bytes
END
-- SELECT dbo.fn_ConvertBinaryToIpAddress(0x200201FF06C200000000000001FF06C2)
-- SELECT dbo.fn_ConvertBinaryToIpAddress(0x0000000000000000000000000A0118FF)
ALTER FUNCTION [dbo].[fn_ConvertBinaryToIpAddress]
(
@bytes BINARY(16)
)
RETURNS VARCHAR(39) AS
BEGIN
DECLARE
@part VARBINARY(2)
, @colIndex TINYINT
, @ipAddress VARCHAR(39)
SET @ipAddress = ''
IF SUBSTRING(@bytes, 1, 12) = 0x000000000000000000000000
BEGIN
SET @colIndex = 13
WHILE @colIndex <= 16
SELECT
@part = SUBSTRING(@bytes, @colIndex, 1)
, @ipAddress = @ipAddress
+ CAST(CAST(@part AS TINYINT) AS VARCHAR(3))
+ CASE @colIndex WHEN 16 THEN '' ELSE '.' END
, @colIndex = @colIndex + 1
IF @ipAddress = '0.0.0.1'
SET @ipAddress = '::1'
END
ELSE
BEGIN
SET @colIndex = 1
WHILE @colIndex <= 16
BEGIN
SET @part = SUBSTRING(@bytes, @colIndex, 2)
SELECT
@ipAddress = @ipAddress
+ CAST('' as xml).value('xs:hexBinary(sql:variable("@part") )', 'varchar(4)')
+ CASE @colIndex WHEN 15 THEN '' ELSE ':' END
, @colIndex = @colIndex + 2
END
END
RETURN @ipAddress
END
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
public String hashString(String s) throws NoSuchAlgorithmException {
byte[] hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
hash = md.digest(s.getBytes());
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.length; ++i) {
String hex = Integer.toHexString(hash[i]);
if (hex.length() == 1) {
sb.append(0);
sb.append(hex.charAt(hex.length() - 1));
} else {
sb.append(hex.substring(hex.length() - 2));
}
}
return sb.toString();
}
It depends on the JUnit version and what assert libraries you use.
The original answer for JUnit <= 4.12
was:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
Reference :
$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "address_of_your_css"
});
For DD-MM-YY use this code:
var array = ["03-03-2017', '03-10-2017', '03-25-2017"]
$('#datepicker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ array.indexOf(string) == -1 ]
}
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
Another issue is that you're reading with scanf("%f", &input);
only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf()
call will not assign anything to input
, and won't progress from there. This means it would attempt to keep reading "pi", and failing.
Given the change to while(!feof(stdin))
which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input
and printing the prompt, but the program would never process any new input.
scanf()
returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);
. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char
is for the null terminator on the string).
You know, this is reminding me of all the reasons I hate scanf()
, and why I use fgets()
instead and then maybe parse it using sscanf()
.
I dont know if there is a canonical way, but here's my method:
And use this code:
MyCustomViewCell *cell = (MyCustomViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
UIViewController* c = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
cell = (MyCustomViewCell *)c.view;
[c release];
}
In your example, using
[nib objectAtIndex:0]
may break if Apple changes the order of items in the xib.
In C# the code looks like:
Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);
or
var dictionary = new Dictionary<string, int> {
{"sample1", 1},
{"sample2", 2}
};
In JavaScript:
var dictionary = {
"sample1": 1,
"sample2": 2
}
A C# dictionary object contains useful methods, like dictionary.ContainsKey()
In JavaScript, we could use the hasOwnProperty
like:
if (dictionary.hasOwnProperty("sample1"))
console.log("sample1 key found and its value is"+ dictionary["sample1"]);
The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException
. It's well worth reading and digesting.
I also had this problem, my solution was to have an element above the element i dont want a hover effect on:
.no-hover {_x000D_
position: relative;_x000D_
opacity: 0.65 !important;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.no-hover::before {_x000D_
content: '';_x000D_
background-color: transparent;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
z-index: 60;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<button class="btn btn-primary">hover</button>_x000D_
<span class="no-hover">_x000D_
<button class="btn btn-primary ">no hover</button>_x000D_
</span>
_x000D_
You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).
Nice tutorial on the subject: here.
For errors:
[error] repository access denied. access via a deployment key is read-only. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
[error] fatal: Could not read from remote repository.
[error] fatal: Unable to find remote helper for 'https'
I solved following this steps:
First install this dependencies:
$ yum install expat expat-devel openssl openssl-devel
Then remove git:
$ yum remove git git-all
Now Build and install Git on last version, in this case:
$ wget https://github.com/git/git/archive/v2.13.0.tar.gz
$ tar zxf v.2.13.0.tar.gz
$ cd git-2.13.0/
Then for the configure:
$ make configure
$ ./configure --with-expat --with-openssl
And finally install like this:
$ make
$ make install install-doc install-html install-info
that´s it, now configure your repo with https:
$ git remote add origin https://github.com/*user*/*repo*.git
# Verify new remote
$ git remote -v
if you have configured an ssh key in your remote server you have to delete it.
our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."
right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.
I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:
On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]
Inside the shell, run these commands:
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su
Then, install SuperSU and install SU binary. This will replace the SU binary we just created. (Optional) Remove SuperSU and install Superuser by CWM. Install the su binary again. Now, root works!
In Visual Studio 2017, select Project/Properties and then select the Web option. In the IIS section next to the default project URL click Create Virtual Directory. This solved the problem for me. I think in my case the default project Virtual Directory had been corrupted in some way following a debugging session.
You would use === to test whether a function or variable is false rather than just equating to false (zero or an empty string).
$needle = 'a';
$haystack = 'abc';
$pos = strpos($haystack, $needle);
if ($pos === false) {
echo $needle . ' was not found in ' . $haystack;
} else {
echo $needle . ' was found in ' . $haystack . ' at location ' . $pos;
}
In this case strpos would return 0 which would equate to false in the test
if ($pos == false)
or
if (!$pos)
which is not what you want here.
I'm not a C programmer so I can't give you information on the uses of static in a C program properly, but when it comes to Object Oriented programming static basically declares a variable, or a function or a class to be the same throughout the life of the program. Take for example.
class A
{
public:
A();
~A();
void somePublicMethod();
private:
void somePrivateMethod();
};
When you instantiate this class in your Main you do something like this.
int main()
{
A a1;
//do something on a1
A a2;
//do something on a2
}
These two class instances are completely different from each other and operate independently from one another. But if you were to recreate the class A like this.
class A
{
public:
A();
~A();
void somePublicMethod();
static int x;
private:
void somePrivateMethod();
};
Lets go back to the main again.
int main()
{
A a1;
a1.x = 1;
//do something on a1
A a2;
a2.x++;
//do something on a2
}
Then a1 and a2 would share the same copy of int x whereby any operations on x in a1 would directly influence the operations of x in a2. So if I was to do this
int main()
{
A a1;
a1.x = 1;
//do something on a1
cout << a1.x << endl; //this would be 1
A a2;
a2.x++;
cout << a2.x << endl; //this would be 2
//do something on a2
}
Both instances of the class A share static variables and functions. Hope this answers your question. My limited knowledge of C allows me to say that defining a function or variable as static means it is only visible to the file that the function or variable is defined as static in. But this would be better answered by a C guy and not me. C++ allows both C and C++ ways of declaring your variables as static because its completely backwards compatible with C.
I assume you wanted columns 1
and 9
?
To select multiple columns at once, use
X = data[:, [1, 9]]
To select one at a time, use
x, y = data[:, 1], data[:, 9]
With names:
data[:, ['Column Name1','Column Name2']]
You can get the names from data.dtype.names
…
If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved
method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.
split($pattern,$string)
split strings within a given pattern or regex (it's deprecated since 5.3.0)
preg_split($pattern,$string)
split strings within a given regex pattern
explode($pattern,$string)
split strings within a given pattern
end($arr)
get last array element
So:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
Will return the last element of a -
separated string.
And there's a hardcore way to do this:
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
// | '--- get the last position of '-' and add 1(if don't substr will get '-' too)
// '----- get the last piece of string after the last occurrence of '-'
The GetLastAccessTime property on the System.IO.File class should help.
Some time you miss below line. add this router will understand this.
module.exports = router;
input(char_val, date9.);
You can consider to convert it to word format using input(char_val, worddate.)
You can get a lot in this page http://v8doc.sas.com/sashtml/lrcon/zenid-63.htm
Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.
The declarative and simpler solution would be :
yourMutableMap.replaceAll((key, val) -> return_value_of_bi_your_function); Nb. be aware your modifying your map state. So this may not be what you want.
You should use DateTime.TryParseExcact
if you know the format, or if not and want to use the system settings DateTime.TryParse
. And to print the date,DateTime.ToString
with the right format in the argument. To get the year, month or day you have DateTime.Year
, DateTime.Month
or DateTime.Day
.
See DateTime Structures in MSDN for additional references.
Try this code. This seems working in my case.
$this->db->where(array('id !='=> $id))
#Check code and apply in your Program: #Input= 'pppmm'
s = 'ppppmm'
s = ''.join(set(s))
print(s)
#Output: pm
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
Thanks for the answer. I just got this working on Windows XP, with a few modifications. Here are my steps.
(snip)
<IfModule mime_module>
LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
AddType application/x-httpd-php-source .phps
AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
<Directory "/xampp/htdocs/xampp">
<IfModule php5_module>
<Files "status.php">
php_admin_flag safe_mode off
</Files>
</IfModule>
</Directory>
</IfModule>
(Note that this is taken from the same file in the 1.7.0 xampp distribution. If you run into trouble, check that conf file and make the new one match it.)
You should then be able to start the apache server with PHP 5.2.8. You can tail the G:\xampp\apache\logs\error.log file to see whether there are any errors on startup. If not, you should be able to see the XAMPP splash screen when you navigate to localhost.
Hope this helps the next guy.
cheers,
Jake
You can't create an array immediately because you need to know the number of rows from the beginning (and this would require to read the csv file twice)
You can store values in two List<T>
and then use them or convert into an array using List<T>.ToArray()
Very simple example:
var column1 = new List<string>();
var column2 = new List<string>();
using (var rd = new StreamReader("filename.csv"))
{
while (!rd.EndOfStream)
{
var splits = rd.ReadLine().Split(';');
column1.Add(splits[0]);
column2.Add(splits[1]);
}
}
// print column1
Console.WriteLine("Column 1:");
foreach (var element in column1)
Console.WriteLine(element);
// print column2
Console.WriteLine("Column 2:");
foreach (var element in column2)
Console.WriteLine(element);
N.B.
Please note that this is just a very simple example. Using string.Split
does not account for cases where some records contain the separator ;
inside it.
For a safer approach, consider using some csv specific libraries like CsvHelper on nuget.
bellow are cause above “org.xml.sax.SAXParseException: Content is not allowed in prolog” exception.
<?xml version='1.0' encoding='utf-8'?>
<?xml version='1.0' encoding='utf-8'?>
hello<?xml version='1.0' encoding='utf-16'?>
Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:
$x="a\n";
chomp $x
results in $x
being "a"
.
but in Python:
x="a\n"
x.rstrip()
will mean that the value of x
is still "a\n"
. Even x=x.rstrip()
doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.
First make sure you correct your program:
#include <stdio.h>
int main(void) {
printf("Hello, world!\n"); //printf instead of pintf
return 0;
}
Save the file as HelloWorld.c
and type in the terminal:
gcc -o HelloWorld HelloWorld.c
Afterwards just run the executable like this:
./HelloWorld
You should be seeing Hello World!
You have a few options:
Using Enumerable.Where:
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
Using List.Find:
list.Find(i => i.Property == value); // C# 3.0+
list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
Both of these options return default(T)
(null
for reference types) if no match is found.
As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:
==
for simple value types or where use of operator overloads are desiredobject.Equals(a,b)
for most scenarios where the type is unknown or comparison has potentially been overriddenstring.Equals(a,b,StringComparison)
for comparing stringsobject.ReferenceEquals(a,b)
for identity comparisons, which are usually the fastestif you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.
div.disabled{
display: none;
}
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.
The error says that the parameter needed to the concerned breaking function is not in the required format i.e. string or Buffer
The solution is to change the parameter to string
breakingFunction(JSON.stringify(offendingParameter), ... other params...);
or buffer
breakingFunction(BSON.serialize(offendingParameter), ... other params...);
I solved this problem by wrapping the "dataTable" Table with a div
with overflow:auto
:
.dataTables_scroll
{
overflow:auto;
}
and adding this JS after your dataTable
initialization:
jQuery('.dataTable').wrap('<div class="dataTables_scroll" />');
Don't use sScrollX
or sScrollY
, remove them and add a div
wrapper yourself which does the same thing.
You can use paste
:
paste file1.txt file2.txt > fileresults.txt
Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
If you prefer an Integer[]
instead array of an int[]
array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
The best way to solve this problem is to add cell at the bottom of your table, and this cell will hold indicator.
In swift you need to add this:
look at code below:
import UIKit
class LoadingCell: UITableViewCell {
@IBOutlet weak var indicator: UIActivityIndicatorView!
}
For table view : numOfRows:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourArray.count + 1
}
cellForRawAt indexPath:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == users.count {
// need to change
let loading = Bundle.main.loadNibNamed("LoadingCell", owner: LoadingCell.self , options: nil)?.first as! LoadingCell
return loading
}
let yourCell = tableView.dequeueReusableCell(withIdentifier: "cellCustomizing", for: indexPath) as! UITableViewCell
return yourCell
}
If you notice that my loading cell is created from a nib file. This videos will explain what I did.
As many answers already clarified disabled
is not a DIV
attribute. However xHTML means Extensible HTML. It means you can define your own HTML attributes (all Frontend frameworks does that as well). And CSS supports attribute selectors which is []
.
Use standard HTML with your defined attribute:
<div disabled>My disabled div</div>
Use CSS:
div[disabled] {
opacity: 0.6;
pointer-events: none;
}
NOTE: you can use CSS attribute selector with ID or Class names as well e.g. .myDiv[disabled] {...}
Also can apply value filter e.g.: following HTML disabling standard attribute with value div[disabled=disabled] {...}
.
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum
is already built in!
File: logdate.aspx
<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%
StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());
tsw.Close();
%>
Done
Here's a prefix-suffix solution (similar to the solutions given by JB and Darron) that matches the first block of digits and does not depend on the surrounding underscores:
str='someletters_12345_morele34ters.ext'
s1="${str#"${str%%[[:digit:]]*}"}" # strip off non-digit prefix from str
s2="${s1%%[^[:digit:]]*}" # strip off non-digit suffix from s1
echo "$s2" # 12345
I can tell from your attributes that you're using MSTest. I had a similar issue: my tests were showing up in the Test Explorer, but when I would try to run them (either by choosing Run All or individually selecting them) they would not.
My problem was that I had created the unit test project manually from an empty .NET Standard Class Library project. I had installed the MSTest.TestFramework
NuGet package, but not the MSTest.TestAdapter
package. As soon as I installed the adapter package, they ran as expected.
Seems obvious in retrospect, but when you create unit test projects from a template, you take these things for granted.
Try the following:
color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)
We have tried custom search box with the pasted snippet. This code will useful for all kind of TextFiled
decoration in Flutter. Hope this snippet will helpful for others.
Container(
margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
child: new Theme(
data: new ThemeData(
hintColor: Colors.white,
primaryColor: Colors.white,
primaryColorDark: Colors.white,
),
child:Padding(
padding: EdgeInsets.all(10.0),
child: TextField(
style: TextStyle(color: Colors.white),
onChanged: (value) {
filterSearchResults(value);
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search,color: Colors.white,),
enabled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
borderRadius: BorderRadius.all(Radius.circular(25.0))),
border: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white, width: 0.0),
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
),
),
I find the following code to be much simpler than anything else:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
Of course:
curl http://example.com:11740
curl https://example.com:11740
Port 80 and 443 are just default port numbers.
You are looking for display:
document.getElementById("endTimeLabel").style.display = 'none';
document.getElementById("endTimeLabel").style.display = 'block';
Edit: You could also easily reuse your validation function.
HTML:
<span id="startDateLabel">Start date/time: </span>
<input id="startDateStr" name="startDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="startDateCalendarTrigger">...</button>
<input id="startDateTime" type="text" size="8" name="startTime" value="12:00 AM" onchange="validateHHMM(this.value, 'startTimeLabel');"/>
<label id="startTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label><br />
<span id="endDateLabel">End date/time: </span>
<input id="endDateStr" name="endDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="endDateCalendarTrigger">...</button>
<input id="endDateTime" type="text" size="8" name="endTime" value="12:00 AM" onchange="validateHHMM(this.value, 'endTimeLabel');"/>
<label id="endTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label>
Javascript:
function validateHHMM(value, message) {
var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(value);
if (isValid) {
document.getElementById(message).style.display = "none";
}else {
document.getElementById(message).style.display= "inline";
}
return isValid;
}
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
have a look at this Regex & PHP - isolate src attribute from img tag
perhaps you can walk through the DOM and get the desired attributes. It works fine for me, getting attributes from the body-tag
In regards to @RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
What does your text file look like?? Each line a record?
You'll have to check out the BULK INSERT statement - that should look something like:
BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
CODEPAGE = '1252',
FIELDTERMINATOR = ';',
CHECK_CONSTRAINTS
)
Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.
From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt'
WITH
(
ROWTERMINATOR ='\n'
)
Seems to work just fine in my test environment :-)
kafka don't have direct method for purge/clean-up topic (Queues), but can do this via deleting that topic and recreate it.
first of make sure sever.properties file has and if not add delete.topic.enable=true
then, Delete topic
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic myTopic
then create it again.
bin/kafka-topics.sh --zookeeper localhost:2181 --create --topic myTopic --partitions 10 --replication-factor 2
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
The same as an int:
float f = 6;
Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:
int i = 8;
float f = Convert.ToSingle(i);
Or you can just cast an int to a float:
float f = (float)i;
You can compare the values using equals()
of Java :
public void onClick(View v) {
// TODO Auto-generated method stub
s1=text1.getText().toString();
s2=text2.getText().toString();
if(s1.equals(s2))
Show.setText("Are Equal");
else
Show.setText("Not Equal");
}
I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned Varchar
column.
NOT IN
took about 10 mins, NOT EXISTS
took 4 secs.
I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that NOT EXISTS
is far better or at least that IN
and EXISTS
are not exactly the same and always worth a check before going ahead with code.
If your destination element is empty and will only contain the <svg>
tag you could consider using ng-bind-html
as follow :
Declare your HTML tag in the directive scope variable
link: function (scope, iElement, iAttrs) {
scope.svgTag = '<svg width="600" height="100" class="svg"></svg>';
...
}
Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :
<!-- start of directive template code -->
...
<!-- end of directive template code -->
<div ng-bind-html="svgTag"></div>
Don't forget to include ngSanitize
to allow ng-bind-html
to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.
See official documentation for more details.
Enter the command which php
in the terminal to see which version of PHP you are using. If it's not the PHP version from MAMP, the $PATH variable used by Bash will need to be updated.
First, you should use command "cd /Applications/MAMP/bin/php" to check which php version from MAMP and take note of the version (eg, php5.6.7).
Once you know the version, you should edit the ~/.bash_profile
file (that is, the .bash_profile
that is in your home directory) and add an export line:
export PATH=/Applications/MAMP/bin/php/php5.6.7/bin:$PATH
Make sure that you replace php5.6.7 with the version of PHP that you have selected in MAMP.
Once the file has been saved, make sure that you close close your Terminal and open it again. Once that has been done, you will be using the PHP that ships with MAMP.
One way to easily find what the line should be that you need to put inside your .bash_profile
is to run the following command inside your terminal:
echo export PATH=`cat /Applications/MAMP/conf/apache/httpd.conf \
| grep php | grep -i LoadModule | head -n1 \
| sed -e 's/^[^\/]*\/\(.*\)\/mod.*/\/\1/'`/bin:\$PATH
Copying and pasting those three lines into your terminal will correctly output the PHP version that has been selected inside the MAMP control panel.
Make sure that your path
contains /usr/local/bin/
(Homebrew) or /opt/local/bin
(MacPorts) if you are using PHP that comes with either of these two package managers.
You can find the exact location of PHP using MacPorts with the following command:
port contents php70 | grep bin/php
Note that you should replace php70
with the version of PHP that you have installed.
Homebrew-php (https://github.com/Homebrew/homebrew-php) is a tap that has various different versions of PHP.
You can find the exact location of PHP using Homebrew with the following command:
brew --prefix homebrew/php/php56
Note that you should replace php56
with the version of PHP that you have installed.
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Required email address');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
One of:
In html
<!-- map.size here because -->
<%= map.size() %>
theoretically the following should work, but i never used it this way.
<%= map.size() // map.size here because %>
Say you want to save the string I'm a "foobar"
in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text")
.
With the $text
variable replaced, this will look like this:
INSERT INTO foos (text) VALUES ("I'm a "foobar"")
Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.
mysql_real_escape_string
makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:
mysql_real_escape_string($text) => I\'m a \"foobar\"
This becomes:
INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")
This makes the statement unambiguous and safe. The \
signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string
takes care of.
Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:
$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";
ConcurrentHashMap
You can use java.util.concurrent.ConcurrentHashMap
.
It implements ConcurrentMap
(which extends the Map
interface).
E.g.:
Map<Object, Content> map = new ConcurrentHashMap<Object, Content>();
for (Object key : map.keySet()) {
if (something) {
map.remove(key);
}
}
This approach leaves your code untouched. Only the map
type differs.
From the Perldoc page on sleep:
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().
Actually, it provides usleep()
(which sleeps in microseconds) and nanosleep()
(which sleeps in nanoseconds). You may want usleep()
, which should let you deal with easier numbers. 1 millisecond sleep (using each):
use strict;
use warnings;
use Time::HiRes qw(usleep nanosleep);
# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);
If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select()
function:
# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}
String Data=response.getEntity().getText().toString(); // reading the string value
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
In the discipline of speech recognition, users are divided into goats and sheeps.
For instance, here on page 89:
Sheeps are people for whom speech recognition works exceptionally well, and goats are people for whom it works exceptionally poorly. Only the voice recognizer knows what separates them. People can't predict whose voice will be recognized easily and whose won't. The best policy is to design the interface so it can handle all kinds of voices in all kinds of environments
Maybe, it is planned to mark Android users as goats in the future to be able to configure the speech recognition engine for goats' needs. ;-)
All the data Git uses for information is stored in .git/
, so removing it should work just fine. Of course, make sure that your working copy is in the exact state that you want it, because everything else will be lost. .git
folder is hidden so make sure you turn on the Show hidden files, folders and disks
option.
From there, you can run git init
to create a fresh repository.
You can use a ResourceManager to load the image.
See the following link: http://www.java2s.com/Code/CSharp/Development-Class/Saveandloadimagefromresourcefile.htm
Important:
Read the note at the end.
Quick answer :
Use to_string()
. (available since c++11)
example :
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string pi = "pi is " + to_string(3.1415926);
cout<< "pi = "<< pi << endl;
return 0;
}
run it yourself : http://ideone.com/7ejfaU
These are available as well :
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Important Note:
As @Michael Konecný rightfully pointed out, using to_string()
is risky at best that is its very likely to cause unexpected results.
From http://en.cppreference.com/w/cpp/string/basic_string/to_string :
With floating point types
std::to_string
may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
The return value may differ significantly from whatstd::cout
prints by default, see the example.std::to_string
relies on the current locale for formatting purposes, and therefore concurrent calls tostd::to_string
from multiple threads may result in partial serialization of calls.C++17
providesstd::to_chars
as a higher-performance locale-independent alternative.
The best way would be to use stringstream
as others such as @dcp demonstrated in his answer.:
This issue is demonstrated in the following example :
run the example yourself : https://www.jdoodle.com/embed/v0/T4k
#include <iostream>
#include <sstream>
#include <string>
template < typename Type > std::string to_str (const Type & t)
{
std::ostringstream os;
os << t;
return os.str ();
}
int main ()
{
// more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
double f = 23.43;
double f2 = 1e-9;
double f3 = 1e40;
double f4 = 1e-40;
double f5 = 123456789;
std::string f_str = std::to_string (f);
std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
std::string f_str5 = std::to_string (f5);
std::cout << "std::cout: " << f << '\n'
<< "to_string: " << f_str << '\n'
<< "ostringstream: " << to_str (f) << "\n\n"
<< "std::cout: " << f2 << '\n'
<< "to_string: " << f_str2 << '\n'
<< "ostringstream: " << to_str (f2) << "\n\n"
<< "std::cout: " << f3 << '\n'
<< "to_string: " << f_str3 << '\n'
<< "ostringstream: " << to_str (f3) << "\n\n"
<< "std::cout: " << f4 << '\n'
<< "to_string: " << f_str4 << '\n'
<< "ostringstream: " << to_str (f4) << "\n\n"
<< "std::cout: " << f5 << '\n'
<< "to_string: " << f_str5 << '\n'
<< "ostringstream: " << to_str (f5) << '\n';
return 0;
}
output :
std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43
std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09
std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40
std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40
std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08
No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.
int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));
This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.
As posted above by blackjar, the below lines worked for me
pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx
You need to give all three --trusted-host options
. I was trying with only the first one after looking at the answers but it didn't work for me like that.
Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.
for individual values:
min(clamp_max, max(clamp_min, value))
for lists of values:
map(lambda x: min(clamp_max, max(clamp_min, x)), values)
You should check that what you are passing to foreach
is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.
For Maven, just include the following in your pom.xml
:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
For Gradle add the following snippet to your build.gradle
:
springBoot {
executable = true
}
The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d
or use a systemd
script.
init.d
example:
$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp
This allows you to start, stop and restart your application like:
$/etc/init.d/yourapp start|stop|restart
Or use a systemd
script:
[Unit]
Description=yourapp
After=syslog.target
[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
More information at the following links:
In Bash I prefer doing this as it addresses itself more as a conditional operation unlike using (( ))
which is more of arithmetic.
[[ N -gt M ]]
Unless I do complex stuffs like
(( (N + 1) > M ))
But everyone just has their own preferences. Sad thing is that some people impose their unofficial standards.
Update:
You actually can also do this:
[[ 'N + 1' -gt M ]]
Which allows you to add something else which you could do with [[ ]]
besides arithmetic stuff.
Running this approach will in fact toggle the checkbox; .isSelected()
in Java/Selenium 2 apparently always returns false
(at least with the Java, Selenium, and Firefox versions I tested it with).
The selection of the proper checkbox isn't where the problem lies -- rather, it is in distinguishing correctly the initial state to needlessly avoid reclicking an already-checked box.
At first I was stuck trying to figure out out to "insert" the Guest Additions CD image in Windows because I presumed it was a separate download that I would have to mount or somehow attach to the virtual CD drive. But just going through the Mac VirtualBox Devices menu and picking "Insert Guest Additions CD Image..." seemed to do the trick. Nothing to mount, nothing to "insert".
Elsewhere I found that the Guest Additions update was part of the update package, so I guess the new VB found the new GA CD automatically when Windows went looking. I wish I had known that to start.
Also, it appears that when I installed the Guest Additions on my Linked Base machine, it propagated to the other machines that were based on it. Sweet. Only one installation for multiple "machines".
I still haven't found that documented, but it appears to be the case (probably I'm not looking for the right explanation terms because I don't already know the explanation). How that works should probably be a different thread.
When we return a value from Stored procedure without select statement. We need to use "ParameterDirection.ReturnValue" and "ExecuteScalar" command to get the value.
CREATE PROCEDURE IsEmailExists
@Email NVARCHAR(20)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
IF EXISTS(SELECT Email FROM Users where Email = @Email)
BEGIN
RETURN 0
END
ELSE
BEGIN
RETURN 1
END
END
in C#
GetOutputParaByCommand("IsEmailExists")
public int GetOutputParaByCommand(string Command)
{
object identity = 0;
try
{
mobj_SqlCommand.CommandText = Command;
SqlParameter SQP = new SqlParameter("returnVal", SqlDbType.Int);
SQP.Direction = ParameterDirection.ReturnValue;
mobj_SqlCommand.Parameters.Add(SQP);
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlCommand.ExecuteScalar();
identity = Convert.ToInt32(SQP.Value);
CloseConnection();
}
catch (Exception ex)
{
CloseConnection();
}
return Convert.ToInt32(identity);
}
We get the returned value of SP "IsEmailExists" using above c# function.
This code will also work fine.
class Thread1 implements Runnable {
private static boolean evenFlag = true;
public synchronized void run() {
if (evenFlag == true) {
printEven();
} else {
printOdd();
}
}
public void printEven() {
for (int i = 0; i <= 10; i += 2) {
System.out.println(i+""+Thread.currentThread());
}
evenFlag = false;
}
public void printOdd() {
for (int i = 1; i <= 11; i += 2) {
System.out.println(i+""+Thread.currentThread());
}
evenFlag = true;
}
}
public class OddEvenDemo {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread td1 = new Thread(t1);
Thread td2 = new Thread(t1);
td1.start();
td2.start();
}
}
With python or pandas when you use read_csv
or pd.read_csv
, both of them look into current working directory, by default where the python process have started. So you need to use os
module to chdir()
and take it from there.
import pandas as pd
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())
The reason is that one construct:
var a = []; // Create a new empty array._x000D_
a[5] = 5; // Perfectly legal JavaScript that resizes the array._x000D_
_x000D_
for (var i = 0; i < a.length; i++) {_x000D_
// Iterate over numeric indexes from 0 to 5, as everyone expects._x000D_
console.log(a[i]);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
undefined_x000D_
undefined_x000D_
undefined_x000D_
undefined_x000D_
undefined_x000D_
5_x000D_
*/
_x000D_
can sometimes be totally different from the other:
var a = [];_x000D_
a[5] = 5;_x000D_
for (var x in a) {_x000D_
// Shows only the explicitly set index of "5", and ignores 0-4_x000D_
console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
5_x000D_
*/
_x000D_
Also consider that JavaScript libraries might do things like this, which will affect any array you create:
// Somewhere deep in your JavaScript library..._x000D_
Array.prototype.foo = 1;_x000D_
_x000D_
// Now you have no idea what the below code will do._x000D_
var a = [1, 2, 3, 4, 5];_x000D_
for (var x in a){_x000D_
// Now foo is a part of EVERY array and _x000D_
// will show up here as a value of 'x'._x000D_
console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
0_x000D_
1_x000D_
2_x000D_
3_x000D_
4_x000D_
foo_x000D_
*/
_x000D_
This answer is to iterate over selected columns as well as all columns in a DF.
df.columns
gives a list containing all the columns' names in the DF. Now that isn't very helpful if you want to iterate over all the columns. But it comes in handy when you want to iterate over columns of your choosing only.
We can use Python's list slicing easily to slice df.columns according to our needs. For eg, to iterate over all columns but the first one, we can do:
for column in df.columns[1:]:
print(df[column])
Similarly to iterate over all the columns in reversed order, we can do:
for column in df.columns[::-1]:
print(df[column])
We can iterate over all the columns in a lot of cool ways using this technique. Also remember that you can get the indices of all columns easily using:
for ind, column in enumerate(df.columns):
print(ind, column)
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
margin:auto;
text-align, if this won't work - try adding display:block;
and set there width:200px;
(in case your TD is too small).
Below is an example for Angular 6
deleteAccount(email) {
const header: HttpHeaders = new HttpHeaders()
.append('Content-Type', 'application/json; charset=UTF-8')
.append('Authorization', 'Bearer ' + sessionStorage.getItem('accessToken'));
const httpOptions = {
headers: header,
body: { Email: email }
};
return this.http.delete<any>(AppSettings.API_ENDPOINT + '/api/Account/DeleteAccount', httpOptions);
}
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.
The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.
The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type
5.66%
into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.
cp -r ./SourceFolder ./DestFolder
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
try it
n.pause();
n.currentTime = 0;
var nopromise = {
catch : new Function()
};
(n.play() || nopromise).catch(function(){}); ;
The solution that work for me is the following:
Putting the comment of EaterOfCode here as an answer.
grep itself also has the -c flag which just returns the count
So the command and output could look like this.
$ grep -Rl "curl" ./ -c
24
EDIT:
Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc
). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l
is much more useful as you can use it with other programs than grep
as well.
The problem with scrolling and text wrapping is that this code is assuming that both the width and the height are set to wrap_content
. However, the LayoutManager
needs to know that the horizontal width is constrained. So instead of creating your own widthSpec
for each child view, just use the original widthSpec
:
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(widthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
Something like this should work:
sh -c 'cd /tmp && exec pwd'
Remove the comma?
select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish'
and a.xyz = b.xyz
Have a look at FROM
SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name
You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:
```diff
+ this text is highlighted in green
- this text is highlighted in red
```
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
Control size and maintain proportion :
#your-img {
height: auto;
width: auto;
max-width: 300px;
max-height: 300px;
}
SimpleDateFormat
stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.
Looking at the source code reveals that there is a Calendar
instance field, which is used by operations on DateFormat
/ SimpleDateFormat
.
For example parse(..)
calls calendar.clear()
initially and then calendar.add(..)
. If another thread invokes parse(..)
before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.
One way to reuse date formats without trading thread-safety is to put them in a ThreadLocal
- some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.
To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use joda-time DateTimeFormat
which is threadsafe.
I would think that your first question is simply a matter of scope. The ServletContext is a much more broad scoped object (the whole servlet context) than a ServletRequest, which is simply a single request. You might look to the Servlet specification itself for more detailed information.
As to how, I am sorry but I will have to leave that for others to answer at this time.
Below script can be a good solution.Worked in large data as well.
ALTER DATABASE WMlive SET RECOVERY SIMPLE WITH NO_WAIT
ALTER TABLE WMBOMTABLE DROP CONSTRAINT PK_WMBomTable
ALTER TABLE WMBOMTABLE drop column BOMID
ALTER TABLE WMBOMTABLE ADD BomID int IDENTITY(1, 1) NOT NULL;
ALTER TABLE WMBOMTABLE ADD CONSTRAINT PK_WMBomTable PRIMARY KEY CLUSTERED (BomID);
ALTER DATABASE WMlive SET RECOVERY FULL WITH NO_WAIT
Calling a Controller from another Controller is not recommended, however if for any reason you have to do it, you can do this:
Laravel 5 compatible method
return \App::call('bla\bla\ControllerName@functionName');
Note: this will not update the URL of the page.
It's better to call the Route instead and let it call the controller.
return \Redirect::route('route-name-here');
If it's a string that you trust meaning that you have checked it before hand then the following would also work.
$date = new DateTime('2015-03-27');
It is not the answer you probably want, but why hide what you're trying to make public?
This provides you with the possibility of adding conditions on the rows and then change all the cells of a specific column corresponding to those rows:
df.loc[(df['issueid'] == '001'), 'industry'] = str('yyy')
In SQL, you escape a quote by another quote:
SELECT 'Alex''s Tea Factory' FROM DUAL
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
In my case the only way to delete was by using all possibilities because my code was supposed to run either by cmd.exe or powershell.exe. If it is your case, just create a function with this code and you will be fine:
#!/usr/bin/env python3
import shutil
from os import path, system
import sys
# Try to delete the folder ---------------------------------------------
if (path.isdir(folder)):
shutil.rmtree(folder, ignore_errors=True)
if (path.isdir(folder)):
try:
system("rd -r {0}".format(folder))
except Exception as e:
print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)
if (path.isdir(self.backup_folder_wrk)):
try:
system("rd /s /q {0}".format(folder))
except Exception as e:
print("WARN: Failed to delete => {0}".format(e),file=sys.stderr)
if (path.isdir(folder)):
print("WARN: Failed to delete {0}".format(folder),file=sys.stderr)
# -------------------------------------------------------------------------------------
I just created this js function using the jQuery size function http://api.jquery.com/size/
function classCount(name){
alert($('.'+name).size())
}
It alerts out the number of times the class name occurs in the document.
If you can change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
Arrays.sort(myArray);
int max = myArray[myArray.length - 1];
If you can't change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > max) {
max = myArray[i];
}
}
public static void duplicatesInteger(int arr[]){
Arrays.sort(arr);
int count=0;
Set s=new HashSet();
for(int i=0;i<=arr.length-1;i++){
for(int j=i+1;j<=arr.length-1;j++){
if(arr[i]==arr[j] && s.add(arr[i])){
count=count+1;
}
}
System.out.println(count);
}
}
I don't know of a command to do this, but you could do it in VBScript or something similar. Somthing like:
sNewName = "put new name here"
Set oShell = CreateObject ("WSCript.shell" )
sCCS = "HKLM\SYSTEM\CurrentControlSet\"
sTcpipParamsRegPath = sCCS & "Services\Tcpip\Parameters\"
sCompNameRegPath = sCCS & "Control\ComputerName\"
With oShell
.RegDelete sTcpipParamsRegPath & "Hostname"
.RegDelete sTcpipParamsRegPath & "NV Hostname"
.RegWrite sCompNameRegPath & "ComputerName\ComputerName", sNewName
.RegWrite sCompNameRegPath & "ActiveComputerName\ComputerName", sNewName
.RegWrite sTcpipParamsRegPath & "Hostname", sNewName
.RegWrite sTcpipParamsRegPath & "NV Hostname", sNewName
End With ' oShell
MsgBox "Computer name changed, please reboot your computer"
FORMAT()
is slower than CONVERT()
. This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.
112 = yyyymmdd - no format change needed
108 = hh:mm:ss - remove :
SELECT CONVERT(VARCHAR, GETDATE(), 112) +
REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')
It seems more logical to check typeof
instead of undefined
? I assume you expect a number as you set the var to 0
when undefined:
var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;
In this case if getVariable
is not a number (string, object, whatever), setVariable is set to 0
C#
string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, @"..\..\"));
This worked in my case: Use %USERPROFILE% instead of giving path .keystore file stored in this path automatically C:Users/user name/.android:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
To check a remote SSH server prior to the first connection, you can give a look at www.server-stats.net/ssh/ to see all SHH keys for the server, as well as from when the key is known.
That's not like an SSL certificate, but definitely a must-do before connecting to any SSH server for the first time.
The environment variables displayed in Jenkins (Manage Jenkins -> System information) are inherited from the system (i.e. inherited environment variables)
If you run env
command in a shell you should see the same environment variables as Jenkins shows.
These variables are either set by the shell/system or by you in ~/.bashrc
, ~/.bash_profile
.
There are also environment variables set by Jenkins when a job executes, but these are not displayed in the System Information.
When using JUnit asserts, I always make the message nice and clear. It saves huge amounts of time debugging. Doing it this way avoids having to add a added dependency on hamcrest Matchers.
previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";
Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);
assertTrue("Previous (" + prev + ") should be greater than current (" + curr + ")", prev > curr);
// This is for normal triangle
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
// This is for left triangle, just removed space before printing *
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
Create an object holding following properties with an appropriate name.
and use this as a value in your map.
Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).
Try using String.format()
:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(String.format("%s",x));
I just changed 2 parameters:
.wrap {
display: block;
width:661px;
}
This script:
import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(1, 10):
ip="192.168.0.{0}".format(n)
result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip, "inactive"
else:
print ip, "active"
will produce something like this output:
192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive
You can capture the output if you replace limbo
with subprocess.PIPE
and use communicate()
on the Popen
object:
p=Popen( ... )
output=p.communicate()
result=p.wait()
This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:
The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.
Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data
, segment
, packet
, frame
and bit
. And the term PDU (Protocol Data Unit
) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.
When we come to your question, we can call all of them by using the general term PDU
, but if you want to call them specifically at a given layer:
Here is a diagram, since a picture is worth a thousand words:
open terminal(or cmd for window), then run following commands: (On window, drop "source" in the second line.)
conda create -n py35 python=3.5
source activate py35
conda install notebook ipykernel
ipython kernel install --user --name=python3.5
I tried some method but It doesnt work, then I found this way. It worked with me. Hoping it can help.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
" error: command 'gcc' failed with exit status 1 ". the installation failed because of missing python-devel and some dependencies.
the best way to correct gcc problem:
You need to reinstall gcc , gcc-c++ and dependencies.
For python 2.7
$ sudo yum -y install gcc gcc-c++ kernel-devel
$ sudo yum -y install python-devel libxslt-devel libffi-devel openssl-devel
$ pip install "your python packet"
For python 3.4
$ sudo apt-get install python3-dev
$ pip install "your python packet"
Hope this will help.
The error message says it all. At runtime, the type is gone, there is no way to check for it.
You could catch it by making a factory for your object like this:
public static <T> MyObject<T> createMyObject(Class<T> type) {
return new MyObject<T>(type);
}
And then in the object's constructor store that type, so variable so that your method could look like this:
if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
{
return -1;
}
Yes you can run keras models on GPU. Few things you will have to check first.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
for TF > v2.0
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
(Thanks @nbro and @Ferro for pointing this out in the comments)
OR
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
output will be something like this:
[
name: "/cpu:0"device_type: "CPU",
name: "/gpu:0"device_type: "GPU"
]
Once all this is done your model will run on GPU:
To Check if keras(>=2.1.1) is using GPU:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
All the best.
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer
serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.
double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.
Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.
Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.
Sources:
http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers
You can use indexOf
But not working well in the last version of internet explorer.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
I suggest you use the following code:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
Connection refused means that the port you are trying to connect to is not actually open.
So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.
A common mistake is not specifying the port number when binding or connecting in network byte order...
Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.
1.in my htaccess file that lives in my wp-content folder i add this below what's already there
<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>
In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.
2.) In my ajax code i can then use my url like this
$.ajax({
url:'/wp-content/themes/themeName/forms.php',
data:({
someVar: someValue
}),
type: 'POST'
});
obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.
Hope it helps someone on earth. In my case jQuery and $ were available but not when the plugin bootstrapped so I wrapped everything inside a setTimeout. Wrapping inside setTimeout helped me fix the error:
setTimeout(() => {
/** Your code goes here */
!function(t, e) {
}(window);
})
If you have php 5.3+, you can use an anonymous function like so:
add_filter( 'login_redirect', function() { return site_url('news'); } );
To use shorthand to get the direction:
int direction = column == 0
? 0
: (column == _gridSize - 1 ? 1 : rand.Next(2));
To simplify the code entirely:
if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}
var token = string.Empty;
if (Request.Headers.TryGetValue("MyKey", out headerValues))
{
token = headerValues.FirstOrDefault();
}
I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!
Move the queue to self instead of as an argument to your functions package
and send
I just encountered this problem. I tried a few things, but settled on using JSoup. The jar is about 132k, which is a bit big, but if you download the source and take out some of the methods you will not be using, then it is not as big.
=> Good thing about it is that it will handle badly formed HTML
Here's a good example from their site.
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
//http://jsoup.org/cookbook/input/load-document-from-url
//Document doc = Jsoup.connect("http://example.com/").get();
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
With fetch, we need to deal with two promises. With axios, we can directly access the JSON result inside the response object data property.
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.et);
EditText et_city = (EditText) findViewById(R.id.et_city);
// Set the default text of second EditText widget
et_city.setText("USA");
}
}
It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char*
could indicate an array of char
s, a char**
could indicate that it points to and array of char*
s.
At some point, isn't it easier(or just as easy) to use a forEach
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
var reduced = []_x000D_
options.forEach(function(option) {_x000D_
if (option.assigned) {_x000D_
var someNewValue = { name: option.name, newProperty: 'Foo' }_x000D_
reduced.push(someNewValue);_x000D_
}_x000D_
});_x000D_
_x000D_
document.getElementById('output').innerHTML = JSON.stringify(reduced);
_x000D_
<h1>Only assigned options</h1>_x000D_
<pre id="output"> </pre>
_x000D_
However it would be nice if there was a malter()
or fap()
function that combines the map
and filter
functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.
A very simple answer if you say you don't care which address is used.
SELECT
CName, MIN(AddressLine)
FROM
MyTable
GROUP BY
CName
If you want the first according to, say, an "inserted" column then it's a different query
SELECT
M.CName, M.AddressLine,
FROM
(
SELECT
CName, MIN(Inserted) AS First
FROM
MyTable
GROUP BY
CName
) foo
JOIN
MyTable M ON foo.CName = M.CName AND foo.First = M.Inserted
Simple socket server app example
I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.
This example app runs a server that returns a ROT-1 cypher of the input.
You would then need to add an Exit
button + some sleep delays, but this should get you started.
To play with it:
netcat $PHONE_IP 12345
Android sockets are the same as Java's, except we have to deal with some permission issues.
src/com/cirosantilli/android_cheat/socket/Main.java
package com.cirosantilli.android_cheat.socket;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Activity {
static final String TAG = "AndroidCheatSocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Main.TAG, "onCreate");
Main.this.startService(new Intent(Main.this, MyService.class));
}
public static class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Main.TAG, "onHandleIntent");
final int port = 12345;
ServerSocket listener = null;
try {
listener = new ServerSocket(port);
Log.d(Main.TAG, String.format("listening on port = %d", port));
while (true) {
Log.d(Main.TAG, "waiting for client");
Socket socket = listener.accept();
Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
for (String inputLine; (inputLine = in.readLine()) != null;) {
Log.d(Main.TAG, "received");
Log.d(Main.TAG, inputLine);
StringBuilder outputStringBuilder = new StringBuilder("");
char inputLineChars[] = inputLine.toCharArray();
for (char c : inputLineChars)
outputStringBuilder.append(Character.toChars(c + 1));
out.println(outputStringBuilder);
}
}
} catch(IOException e) {
Log.d(Main.TAG, e.toString());
}
}
}
}
We need a Service
or other background method or else: How do I fix android.os.NetworkOnMainThreadException?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cirosantilli.android_cheat.socket"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="AndroidCheatsocket">
<activity android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Main$MyService" />
</application>
</manifest>
We must add: <uses-permission android:name="android.permission.INTERNET" />
or else: Java socket IOException - permission denied
On GitHub with a build.xml
: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket
In Spring boot: 2.1.6, you can use like below:
@GetMapping("/orders")
@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
@RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.
I will try to show it as simple as i can:
DECLARE FULL SCREEN ACTIVITY IN ANDROID MAINIFEST file:
<activity
android:name=".GameActivity"
android:label="@string/title_activity_game"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
Now in Android studio (if you using it) open your Activity xml file ( in my example activity_game.xml) in designer and select theme (above mobile phone in designer click button with small circle) and then select Mainfest Themes on the left side and then NoTitleBar.Fullscreen.
Hope it will help!
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
If you want to set image as background for whole page, use this:
body
{
background-image: url('Image URL');
}
I think if you think it from the point of CALayer
, everything is more clear.
Frame is not really a distinct property of the view or layer at all, it is a virtual property, computed from the bounds, position(UIView
's center), and transform.
So basically how the layer/view layouts is really decided by these three property(and anchorPoint), and either of these three property won't change any other property, like changing transform doesn't change bounds.
Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:
int x = 13;
int y = 4;
float x = (float)y / (float)z;
or, if you are using literals:
float x = 13f / 4f;
Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
Consider the signal()
function from the C standard:
extern void (*signal(int, void(*)(int)))(int);
Perfectly obscurely obvious - it's a function that takes two arguments, an integer and a pointer to a function that takes an integer as an argument and returns nothing, and it (signal()
) returns a pointer to a function that takes an integer as an argument and returns nothing.
If you write:
typedef void (*SignalHandler)(int signum);
then you can instead declare signal()
as:
extern SignalHandler signal(int signum, SignalHandler handler);
This means the same thing, but is usually regarded as somewhat easier to read. It is clearer that the function takes an int
and a SignalHandler
and returns a SignalHandler
.
It takes a bit of getting used to, though. The one thing you can't do, though is write a signal handler function using the SignalHandler
typedef
in the function definition.
I'm still of the old-school that prefers to invoke a function pointer as:
(*functionpointer)(arg1, arg2, ...);
Modern syntax uses just:
functionpointer(arg1, arg2, ...);
I can see why that works - I just prefer to know that I need to look for where the variable is initialized rather than for a function called functionpointer
.
Sam commented:
I have seen this explanation before. And then, as is the case now, I think what I didn't get was the connection between the two statements:
extern void (*signal(int, void()(int)))(int); /*and*/ typedef void (*SignalHandler)(int signum); extern SignalHandler signal(int signum, SignalHandler handler);
Or, what I want to ask is, what is the underlying concept that one can use to come up with the second version you have? What is the fundamental that connects "SignalHandler" and the first typedef? I think what needs to be explained here is what is typedef is actually doing here.
Let's try again. The first of these is lifted straight from the C standard - I retyped it, and checked that I had the parentheses right (not until I corrected it - it is a tough cookie to remember).
First of all, remember that typedef
introduces an alias for a type. So, the alias is SignalHandler
, and its type is:
a pointer to a function that takes an integer as an argument and returns nothing.
The 'returns nothing' part is spelled void
; the argument that is an integer is (I trust) self-explanatory. The following notation is simply (or not) how C spells pointer to function taking arguments as specified and returning the given type:
type (*function)(argtypes);
After creating the signal handler type, I can use it to declare variables and so on. For example:
static void alarm_catcher(int signum)
{
fprintf(stderr, "%s() called (%d)\n", __func__, signum);
}
static void signal_catcher(int signum)
{
fprintf(stderr, "%s() called (%d) - exiting\n", __func__, signum);
exit(1);
}
static struct Handlers
{
int signum;
SignalHandler handler;
} handler[] =
{
{ SIGALRM, alarm_catcher },
{ SIGINT, signal_catcher },
{ SIGQUIT, signal_catcher },
};
int main(void)
{
size_t num_handlers = sizeof(handler) / sizeof(handler[0]);
size_t i;
for (i = 0; i < num_handlers; i++)
{
SignalHandler old_handler = signal(handler[i].signum, SIG_IGN);
if (old_handler != SIG_IGN)
old_handler = signal(handler[i].signum, handler[i].handler);
assert(old_handler == SIG_IGN);
}
...continue with ordinary processing...
return(EXIT_SUCCESS);
}
Please note How to avoid using printf()
in a signal handler?
So, what have we done here - apart from omit 4 standard headers that would be needed to make the code compile cleanly?
The first two functions are functions that take a single integer and return nothing. One of them actually doesn't return at all thanks to the exit(1);
but the other does return after printing a message. Be aware that the C standard does not permit you to do very much inside a signal handler; POSIX is a bit more generous in what is allowed, but officially does not sanction calling fprintf()
. I also print out the signal number that was received. In the alarm_handler()
function, the value will always be SIGALRM
as that is the only signal that it is a handler for, but signal_handler()
might get SIGINT
or SIGQUIT
as the signal number because the same function is used for both.
Then I create an array of structures, where each element identifies a signal number and the handler to be installed for that signal. I've chosen to worry about 3 signals; I'd often worry about SIGHUP
, SIGPIPE
and SIGTERM
too and about whether they are defined (#ifdef
conditional compilation), but that just complicates things. I'd also probably use POSIX sigaction()
instead of signal()
, but that is another issue; let's stick with what we started with.
The main()
function iterates over the list of handlers to be installed. For each handler, it first calls signal()
to find out whether the process is currently ignoring the signal, and while doing so, installs SIG_IGN
as the handler, which ensures that the signal stays ignored. If the signal was not previously being ignored, it then calls signal()
again, this time to install the preferred signal handler. (The other value is presumably SIG_DFL
, the default signal handler for the signal.) Because the first call to 'signal()' set the handler to SIG_IGN
and signal()
returns the previous error handler, the value of old
after the if
statement must be SIG_IGN
- hence the assertion. (Well, it could be SIG_ERR
if something went dramatically wrong - but then I'd learn about that from the assert firing.)
The program then does its stuff and exits normally.
Note that the name of a function can be regarded as a pointer to a function of the appropriate type. When you do not apply the function-call parentheses - as in the initializers, for example - the function name becomes a function pointer. This is also why it is reasonable to invoke functions via the pointertofunction(arg1, arg2)
notation; when you see alarm_handler(1)
, you can consider that alarm_handler
is a pointer to the function and therefore alarm_handler(1)
is an invocation of a function via a function pointer.
So, thus far, I've shown that a SignalHandler
variable is relatively straight-forward to use, as long as you have some of the right type of value to assign to it - which is what the two signal handler functions provide.
Now we get back to the question - how do the two declarations for signal()
relate to each other.
Let's review the second declaration:
extern SignalHandler signal(int signum, SignalHandler handler);
If we changed the function name and the type like this:
extern double function(int num1, double num2);
you would have no problem interpreting this as a function that takes an int
and a double
as arguments and returns a double
value (would you? maybe you'd better not 'fess up if that is problematic - but maybe you should be cautious about asking questions as hard as this one if it is a problem).
Now, instead of being a double
, the signal()
function takes a SignalHandler
as its second argument, and it returns one as its result.
The mechanics by which that can also be treated as:
extern void (*signal(int signum, void(*handler)(int signum)))(int signum);
are tricky to explain - so I'll probably screw it up. This time I've given the parameters names - though the names aren't critical.
In general, in C, the declaration mechanism is such that if you write:
type var;
then when you write var
it represents a value of the given type
. For example:
int i; // i is an int
int *ip; // *ip is an int, so ip is a pointer to an integer
int abs(int val); // abs(-1) is an int, so abs is a (pointer to a)
// function returning an int and taking an int argument
In the standard, typedef
is treated as a storage class in the grammar, rather like static
and extern
are storage classes.
typedef void (*SignalHandler)(int signum);
means that when you see a variable of type SignalHandler
(say alarm_handler) invoked as:
(*alarm_handler)(-1);
the result has type void
- there is no result. And (*alarm_handler)(-1);
is an invocation of alarm_handler()
with argument -1
.
So, if we declared:
extern SignalHandler alt_signal(void);
it means that:
(*alt_signal)();
represents a void value. And therefore:
extern void (*alt_signal(void))(int signum);
is equivalent. Now, signal()
is more complex because it not only returns a SignalHandler
, it also accepts both an int and a SignalHandler
as arguments:
extern void (*signal(int signum, SignalHandler handler))(int signum);
extern void (*signal(int signum, void (*handler)(int signum)))(int signum);
If that still confuses you, I'm not sure how to help - it is still at some levels mysterious to me, but I've grown used to how it works and can therefore tell you that if you stick with it for another 25 years or so, it will become second nature to you (and maybe even a bit quicker if you are clever).
Here is some code that works for me:
public class MainActivity extends AppCompatActivity {
public static String storeLang;
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences shp = PreferenceManager.getDefaultSharedPreferences(this);
storeLang = shp.getString(getString(R.string.key_lang), "");
// Create a new Locale object
Locale locale = new Locale(storeLang);
// Create a new configuration object
Configuration config = new Configuration();
// Set the locale of the new configuration
config.locale = locale;
// Update the configuration of the Accplication context
getResources().updateConfiguration(
config,
getResources().getDisplayMetrics()
);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Source: here
var timeArr = moment().format('x');
returns the Unix Millisecond Timestamp as per the format() documentation.
Instead of modifying the global profile
you could create the .bash_profile
in your default $HOME
directory (e.g. C:\Users\WhateverUser\.bash_profile
) with the following contents:
export HOME="C:\my\projects\dir"
cd "$HOME" # if you'd like it to be the starting dir of the git shell
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
Here is a method you can use:
public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
{
foreach (var key in dictionary.Where(
kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
Select(x => x.Key).ToArray())
dictionary.Remove(key);
}
If you are running python 3 then you need to change the print statements to print functions, i.e. put things in brackets () after print statements.
The only thing that you will see the above do is the prints unless you have something listening on 127.0.0.1 port 5005
as you are sending a packet not receiving it - so you need to implement and start the other part of the example in another console window first so it is waiting for the message.
iOS users also expect autocapitalization: In a standard text field, the first letter of a sentence in a case-sensitive language is automatically capitalized.
You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed, so providing them is a competitive advantage.
Apple document is saying there is no API available for this feature and some other expected feature in a customkeyboard. so you need to find out your own logic to implement this.