It would be easier using stringstreams:
#include <sstream>
int x = 42; // The integer
string str; // The string
ostringstream temp; // 'temp' as in temporary
temp << x;
str = temp.str(); // str is 'temp' as string
Or make a function:
#include <sstream>
string IntToString(int a)
{
ostringstream temp;
temp << a;
return temp.str();
}
In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:
#include <string>
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("filename.txt");
std::string line;
while( std::getline( input, line ) ) {
std::cout<<line<<'\n';
}
return 0;
}
This program reads each line from a file and echos it to the console.
For C you're probably looking at using fgets
, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:
#include <stdio.h>
int main() {
char line[1024];
FILE *fp = fopen("filename.txt","r");
//Checks if file is empty
if( fp == NULL ) {
return 1;
}
while( fgets(line,1024,fp) ) {
printf("%s\n",line);
}
return 0;
}
With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.
for the entire line
^(\w+)\s+(\w+)\s+(\d+(?:\/\d+){2})\s+(\w+)$
This is a simpler version
import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`
If you have bash (e.g. git bash), you can use the following script to convert from unix2dos:
ex filename.ext <<EOF
:set fileformat=dos
:wq
EOF
similarly, to convert from dos2unix:
ex filename.ext <<EOF
:set fileformat=unix
:wq
EOF
column-span: all; /* W3C */
-webkit-column-span: all; /* Safari & Chrome */
-moz-column-span: all; /* Firefox */
-ms-column-span: all; /* Internet Explorer */
-o-column-span: all; /* Opera */
http://www.quackit.com/css/css3/properties/css_column-span.cfm
The HTML attribute for the purpose is rules=none
(to be inserted into the table
tag).
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
var type={
format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);
To make the scripts compatible with Python2 and 3 i use :
from sys import version_info
if version_info[0] < 3:
from __future__ import print_function
Writing an updated answer since most of the already present answers are obsolete as of now.
Versions earlier than Docker 19.03
used to require nvidia-docker2
and the --runtime=nvidia
flag.
Since Docker 19.03
, you need to install nvidia-container-toolkit
package and then use the --gpus all
flag.
So, here are the basics,
Package Installation
Install the nvidia-container-toolkit
package as per official documentation at Github.
For Redhat based OSes, execute the following set of commands:
$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo
$ sudo yum install -y nvidia-container-toolkit
$ sudo systemctl restart docker
For Debian based OSes, execute the following set of commands:
# Add the package repositories
$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
$ sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit
$ sudo systemctl restart docker
Running the docker with GPU support
docker run --name my_all_gpu_container --gpus all -t nvidia/cuda
Please note, the flag --gpus all
is used to assign all available gpus to the docker container.
To assign specific gpu to the docker container (in case of multiple GPUs available in your machine)
docker run --name my_first_gpu_container --gpus device=0 nvidia/cuda
Or
docker run --name my_first_gpu_container --gpus '"device=0"' nvidia/cuda
Think about protected internal
as applying two access modifier (protected
, and internal
) on the same field, property or method.
In the real world, imagine we are issuing privilege for people to visit museum:
- Everyone inside the city are allowed to visit museum (internal).
- Everyone outside of the city that their parents live here are allowed to visit museum (protected).
And we can put them together in these way:
Everyone inside the city (internal) and everyone outside of city that their parents live here (protected) are allowed to visit the museum (protected internal).
Programming world:
internal: The field is available everywhere in the assembly (project). It is like saying it is public
in its project scope (but can not being accessed outside of project scope even by those classes outside of assembly which inherit from that class). Every instance of that type can see it in that assembly (project scope).
protected: simply means that all derived classes can see it (inside or outside of assembly). For example derived classes can see the field or method inside its methods and constructors using: base.NameOfProtectedInternal
.
So, putting these two access modifier together (protected internal
), you have something that can being public inside the project, and can be seen by those which have inherited from that class inside their scope.
They can be written in the
internal protected
, and does not change the meaning, but it is convenient to write itprotected internal
.
Make sure you have a .babelrc file that declares what Babel is supposed to be transpiling. I spent like 30 minutes trying to figure this exact error. After I copied a bunch of files over to a new folder and found out I didn't copy the .babelrc file because it was hidden.
{
"presets": "es2015"
}
or something along those lines is what you are looking for inside your .babelrc file
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
In your Apache .htaccess file:
#Create filter to match files you want to cache
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>
I wrote about it here also:
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/
you can add custom clear button and control the size and every thing using this:
UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[clearButton setImage:img forState:UIControlStateNormal];
[clearButton setFrame:frame];
[clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];
textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing
[textField setRightView:clearButton];
If you used ms build tools to install node the path is here:
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Microsoft\VisualStudio\NodeJs
Suppose
$row=mysql_fetch_row($rc)
and if you want to check if row[8] is null then do
$field=$row[8];
if($field)
echo "";
else
echo "";
Try
data.items.pop();
data.items.push({id: "7", name: "Matrix", type: "adult"});
var data = {items: [_x000D_
{id: "1", name: "Snatch", type: "crime"},_x000D_
{id: "2", name: "Witches of Eastwick", type: "comedy"},_x000D_
{id: "3", name: "X-Men", type: "action"},_x000D_
{id: "4", name: "Ordinary People", type: "drama"},_x000D_
{id: "5", name: "Billy Elliot", type: "drama"},_x000D_
{id: "6", name: "Toy Story", type: "children"}_x000D_
]};_x000D_
_x000D_
data.items.pop();_x000D_
data.items.push({id: "7", name: "Matrix", type: "adult"});_x000D_
_x000D_
console.log(data);
_x000D_
In my opinion errors have a reason to appear, that my sound stupid, but thats the way it is. Good programming only raises errors when you have to handle them. Also, as i read some time ago, "the pass-Statement is a Statement that Shows code will be inserted later", so if you want to have an empty except-statement feel free to do so, but for a good program there will be a part missing. because you dont handle the things you should have. Appearing exceptions give you the chance to correct input data or to change your data structure so these exceptions dont occur again (but in most cases (Network-exceptions, General input-exceptions) exceptions indicate that the next parts of the program wont execute well. For example a NetworkException can indicate a broken network-connection and the program cant send/recieve data in the next program steps.
But using a pass block for only one execption-block is valid, because you still differenciate beetween the types of exceptions, so if you put all exception-blocks in one, it is not empty:
try:
#code here
except Error1:
#exception handle1
except Error2:
#exception handle2
#and so on
can be rewritten that way:
try:
#code here
except BaseException as e:
if isinstance(e, Error1):
#exception handle1
elif isinstance(e, Error2):
#exception handle2
...
else:
raise
So even multiple except-blocks with pass-statements can result in code, whose structure handles special types of exceptions.
It can be done simply using the following code:
if index < len(my_list):
print(index, 'exists in the list')
else:
print(index, "doesn't exist in the list")
In my case I felt that "defaultChecked" was not working properly with states/conditions. So I used "checked" with "onChange" for toggling the state.
Eg.
checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}
I think you are right, it's just not possible with pure CSS as far as I know (not cross-browser I mean).
Edit:
Ok I didn't like my answer very much so I puzzled a little. I might have found an interesting idea which could help out.. maybe it IS possible after all (although not the prettiest thing ever):
Edit: Tested and working in Chrome, FF and IE 8&9. . It doesn't work in IE7.
html:
<div id="img_wrap">
<img id="original_img" src="http://upload.wikimedia.org/wikipedia/en/8/81/Mdna-standard-edition-cover.jpg"/>
<div id="rescaled_img_wrap">
<img id="rescaled_img" src="http://upload.wikimedia.org/wikipedia/en/8/81/Mdna-standard-edition-cover.jpg"/>
</div>
</div>
css:
#img_wrap {
display: inline-block;
position:relative;
}
#rescaled_img_wrap {
width: 50%;
}
#original_img {
display: none;
}
#rescaled_img {
width: 100%;
height: 100%;
}
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
I was recently reading more on difference between :joins
and :includes
in rails. Here is an explaination of what I understood (with examples :))
Consider this scenario:
A User has_many comments and a comment belongs_to a User.
The User model has the following attributes: Name(string), Age(integer). The Comment model has the following attributes:Content, user_id. For a comment a user_id can be null.
:joins performs a inner join between two tables. Thus
Comment.joins(:user)
#=> <ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">,
#<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,
#<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">]>
will fetch all records where user_id (of comments table) is equal to user.id (users table). Thus if you do
Comment.joins(:user).where("comments.user_id is null")
#=> <ActiveRecord::Relation []>
You will get a empty array as shown.
Moreover joins does not load the joined table in memory. Thus if you do
comment_1 = Comment.joins(:user).first
comment_1.user.age
#=>?[1m?[36mUser Load (0.0ms)?[0m ?[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1?[0m [["id", 1]]
#=> 24
As you see, comment_1.user.age
will fire a database query again in the background to get the results
:includes performs a left outer join between the two tables. Thus
Comment.includes(:user)
#=><ActiveRecord::Relation [#<Comment id: 1, content: "Hi I am Aaditi.This is my first comment!", user_id: 1, created_at: "2014-11-12 18:29:24", updated_at: "2014-11-12 18:29:24">,
#<Comment id: 2, content: "Hi I am Ankita.This is my first comment!", user_id: 2, created_at: "2014-11-12 18:29:29", updated_at: "2014-11-12 18:29:29">,
#<Comment id: 3, content: "Hi I am John.This is my first comment!", user_id: 3, created_at: "2014-11-12 18:30:25", updated_at: "2014-11-12 18:30:25">,
#<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>
will result in a joined table with all the records from comments table. Thus if you do
Comment.includes(:user).where("comment.user_id is null")
#=> #<ActiveRecord::Relation [#<Comment id: 4, content: "Hi This is an anonymous comment!", user_id: nil, created_at: "2014-11-12 18:31:02", updated_at: "2014-11-12 18:31:02">]>
it will fetch records where comments.user_id is nil as shown.
Moreover includes loads both the tables in the memory. Thus if you do
comment_1 = Comment.includes(:user).first
comment_1.user.age
#=> 24
As you can notice comment_1.user.age simply loads the result from memory without firing a database query in the background.
My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).
In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:
In short, you can create a GetElement function:
private XElement GetElement(XDocument doc,string elementName)
{
foreach (XNode node in doc.DescendantNodes())
{
if (node is XElement)
{
XElement element = (XElement)node;
if (element.Name.LocalName.Equals(elementName))
return element;
}
}
return null;
}
Which you can then call like this:
XElement element = GetElement(doc,"Band");
Note that this will return null if no matching element is found.
Just Restart the Eclipse will solve this Issue as the workspace will be freshly Build ! go to
File -> Restart
Its the easiest way to avoid frustration by going it into Build,properties,blah blah.....
Try moving the button styling to the TouchableHighlight
itself:
Styles:
submit:{
marginRight:40,
marginLeft:40,
marginTop:10,
paddingTop:20,
paddingBottom:20,
backgroundColor:'#68a0cf',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
submitText:{
color:'#fff',
textAlign:'center',
}
Button (same):
<TouchableHighlight
style={styles.submit}
onPress={() => this.submitSuggestion(this.props)}
underlayColor='#fff'>
<Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>
You can use an svn changelist to keep track of a set of files that you want to commit together.
The linked page goes into lots of details, but here's an executive summary example:
$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist
I often use a MS Word macro that takes a source-code file, formats it in two columns of monospaced type on a landscape page, numbers the lines, and adds company header and footer info such as filename, print date, page number, and confidentiality statement.
Printing both sides of the page uses about 1/4 the paper as the equivalent lpr
command. (Does anyone use lpr
anymore???)
What's your operating system? What version of R are you running: 32-bit or 64-bit? What version of Java do you have installed?
I had a similar error when I first started using the read.xlsx()
function and discovered that my issue (which may or may not be related to yours; at a minimum, this response should be viewed as "try this, too") was related to the incompatability of .xlsx pacakge with 64-bit Java. I'm fairly certain that the .xlsx package requires 32-bit Java.
Use 32-bit R and make sure that 32-bit Java is installed. This may address your issue.
Escape characters are dependent on whatever system is interpreting them. \n
is interpreted as a newline character by many programming languages, but that doesn't necessarily hold true for the other utilities you mention. Even if they do treat \n
as newline, there may be some other techniques to get them to behave how you want. You would have to consult their documentation (or see other answers here).
For DOS/Windows systems, the newline is actually two characters: Carriage Return (ASCII 13, AKA \r
), followed by Line Feed (ASCII 10). On Unix systems (including Mac OSX) it's just Line Feed. On older Macs it was a single Carriage Return.
This is worked for me
Taking Shiraz's idea and running with it...
In your application, are you explicitly defining a domain User Account and Password to access AD?
When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.
A VBScript example would be as follows:
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "MyDomain\MyAccount"
objConnection.Properties("Password") = "MyPassword"
objConnection.Open "Active Directory Provider"
If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.
You'll have to uninstall XAMPP 1.7.2 and install XAMPP 1.7.0, which contains PHP 5.2.8.
D:\Documents and Settings\box>php -v
PHP 5.2.8 (cli) (built: Dec 8 2008 19:31:23)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies
XAMPP 1.6.8 contains PHP 5.2.6.
D:\Documents and Settings\box>php -v
PHP 5.2.6 (cli) (built: May 2 2008 18:02:07)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies
on Debian 10
apt install php-mysql
/etc/init.d/apache2 restart
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
The mappedBy
attribute is referencing customer
while the property is mCustomer
, hence the error message. So either change your mapping into:
/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;
Or change the entity property into customer
(which is what I would do).
The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."
One needs to create a schema, and attach it to the Rdd.
Assuming val spark is a product of a SparkSession.builder...
import org.apache.spark._
import org.apache.spark.sql._
import org.apache.spark.sql.types._
/* Lets gin up some sample data:
* As RDD's and dataframes can have columns of differing types, lets make our
* sample data a three wide, two tall, rectangle of mixed types.
* A column of Strings, a column of Longs, and a column of Doubules
*/
val arrayOfArrayOfAnys = Array.ofDim[Any](2,3)
arrayOfArrayOfAnys(0)(0)="aString"
arrayOfArrayOfAnys(0)(1)=0L
arrayOfArrayOfAnys(0)(2)=3.14159
arrayOfArrayOfAnys(1)(0)="bString"
arrayOfArrayOfAnys(1)(1)=9876543210L
arrayOfArrayOfAnys(1)(2)=2.71828
/* The way to convert an anything which looks rectangular,
* (Array[Array[String]] or Array[Array[Any]] or Array[Row], ... ) into an RDD is to
* throw it into sparkContext.parallelize.
* http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.SparkContext shows
* the parallelize definition as
* def parallelize[T](seq: Seq[T], numSlices: Int = defaultParallelism)
* so in our case our ArrayOfArrayOfAnys is treated as a sequence of ArraysOfAnys.
* Will leave the numSlices as the defaultParallelism, as I have no particular cause to change it.
*/
val rddOfArrayOfArrayOfAnys=spark.sparkContext.parallelize(arrayOfArrayOfAnys)
/* We'll be using the sqlContext.createDataFrame to add a schema our RDD.
* The RDD which goes into createDataFrame is an RDD[Row] which is not what we happen to have.
* To convert anything one tall and several wide into a Row, one can use Row.fromSeq(thatThing.toSeq)
* As we have an RDD[somethingWeDontWant], we can map each of the RDD rows into the desired Row type.
*/
val rddOfRows=rddOfArrayOfArrayOfAnys.map(f=>
Row.fromSeq(f.toSeq)
)
/* Now to construct our schema. This needs to be a StructType of 1 StructField per column in our dataframe.
* https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.types.StructField shows the definition as
* case class StructField(name: String, dataType: DataType, nullable: Boolean = true, metadata: Metadata = Metadata.empty)
* Will leave the two default values in place for each of the columns:
* nullability as true,
* metadata as an empty Map[String,Any]
*
*/
val schema = StructType(
StructField("colOfStrings", StringType) ::
StructField("colOfLongs" , LongType ) ::
StructField("colOfDoubles", DoubleType) ::
Nil
)
val df=spark.sqlContext.createDataFrame(rddOfRows,schema)
/*
* +------------+----------+------------+
* |colOfStrings|colOfLongs|colOfDoubles|
* +------------+----------+------------+
* | aString| 0| 3.14159|
* | bString|9876543210| 2.71828|
* +------------+----------+------------+
*/
df.show
Same steps, but with fewer val declarations:
val arrayOfArrayOfAnys=Array(
Array("aString",0L ,3.14159),
Array("bString",9876543210L,2.71828)
)
val rddOfRows=spark.sparkContext.parallelize(arrayOfArrayOfAnys).map(f=>Row.fromSeq(f.toSeq))
/* If one knows the datatypes, for instance from JDBC queries as to RDBC column metadata:
* Consider constructing the schema from an Array[StructField]. This would allow looping over
* the columns, with a match statement applying the appropriate sql datatypes as the second
* StructField arguments.
*/
val sf=new Array[StructField](3)
sf(0)=StructField("colOfStrings",StringType)
sf(1)=StructField("colOfLongs" ,LongType )
sf(2)=StructField("colOfDoubles",DoubleType)
val df=spark.sqlContext.createDataFrame(rddOfRows,StructType(sf.toList))
df.show
If both Column are numeric Then Use This code
Just Cast Column As Varchar(Size)
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
Here is the example I use for all of my form email inputs. This example is ASP.NET, but applies to any:
<asp:TextBox runat="server" class="form-control" placeholder="Contact's email"
name="contact_email" ID="contact_email" title="Contact's email (format: [email protected])"
type="email" TextMode="Email" validate="required:true"
pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*" >
</asp:TextBox>
HTML5 still validates using the pattern when not required. Haven't found one yet that was a false positive.
This renders as the following HTML:
<input class="form-control" placeholder="Contact's email"
name="contact_email" id="contact_email" type="email"
title="Contact's email (format: [email protected])"
pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">
Use the CONCAT
function to avoid conversion errors:
DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = CONCAT(COALESCE(@StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID
You should define the attributes of option
like selected="selected"
<select>
<option selected="selected">a</option>
<option>b</option>
<option>c</option>
</select>
I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.
My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.
Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.
An importer tool has been implemented to help you to use CMake.
Edit:
Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/
I repaired it using the Microsoft .NET Framework Repair Tool. After reloading my project a couple of times after that the problem went away.
I had this same issue where I wanted to initialize my MySQL Docker instance's schema, but I ran into difficulty getting this working after doing some Googling and following others' examples. Here's how I solved it.
1) Dump your MySQL schema to a file.
mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_name> > schema.sql
2) Use the ADD command to add your schema file to the /docker-entrypoint-initdb.d
directory in the Docker container. The docker-entrypoint.sh
file will run any files in this directory ending with ".sql"
against the MySQL database.
Dockerfile:
FROM mysql:5.7.15
MAINTAINER me
ENV MYSQL_DATABASE=<schema_name> \
MYSQL_ROOT_PASSWORD=<password>
ADD schema.sql /docker-entrypoint-initdb.d
EXPOSE 3306
3) Start up the Docker MySQL instance.
docker-compose build
docker-compose up
Thanks to Setting up MySQL and importing dump within Dockerfile for clueing me in on the docker-entrypoint.sh and the fact that it runs both SQL and shell scripts!
Do you mean Delegate.Invoke
/BeginInvoke
or Control.Invoke
/BeginInvoke
?
Delegate.Invoke
: Executes synchronously, on the same thread.Delegate.BeginInvoke
: Executes asynchronously, on a threadpool
thread.Control.Invoke
: Executes on the UI thread, but calling thread waits for completion before continuing.Control.BeginInvoke
: Executes on the UI thread, and calling thread doesn't wait for completion.Tim's answer mentions when you might want to use BeginInvoke
- although it was mostly geared towards Delegate.BeginInvoke
, I suspect.
For Windows Forms apps, I would suggest that you should usually use BeginInvoke
. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person
with FirstName
and LastName
properties, and you did:
person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";
Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)
Unless you have this sort of issue, however, Control.BeginInvoke
is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke
in a "fire and forget" manner - i.e. without ever calling EndInvoke
. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.
Either
Method 2 by step
Relying on the "struct" module can cause problems with endian-ness and type sizes, and just isn't needed. Nor is socket.inet_aton(). Python works very well with dotted-quad IP addresses:
def ip_to_u32(ip):
return int(''.join('%02x' % int(d) for d in ip.split('.')), 16)
I need to do IP matching on each socket accept() call, against a whole set of allowable source networks, so I precompute masks and networks, as integers:
SNS_SOURCES = [
# US-EAST-1
'207.171.167.101',
'207.171.167.25',
'207.171.167.26',
'207.171.172.6',
'54.239.98.0/24',
'54.240.217.16/29',
'54.240.217.8/29',
'54.240.217.64/28',
'54.240.217.80/29',
'72.21.196.64/29',
'72.21.198.64/29',
'72.21.198.72',
'72.21.217.0/24',
]
def build_masks():
masks = [ ]
for cidr in SNS_SOURCES:
if '/' in cidr:
netstr, bits = cidr.split('/')
mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
net = ip_to_u32(netstr) & mask
else:
mask = 0xffffffff
net = ip_to_u32(cidr)
masks.append((mask, net))
return masks
Then I can quickly see if a given IP is within one of those networks:
ip = ip_to_u32(ipstr)
for mask, net in cached_masks:
if ip & mask == net:
# matched!
break
else:
raise BadClientIP(ipstr)
No module imports needed, and the code is very fast at matching.
Mac already has Python and a package manager called easy_install
, so open Terminal and type
sudo easy_install selenium
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
Also you can use f-string formatting to write integer to file
For appending use following code, for writing once replace 'a' with 'w'.
for i in s_list:
with open('path_to_file','a') as file:
file.write(f'{i}\n')
file.close()
Bootstrap col slightly use some spaces both left and right. I have just added a block element like div and set border for the differences. also adding some extra padding or margin in that extra div will work perfectly..
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<br><br>
<div class="container">
<div class="row">
<div class="col-6 ">
<div class="border border-danger ">
<h2 class="text-center">1</h2>
</div>
</div>
<div class="col-6">
<div class="border border-warning">
<h2 class="text-center">2</h2>
</div>
</div>
</div>
</div>
_x000D_
If anyone is struggling with angular version 4+ (mine was 4.3.6). This was the sample code which worked for me.
First add the required imports
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
Then for the api function. It's a login sample which can be changed as per your needs.
login(username: string, password: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('email', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
return this.http.post('http://localhost:3000/api/v1/login', body, {headers: headers})
.map((response: Response) => {
// login successful if user.status = success in the response
let user = response.json();
console.log(user.status)
if (user && "success" == user.status) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user.data));
}
});
}
Is the standard procedure not working?
git stash save
git branch xxx HEAD
git checkout xxx
git stash pop
Shorter:
git stash
git checkout -b xxx
git stash pop
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
You can use PowerMockito
Second second = Mockito.mock(Second.class);
whenNew(Second.class).withNoArguments().thenReturn(second);
But re-factoring is better decision.
For using by datalist, repeater.. in aspx page:<%# Eval("YourDateString").ToString().Remove(10) %>
I ran into this issue working with pyspark. As this is a python frontend for code running on a jvm, it requires type safety and using float instead of int is not an option. I worked around the issue by wrapping the pandas pd.read_csv
in a function that will fill user-defined columns with user-defined fill values before casting them to the required type. Here is what I ended up using:
def custom_read_csv(file_path, custom_dtype = None, fill_values = None, **kwargs):
if custom_dtype is None:
return pd.read_csv(file_path, **kwargs)
else:
assert 'dtype' not in kwargs.keys()
df = pd.read_csv(file_path, dtype = {}, **kwargs)
for col, typ in custom_dtype.items():
if fill_values is None or col not in fill_values.keys():
fill_val = -1
else:
fill_val = fill_values[col]
df[col] = df[col].fillna(fill_val).astype(typ)
return df
I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.
Use With in the code.
Try this way :
''''Way 1
currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))
''''Way 2
With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With
''''Way 3
With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
If You have jar file then create bat file with:
java -jar NameOfJar.jar
Love VonC's answer. Here's an easy version of it for beginners.
There is a git remote called origin
which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original
Let's add original repo's to our fork as a remote.
git remote add original https://git-repo/original/original.git
Now let's fetch the original repo to make sure we have the latest coded
git fetch original
As, VonC suggested, make sure we are on the master.
git checkout master
Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.
git reset --hard original/master
And you are done :)
To add one more item to Spinner you can:
ArrayAdapter myAdapter =
((ArrayAdapter) mySpinner.getAdapter());
myAdapter.add(myValue);
myAdapter.notifyDataSetChanged();
I've used bundle update --source
myself for a long time but there are scenarios where it doesn't work. Luckily, there's a gem called bundler-patch
which has the goal of fixing this shortcoming.
I also wrote a short blog post about how to use bundler-patch
and why bundle update --source
doesn't work consistently. Also, be sure to check out a post by chrismo that explains in great detail what the --source
option does.
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urls[0])
.build();
Response responses = null;
try {
responses = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
}
}
Example add to your columns:
JCol employees = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);
Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su
you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using .
or source
from the interactive shell. It could have been a standalone scipt, or it could have been source
'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.
I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.
Personally I don't mind mixing HTML and PHP like so
<a href="<?php echo $link;?>">link description</a>
As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.
echo '<a href="'.$link.'">link description</a>';
The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
var ans = 334 + '';
var temp = ans.toLowerCase();
alert(temp);
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
As an extension of Anooj VM's answer, I suggest the following to refresh content size only when it changes.
This approach also disable scrolling properly and support larger lists and rotation. There is no need to dispatch_async because contentSize changes are dispatched on main thread.
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:NULL];
}
- (void)resizeTableAccordingToContentSize:(CGSize)newContentSize {
CGRect superviewTableFrame = self.tableView.superview.bounds;
CGRect tableFrame = self.tableView.frame;
BOOL shouldScroll = newContentSize.height > superviewTableFrame.size.height;
tableFrame.size = shouldScroll ? superviewTableFrame.size : newContentSize;
[UIView animateWithDuration:0.3
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
self.tableView.frame = tableFrame;
} completion: nil];
self.tableView.scrollEnabled = shouldScroll;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([change[NSKeyValueChangeKindKey] unsignedIntValue] == NSKeyValueChangeSetting &&
[keyPath isEqualToString:@"contentSize"] &&
!CGSizeEqualToSize([change[NSKeyValueChangeOldKey] CGSizeValue], [change[NSKeyValueChangeNewKey] CGSizeValue])) {
[self resizeTableAccordingToContentSize:[change[NSKeyValueChangeNewKey] CGSizeValue]];
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[self resizeTableAccordingToContentSize:self.tableView.contentSize]; }
- (void)dealloc {
[self.tableView removeObserver:self forKeyPath:@"contentSize"];
}
Here's a pure VBA solution because Excel can hold joined cells:
Public Function GetIndexForColumn(Column As String) As Long
Dim astrColumn() As String
Dim Result As Long
Dim i As Integer
Dim n As Integer
Column = UCase(Column)
ReDim astrColumn(Len(Column) - 1)
For i = 0 To (Len(Column) - 1)
astrColumn(i) = Mid(Column, (i + 1), 1)
Next
n = 1
For i = UBound(astrColumn) To 0 Step -1
Result = (Result + ((Asc(astrColumn(i)) - 64) * n))
n = (n * 26)
Next
GetIndexForColumn = Result
End Function
Basically, this function does the same as any Hex to Dec function, except that it only takes alphabetical chars (A = 1, B = 2, ...). The rightmost char counts single, each char to the left counts 26 times the char right to it (which makes AA = 27 [1 + 26], AAA = 703 [1 + 26 + 676]). The use of UCase() makes this function case-insensitive.
You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.
You can also use for ex. this plugin https://github.com/tstabla/stVideo
Here's what you do if you dont have newlines in the file:
with open('large_text.txt') as f:
while True:
c = f.read(1024)
if not c:
break
print(c)
In my case it was a very silly error. I was using a library to read the connection string out of a config file, and I forgot to double back slash.
For example I had:
localhost\sqlexpress
which was read as localhostsqlexpress
when I should rather have had
localhost\\sqlexpress
note the \
If you have converted your form from plain HTML to twig, be sure you didn't miss deleting a closing </form>
tag. Silly mistake, but as I discovered it's a possible cause for this problem.
When I got this error, I couldn't figure it out at first. I'm using form_start()
and form_end()
to generate the form, so I shouldn't have to explicitly add the token with form_row(form._token)
, or use form_rest()
to get it. It should have already been added automatically by form_end()
.
The problem was, the view I was working with was one that I had converted from plain HTML to twig, and I had missed deleting the closing </form>
tag, so instead of :
{{ form_end(form) }}
I had:
</form>
{{ form_end(form) }}
That actually seems like something that might throw an error, but apparently it doesn't, so when form_end()
outputs form_rest()
, the form is already closed. The actual generated page source of the form was like this:
<form>
<!-- all my form fields... -->
</form>
<input type="hidden" id="item__token" name="item[_token]" value="SQAOs1xIAL8REI0evGMjOsatLbo6uDzqBjVFfyD0PE4" />
</form>
Obviously the solution is to delete the extra closing tag and maybe drink some more coffee.
This solution helped in my situation:
public class DateHelper {
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
}
using helper in code:
double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)
Pros and cons between #define
s, const
s and (what you have forgot) enum
s, depending on usage:
enum
s:
enum class X
are disambiguated by the scope X::
int
but can be explicitly set by the programmertemplate <typename T> void f(T t) { cout << ++t; }
won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)template <typename T> void f(T)
get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int)
instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.enum { A = 1, B = 2 }
- is A|B
"legal" from a program logic perspective?)make
and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)const
s:
#define
ala #define S std::string("abc")
, but the constant avoids repeated construction of distinct temporaries at each point of useconst
value, which minimises work and impact if switching between the two#define
s:
#define X "x"
and some client usage ala "pre" X "post"
, if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char*
or const std::string
given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post"
for string
)sizeof
directly on a defined numeric literalunsigned
){ 1, 2 }
that can be used to initialise arrays, or #define MICROSECONDS *1E-6
etc. (definitely not recommending this!)__FILE__
and __LINE__
can be incorporated into the macro substitution#if
statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef
-ine, redefine etc.make
and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)My personal opinion:
As a general rule, I use const
s and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).
RouterModule.forRoot([
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
{ path: '**', component: 'pageNotFoundComponent' }
])
Case 1 pathMatch:'full'
:
In this case, when app is launched on localhost:4200
(or some server) the default page will be welcome screen, since the url will be https://localhost:4200/
If https://localhost:4200/gibberish
this will redirect to pageNotFound screen because of path:'**'
wildcard
Case 2
pathMatch:'prefix'
:
If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }
, now this will never reach the wildcard route since every url would match path:''
defined.
Try this
select to_char(SYSDATE,'Month') from dual;
for full name and try this
select to_char(SYSDATE,'Mon') from dual;
for abbreviation
you can find more option here:
Assumed imports:
import pandas as pd
John Galt's answer is basically a reduce
operation. If I have more than a handful of dataframes, I'd put them in a list like this (generated via list comprehensions or loops or whatnot):
dfs = [df0, df1, df2, dfN]
Assuming they have some common column, like name
in your example, I'd do the following:
df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)
That way, your code should work with whatever number of dataframes you want to merge.
Edit August 1, 2016: For those using Python 3: reduce
has been moved into functools
. So to use this function, you'll first need to import that module:
from functools import reduce
I would use these polyfill https://github.com/WebReflection/ie8
<!--[if IE 8]><script
src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->
public class ListOfLists<T> : List<List<T>>
{
}
var myList = new ListOfLists<string>();
There is also this:
select m from table where not regexp_like(m, '^[0-9]\d+$')
which selects the rows that contains characters from the column you want (which is m in the example but you can change).
Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.
Did some testing with the following script, on both PS 2 and PS 4 and had the same result. I hope this helps people.
$PSVersionTable.PSVersion
function PSscript {
$PSscript = Get-Item $MyInvocation.ScriptName
Return $PSscript
}
""
$PSscript = PSscript
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
""
$PSscript = Get-Item $MyInvocation.InvocationName
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
Results -
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
There are a few things you should check :
install.packages("thePackage")
(this only needs to be done once)require(thePackage)
or library(thePackage)
(this should be done every time you start a new R session)If you're not sure in which package that function is situated, you can do a few things.
help.search("some.function")
or ??some.function
to get an information box that can tell you in which package it is contained.find
and getAnywhere
can also be used to locate functions.findFn
in the sos
package as explained in this answer.RSiteSearch("some.function")
or searching with rdocumentation or rseek are alternative ways to find the function.Sometimes you need to use an older version of R, but run code created for a newer version. Newly added functions (eg hasName in R 3.4.0) won't be found then. If you use an older R version and want to use a newer function, you can use the package backports to make such functions available. You also find a list of functions that need to be backported on the git repo of backports. Keep in mind that R versions older than R3.0.0 are incompatible with packages built for R3.0.0 and later versions.
You need to have a rmiregistry
running before attempting to connect (register) a RMI service with it.
The LocateRegistry.createRegistry(2020)
method call creates and exports a registry on the specified port number.
See the documentation for LocateRegistry
You can't do it without a full CSV parser.
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
To Hex:
string hex = intValue.ToString("X");
To int:
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
It's security all about. Make sure you have double check your firewall (windows and anti virus) in some cases when you disabled av firewall and restart your computer, automatically windows firewall is active and it's still block your application. Hope this is helpful ..
Immutable Object's state cannot be altered.
for example String
.
String str= "abc";//a object of string is created
str = str + "def";// a new object of string is created and assigned to str
I think i have the best answer for you, your git apps read your id_rsa.pub in root user directory
/home/root/.ssh/id_rsa.pub
That's why your key in /home/your_username/.ssh/id_rsa.pub can't be read by git. So you need to create the key in /home/root/.ssh/
$ sudo su
$ ssh-keygen
$ cd ~/.ssh
$ cat id_rsa.pub
Then copy the key in your github account. It's worked for me. You can try it.
Sort the file randomly and pick first 100
lines:
$ sort -R input | head -n 100 >output
Since jQuery 1.9, the :target
selector will match the URL hash. So you could do:
$(":target").show(); // or $("ul:target").show();
Which would select the element with the ID matching the hash and show it.
Unfortunately none of the above solved the problem for me.
I didn't want to edit the bootstrap-responsive.css so I went the easy way:
@media (min-width: 768px) and (max-width: 979px)
(line 461 with latest bootstrap version 2.3.1 as of today)@media (min-width: 979px)
in the place where it said @media (min-width: 768px) and (max-width: 979px)
before. This sets the from 768 to 979 style to everything above 768.That's it. It's not optimal, you will have duplicated css, but it works 100% perfect!
On Windows XP the path to the .gemrc file is
c:\Documents and Settings\All Users\Application Data\gemrc
and this file is not created by default, you should create it yourself.
You would like to add column z to the old data frame (old.df) defined by columns x and y.
z = rbinom(1000, 5, 0.25)
old.df <- data.frame(x = c(1:1000), y = rnorm(1:1000))
head(old.df)
Define a new data frame called new.df
new.df <- data.frame(x = old.df[,1], z, y = old.df[,2])
head(new.df)
This method should work with any enum
:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public int getValue() {
return this.ordinal();
}
public static DataType forValue(int value) {
return values()[value];
}
public String toString() {
return forValue(getValue()).name();
}
}
If you want to know the number of physical cores (not virtual hyperthreaded cores), here is a platform independent solution:
psutil.cpu_count(logical=False)
https://github.com/giampaolo/psutil/blob/master/INSTALL.rst
Note that the default value for logical
is True
, so if you do want to include hyperthreaded cores you can use:
psutil.cpu_count()
This will give the same number as os.cpu_count()
and multiprocessing.cpu_count()
, neither of which have the logical
keyword argument.
Steps to install curl in windows
Install cURL on Windows
There are 4 steps to follow to get cURL installed on Windows.
Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate
Step One: Install Visual C++ 2008 Redistributables
From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)
Step Two: Install Win(32/64) OpenSSL v1.0.0k Light
From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light
Step Three: Install cURL
Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html
Copy curl.exe to C:\Windows\System32
Step Four: Install Recent Certificates
Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt
If you have already installed curl
or after doing the above steps, add the directory where it's installed to the windows path:
1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Start a timer in the constructor of your class. The interval is in milliseconds so 5*60 seconds = 300 seconds = 300000 milliseconds.
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 300000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
Then call GetData()
in the timer_Elapsed
event like this:
static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//YourCode
}
UTF-8 is one possible encoding scheme for Unicode text.
Unicode is a broad-scoped standard which defines over 140,000 characters and allocates each a numerical code (a code point). It also defines rules for how to sort this text, normalise it, change its case, and more. A character in Unicode is represented by a code point from zero up to 0x10FFFF inclusive, though some code points are reserved and cannot be used for characters.
There is more than one way that a string of Unicode code points can be encoded into a binary stream. These are called "encodings". The most straightforward encoding is UTF-32, which simply stores each code point as a 32-bit integer, with each being 4 bytes wide.
UTF-8 is another encoding, and is becoming the de-facto standard, due to a number of advantages over UTF-32 and others. UTF-8 encodes each code point as a sequence of either 1, 2, 3 or 4 byte values. Code points in the ASCII range are encoded as a single byte value, to be compatible with ASCII. Code points outside this range use either 2, 3, or 4 bytes each, depending on what range they are in.
UTF-8 has been designed with these properties in mind:
ASCII characters are encoded exactly as they are in ASCII, such that an ASCII string is also a valid UTF-8 string representing the same characters.
Binary sorting: Sorting UTF-8 strings using a binary sort will still result in all code points being sorted in numerical order.
When a code point uses multiple bytes, none of those bytes contain values in the ASCII range, ensuring that no part of them could be mistaken for an ASCII character. This is also a security feature.
UTF-8 can be easily validated, and distinguished from other character encodings by a validator. Text in other 8-bit or multi-byte encodings will very rarely also validate as UTF-8 due to the very specific structure of UTF-8.
Random access: At any point in a UTF-8 string it is possible to tell if the byte at that position is the first byte of a character or not, and to find the start of the next or current character, without needing to scan forwards or backwards more than 3 bytes or to know how far into the string we started reading from.
For using Android you use below code
<a href="sms:+32665?body=reg fb1>Send SMS</a>
For iOS you can use below code
<a href="sms:+32665&body=reg fb1>Send SMS</a>
below code working for both iOs and Android
<a href="sms:+32665?&body=reg fb1>Send SMS</a>
I'm slightly confused. You should be able to call sqlplus from within the bash script. This may be what you were doing with your first statement
Try Executing the following within your bash script:
#!/bin/bash
echo Start Executing SQL commands
sqlplus <user>/<password> @file-with-sql-1.sql
sqlplus <user>/<password> @file-with-sql-2.sql
If you want to be able to pass data into your scripts you can do it via SQLPlus by passing arguments into the script:
Contents of file-with-sql-1.sql
select * from users where username='&1';
Then change the bash script to call sqlplus passing in the value
#!/bin/bash
MY_USER=bob
sqlplus <user>/<password> @file-with-sql-1.sql $MY_USER
Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:
$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%
This will use awk
to print out 100 minus the 12th field (idle), with a percentage sign after it. awk
will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/
).
You can also average five samples, one second apart:
$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'
Test it like this:
$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
I recently came across Python 3 interpreter at CompileOnline.
You can mock datetime
using this:
In the module sources.py
:
import datetime
class ShowTime:
def current_date():
return datetime.date.today().strftime('%Y-%m-%d')
In your tests.py
:
from unittest import TestCase, mock
import datetime
class TestShowTime(TestCase):
def setUp(self) -> None:
self.st = sources.ShowTime()
super().setUp()
@mock.patch('sources.datetime.date')
def test_current_date(self, date_mock):
date_mock.today.return_value = datetime.datetime(year=2019, month=10, day=1)
current_date = self.st.current_date()
self.assertEqual(current_date, '2019-10-01')
You can use the following methods to update the value of a reactive form control. Any of the following method will suit for your need.
Methods using setValue()
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
Methods using patchValue()
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
Last method will loop thorough all the controls in the form so it is not preferred when updating single control
You can use any of the method inside the event handler
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
You can update multiple controls in the form group if required using the
this.form.patchValue({"dept": selected.id, "description":"description value"});
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
request.remote_ip
is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.
For this scenario HTTP 404 is response code for the response from the REST API Like 400, 401, 404 , 422 unprocessable entity
use the Exception handling to check the full exception message.
try{
// call the rest api
} catch(RestClientException e) {
//process exception
if(e instanceof HttpStatusCodeException){
String responseText=((HttpStatusCodeException)e).getResponseBodyAsString();
//now you have the response, construct json from it, and extract the errors
System.out.println("Exception :" +responseText);
}
}
This exception block give you the proper message thrown by the REST API
Non-pandas
solution: using set().
import pandas as pd
import numpy as np
df = pd.DataFrame({'Col1' : ['Bob', 'Joe', 'Bill', 'Mary', 'Joe'],
'Col2' : ['Joe', 'Steve', 'Bob', 'Bob', 'Steve'],
'Col3' : np.random.random(5)})
print df
print set(df.Col1.append(df.Col2).values)
Output:
Col1 Col2 Col3
0 Bob Joe 0.201079
1 Joe Steve 0.703279
2 Bill Bob 0.722724
3 Mary Bob 0.093912
4 Joe Steve 0.766027
set(['Steve', 'Bob', 'Bill', 'Joe', 'Mary'])
I solved this with Access options.
Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar
In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."
Closed Access, reopened the database and got the warning for blocked content again.
So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )
This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}
{{vm.StateName === "AA" ? "ALL" : vm.StateName}}
useHistory()
from react-router-dom
can fix your problem
import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
const history = useHistory();
const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');
return (
<div>
<button onClick={navigateTo} type="button" />
</div>
);
}
export default NavigationDemo;
Based on your comments, you would be better off with Text-finder plugin.
It allows to search file(s), as well as console, for a regular expression and then set the build either unstable
or failed
if found.
As for the Groovy, you can use the following to access ${WORKSPACE}
environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]
IF you know the width of the container, you could do like this:
#container
width: #{200}px
#element
width: #{(0.25 * 200) - 5}px
I'm aware that in many cases #container could have a relative width. Then this wouldn't work.
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
You can use the .delay()
function.
This is what you're after:
.addClass("load").delay(2000).addClass("done");
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'
Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1
argument.
Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
Timer for jQuery - smaller, working, tested.
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
$("#seconds").html(pad(++sec%60));_x000D_
$("#minutes").html(pad(parseInt(sec/60,10)));_x000D_
}, 1000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Pure JavaScript:
var sec = 0;_x000D_
function pad ( val ) { return val > 9 ? val : "0" + val; }_x000D_
setInterval( function(){_x000D_
document.getElementById("seconds").innerHTML=pad(++sec%60);_x000D_
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));_x000D_
}, 1000);
_x000D_
<span id="minutes"></span>:<span id="seconds"></span>
_x000D_
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
mv /usr/local/hadoop_store/hdfs/datanode /usr/local/hadoop_store/hdfs/datanode.backup
mkdir /usr/local/hadoop_store/hdfs/datanode
hadoop datanode OR start-all.sh
jps
In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
I'd use iloc
, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:
df.iloc[::5, :]
It's worth noting that multiple field indexes can drastically improve your query performance. So in the above example we assume ProductID is the only field to lookup but were the query to say ProductID = 1 AND Category = 7 then a multiple column index helps. This is achieved with the following:
ALTER TABLE `table` ADD INDEX `index_name` (`col1`,`col2`)
Additionally the index should match the order of the query fields. In my extended example the index should be (ProductID,Category) not the other way around.
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.tv_data);
try {
Class.forName("com.mysql.jdbc.Driver");
// perfect
// localhost
/*
* Connection con = DriverManager .getConnection(
* "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
* );
*/
// online testing
Connection con = DriverManager
.getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tablename ");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
}
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
In addition to @JesperFyhrKnudsen's answer and @MathiasLykkegaardLorenzen's comment, you'd better dispose
the returned Process
after using it.
So, In order to dispose the Process
, you could wrap it in a using
scope or calling Dispose
on the returned process (proc
variable).
using
scope:
var memory = 0.0;
using (Process proc = Process.GetCurrentProcess())
{
// The proc.PrivateMemorySize64 will returns the private memory usage in byte.
// Would like to Convert it to Megabyte? divide it by 2^20
memory = proc.PrivateMemorySize64 / (1024*1024);
}
Or Dispose
method:
var memory = 0.0;
Process proc = Process.GetCurrentProcess();
memory = Math.Round(proc.PrivateMemorySize64 / (1024*1024), 2);
proc.Dispose();
Now you could use the memory
variable which is converted to Megabyte.
Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/
This one did works for me:
function hasVerticalScroll(node){
if(node == undefined){
if(window.innerHeight){
return document.body.offsetHeight> window.innerHeight;
}
else {
return document.documentElement.scrollHeight >
document.documentElement.offsetHeight ||
document.body.scrollHeight>document.body.offsetHeight;
}
}
else {
return node.scrollHeight> node.offsetHeight;
}
}
For the body, just use hasVerticalScroll()
.
Just write
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name
the order by is applied to the complete resultset
To make a text default in a select box use the $form->select()
method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female
in the list box by default.
Keep baking...
According to the above answers setdefault() method worked for me.
old_attr_name = mydict.setdefault(key, attr_name)
if attr_name != old_attr_name:
raise RuntimeError(f"Key '{key}' duplication: "
f"'{old_attr_name}' and '{attr_name}'.")
Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key
first (as was already advised), but with setdefault()
we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.
Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.
In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.
You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.
1. Generalized Substring
To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:
${string: -7:4}
Where 4 is the length of course (7-3).
2. Alternative using cut
In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:
echo $string | cut -c $((${#string}-2))-
Here, ${#string}
is the length of the string, and the "-" means cut to the end.
3. Alternative using awk
This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length)
going to the end if the length is omitted. length($string)-2)
thus picks up the last three characters.
echo $string | awk '{print substr($1,length($1)-2) }'
If you cannot get your tables to convert or your table is always set to some non-utf8 character set, but you want utf8, your best bet might be to wipe it out and start over again and explicitly specify:
create database database_name character set utf8;
First of all open applicationhost.config file in visual studio.
address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config
Then find this codes:
<site name="Your Site_Name" id="24">
<application path="/" applicationPool="Clr4IntegratedAppPool"
<virtualDirectory path="/" physicalPath="C:\Users\Your User Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:Port_Number:*" />
</bindings>
</site>
*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.
In the Second step you must run cmd as administrator and type this code:
netsh http add urlacl url=http://*:port_Number/ user=everyone
and press enter
In Third step you must Enable port on firewall
Go to the “Control Panel\System and Security\Windows Firewall”
Click “Advanced settings”
Select “Inbound Rules”
Click on “New Rule …” button
Select “Port”, click “Next”
Fill your IIS Express listening port number, click “Next”
Select “Allow the connection”, click “Next”
Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”
Fill rule name (e.g “IIS Express), click “Finish”
I hopeful this answer be useful for you
Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer
I would use it like this, its way shorter and it won't give any problems
dynamic result = null;
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
result = methodInfo.Invoke(classInstance, parameters.Length == 0 ? null : parametersArray);
}
This python script is awesome.
Here's my Ruby version of it (with minor improvement) and search capabilities. (for iOS 5)
# encoding: utf-8
require 'fileutils'
require 'digest/sha1'
class ManifestParser
def initialize(mbdb_filename, verbose = false)
@verbose = verbose
process_mbdb_file(mbdb_filename)
end
# Returns the numbers of records in the Manifest files.
def record_number
@mbdb.size
end
# Returns a huge string containing the parsing of the Manifest files.
def to_s
s = ''
@mbdb.each do |v|
s += "#{fileinfo_str(v)}\n"
end
s
end
def to_file(filename)
File.open(filename, 'w') do |f|
@mbdb.each do |v|
f.puts fileinfo_str(v)
end
end
end
# Copy the backup files to their real path/name.
# * domain_match Can be a regexp to restrict the files to copy.
# * filename_match Can be a regexp to restrict the files to copy.
def rename_files(domain_match = nil, filename_match = nil)
@mbdb.each do |v|
if v[:type] == '-' # Only rename files.
if (domain_match.nil? or v[:domain] =~ domain_match) and (filename_match.nil? or v[:filename] =~ filename_match)
dst = "#{v[:domain]}/#{v[:filename]}"
puts "Creating: #{dst}"
FileUtils.mkdir_p(File.dirname(dst))
FileUtils.cp(v[:fileID], dst)
end
end
end
end
# Return the filename that math the given regexp.
def search(regexp)
result = Array.new
@mbdb.each do |v|
if "#{v[:domain]}::#{v[:filename]}" =~ regexp
result << v
end
end
result
end
private
# Retrieve an integer (big-endian) and new offset from the current offset
def getint(data, offset, intsize)
value = 0
while intsize > 0
value = (value<<8) + data[offset].ord
offset += 1
intsize -= 1
end
return value, offset
end
# Retrieve a string and new offset from the current offset into the data
def getstring(data, offset)
return '', offset + 2 if data[offset] == 0xFF.chr and data[offset + 1] == 0xFF.chr # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset...(offset + length)]
return value, (offset + length)
end
def process_mbdb_file(filename)
@mbdb = Array.new
data = File.open(filename, 'rb') { |f| f.read }
puts "MBDB file read. Size: #{data.size}"
raise 'This does not look like an MBDB file' if data[0...4] != 'mbdb'
offset = 4
offset += 2 # value x05 x00, not sure what this is
while offset < data.size
fileinfo = Hash.new
fileinfo[:start_offset] = offset
fileinfo[:domain], offset = getstring(data, offset)
fileinfo[:filename], offset = getstring(data, offset)
fileinfo[:linktarget], offset = getstring(data, offset)
fileinfo[:datahash], offset = getstring(data, offset)
fileinfo[:unknown1], offset = getstring(data, offset)
fileinfo[:mode], offset = getint(data, offset, 2)
if (fileinfo[:mode] & 0xE000) == 0xA000 # Symlink
fileinfo[:type] = 'l'
elsif (fileinfo[:mode] & 0xE000) == 0x8000 # File
fileinfo[:type] = '-'
elsif (fileinfo[:mode] & 0xE000) == 0x4000 # Dir
fileinfo[:type] = 'd'
else
# $stderr.puts "Unknown file type %04x for #{fileinfo_str(f, false)}" % f['mode']
fileinfo[:type] = '?'
end
fileinfo[:unknown2], offset = getint(data, offset, 4)
fileinfo[:unknown3], offset = getint(data, offset, 4)
fileinfo[:userid], offset = getint(data, offset, 4)
fileinfo[:groupid], offset = getint(data, offset, 4)
fileinfo[:mtime], offset = getint(data, offset, 4)
fileinfo[:atime], offset = getint(data, offset, 4)
fileinfo[:ctime], offset = getint(data, offset, 4)
fileinfo[:filelen], offset = getint(data, offset, 8)
fileinfo[:flag], offset = getint(data, offset, 1)
fileinfo[:numprops], offset = getint(data, offset, 1)
fileinfo[:properties] = Hash.new
(0...(fileinfo[:numprops])).each do |ii|
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo[:properties][propname] = propval
end
# Compute the ID of the file.
fullpath = fileinfo[:domain] + '-' + fileinfo[:filename]
fileinfo[:fileID] = Digest::SHA1.hexdigest(fullpath)
# We add the file to the list of files.
@mbdb << fileinfo
end
@mbdb
end
def modestr(val)
def mode(val)
r = (val & 0x4) ? 'r' : '-'
w = (val & 0x2) ? 'w' : '-'
x = (val & 0x1) ? 'x' : '-'
r + w + x
end
mode(val >> 6) + mode(val >> 3) + mode(val)
end
def fileinfo_str(f)
return "(#{f[:fileID]})#{f[:domain]}::#{f[:filename]}" unless @verbose
data = [f[:type], modestr(f[:mode]), f[:userid], f[:groupid], f[:filelen], f[:mtime], f[:atime], f[:ctime], f[:fileID], f[:domain], f[:filename]]
info = "%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % data
info += ' -> ' + f[:linktarget] if f[:type] == 'l' # Symlink destination
f[:properties].each do |k, v|
info += " #{k}=#{v.inspect}"
end
info
end
end
if __FILE__ == $0
mp = ManifestParser.new 'Manifest.mbdb', true
mp.to_file 'filenames.txt'
end
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
Considering that both strings may be very large, there are 2 main approaches bitwise search
and localeCompare
I recommed this function
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
An expression like
dosomething1 && dosomething2 && dosomething3
will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":
cat nosuchfile && echo "done"
echo $?
1
Here is an option for people who use DataBinding
for RecyclerView
.
I have var recyclerViewState: Parcelable?
in my adapter. And I use a BindingAdapter
with a variation of @DawnYu's answer to set and update data in the RecyclerView
:
@BindingAdapter("items")
fun setRecyclerViewItems(
recyclerView: RecyclerView,
items: List<RecyclerViewItem>?
) {
var adapter = (recyclerView.adapter as? RecyclerViewAdapter)
if (adapter == null) {
adapter = RecyclerViewAdapter()
recyclerView.adapter = adapter
}
adapter.recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState()
// the main idea is in this call with a lambda. It allows to avoid blinking on data update
adapter.submitList(items.orEmpty()) {
adapter.recyclerViewState?.let {
recyclerView.layoutManager?.onRestoreInstanceState(it)
}
}
}
Finally, the XML part looks like:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/possible_trips_rv"
android:layout_width="match_parent"
android:layout_height="0dp"
app:items="@{viewState.yourItems}"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
<input id="fusk" type="file" name="upload" style="display: none;"
onChange=" document.getElementById('myForm').submit();"
>
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.
I think the following would work well with lesser line of codes.
session()->flash('toast', [
'status' => 'success',
'body' => 'Body',
'topic' => 'Success']
);
I'm using a toaster package, but you can have something like this in your view.
toastr.{{session('toast.status')}}(
'{{session('toast.body')}}',
'{{session('toast.topic')}}'
);
Try this updated code :
$(bla).click(function(){
if (something) {
console.log($target.prev("input")) // gives out the right object
$target.toggleClass("open").prev("input").attr("disabled", "true");
}else{
$target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
}
})
java.util.logging
keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.
In general, at the top of every class, you should have:
private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );
Then, you can just use various facilities of the Logger class.
Use Level.FINE
for anything that is debugging at the top level of execution flow:
LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );
Use Level.FINER
/ Level.FINEST
inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:
LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );
Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with. Object[]
as above is cheap, on the stack allocation usually.
With exception handling, always log the complete exception details:
try {
...something that can throw an ignorable exception
} catch( Exception ex ) {
LOGGER.log( Level.SEVERE, ex.toString(), ex );
}
I always pass ex.toString()
as the message here, because then when I "grep -n
" for "Exception
" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.
Thanks to the talk with Sarfraz we could figure out the solution.
The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities
table and filter correct entries).
So, instead of:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex]
};
it should be:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex].value
};
Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.
Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.
dim rng as range
dim rDel as range
for each rng in {the range you're searching}
if {Conditions to be met} = true then
if not rDel is nothing then
set rDel = union(rng,rDel)
else
set rDel = rng
end if
end if
next
rDel.entirerow.delete
That way you don't have to worry about sorting or things being at the bottom.
I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
Replace userEnteredValue with (big surprise) the value that the user entered :)
Like this:
String[][] arrays = { array1, array2, array3, array4, array5 };
or
String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };
(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)
$description = nl2br(stripcslashes($description));
The NetBeans IDE checks for syntax errors, unusued variables and such. It's not automated, but works fine for small or medium projects.
Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension.
But still, the accept attribute of <input type = "file">
can help to provide a filter in the file select dialog box of the OS. For example,
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" />
_x000D_
should provide a way to filter out files other than .xls or .xlsx. Although the MDN page for input
element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.
So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
_x000D_
[Edge (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is All files (*)
.]
You can also use asterisks in MIME-types. For example:
<input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
<input type="file" accept="video/*" /> <!-- all video types -->
_x000D_
W3C recommends authors to specify both MIME-types and corresponding extensions in the accept
attribute. So, the best approach is:
<!-- Right approach: Use both file extensions and corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
_x000D_
JSFiddle of the same: here.
Reference: List of MIME-types
IMPORTANT: Using the accept
attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be this), and definitely file types MUST be verified on the server, using a combination of MIME-type using both the file extension and its binary signature (ASP.NET, PHP, Ruby, Java). You might also want to refer to these tables for file types and their magic numbers, to perform a more robust server-side verification.
Here are three good reads on file-uploads and security.
EDIT: Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.
pthread_exit
terminates the calling thread while pthread_join
suspends execution of calling thread until target threads completes execution.
They are pretty much well explained in detail in the open group documentation:
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH
from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Calling git from a PS script
I had to repackage a git
client wrapped in Chocolatey
(for those who may not know, it's a kind of app-store for Windows) which massively uses PS scripts.
I found out that, once git
is in the PATH
, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git
crt
file in $ca_bundle
variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where
command
$java_exe = cmd.exe /c where java
will store the location of java.exe
file in $java_exe
variable.
If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok
The modern (systemctl
) way of doing it:
systemctl is-active nginx
You can use the exit value in your shell scripts as follows:
systemctl -q is-active nginx && echo "It is active, do something"
Simply enter these into Windows command prompt.
cd C:\Program Files\Java\jdk1.7.0_09\bin
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\userName\.android\debug.keystore" -list -v
The base password is android
You will be presented with the MD5
, SHA1
, and SHA256
keys; Choose the one you need.
Have a look at entry points too. You will be able to use multiple CMD https://docs.docker.com/engine/reference/builder/#/entrypoint
Similar to older answers, but a bit simpler, without the lambda:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
(broken in two lines here, for clarity)
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
Following code could be used:
ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
First off, see How Big can a Python Array Get? and Numpy, problem with long arrays
Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:
I had the same issue and the following seemed to have addressed the issue.
a) Updated to latest version 1.3.5 and re-enabled all the diagnosis settings.
I was still getting the messages
b) Added the vendor folder with the dependent libraries to the workspace
This seems to have solved the problem.
It depends on whether a function uses external variable or not to perform operation.
External variables - variables defined outside the scope of a function.
Lambda expressions are stateless because It depends on parameters, internal variables or constants to perform operations.
Function<Integer,Integer> lambda = t -> {
int n = 2
return t * n
}
Closures hold state because it uses external variables (i.e. variable defined outside the scope of the function body) along with parameters and constants to perform operations.
int n = 2
Function<Integer,Integer> closure = t -> {
return t * n
}
When Java creates closure, it keeps the variable n with the function so it can be referenced when passed to other functions or used anywhere.
As @wirey said appendTo
should work, if not then you can try this:
$("#tblEntAttributes tbody").append(newRowContent);
In my case, i only needed it within certain conditions, and to be done easily in HTML:
<input type="checkbox" [style.pointer-events]="(condition == true) ? 'none' : 'auto'">
Or in case you need this consistently:
<input type="checkbox" style="pointer-events: none;">
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
I liked this:
new_column = np.zeros((len(a), 1))
b = np.block([a, new_column])
You can use https://ip-api.io/ to get city Name. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
Javascript Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('City Name: ' + result.city)
console.log(result);
});
});
});
HTML Code
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
JSON Output
{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}
}
I would do it like this:
int totalMinutes = (int)(end - start).TotalMinutes;
In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
If you don't, unless there's some Join()
override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):
db.Services.Join(db.ServiceAssignments,
s => s.Id,
sa => sa.ServiceId,
(s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);
To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector
) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array
) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array
won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a
definitely use a std::array
over a vector. If any of those requirements is not true, then use a std::vector
.
There are good answers here but let me address the more global point of adding action listener that listens to multiple buttons.
There are two popular approaches.
Using a Common Action Listener
You can get the source of the action in your actionPerformed(ActionEvent e)
implementation:
JButton button1, button2; //your button
@Override
public void actionPerformed(ActionEvent e) {
JButton actionSource = (JButton) e.getSource();
if(actionSource.equals(button1)){
// YOU BUTTON 1 CODE HERE
} else if (actionSource.equals(button2)) {
// YOU BUTTON 2 CODE HERE
}
}
Using ActionCommand
With this approach you setting the actionCommand
field of your button which later will allow you to use switch
:
button1.setActionCommand("actionName1");
button2.setActionCommand("actionName2");
And later:
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
switch (actionCommand) {
case "actionName1":
// YOU BUTTON 1 CODE HERE
break;
case "actionName2":
// YOU BUTTON 2 CODE HERE
break;
}
}
Check out to learn more about JFrame Buttons, Listeners and Fields.
this is the query you need:
SELECT b.id, a.home,b.[datetime],b.player,a.resource FROM
(SELECT home,MAX(resource) AS resource FROM tbl_1 GROUP BY home) AS a
LEFT JOIN
(SELECT id,home,[datetime],player,resource FROM tbl_1) AS b
ON a.resource = b.resource WHERE a.home =b.home;
You are getting this is because you are using a Anaconda distribution of Jupyter notebook. So just do conda install pandas
restart your jupyter notebook
and rerun your cell. It should work.
If you are trying this on a Virtual Env try this
conda create -n name_of_my_env python
This will create a minimal environment with only Python installed in it. To put your self inside this environment run:2 source activate name_of_my_env
On Windows the command is:
activate name_of_my_env
The final step required is to install pandas. This can be done with the following command:
conda install pandas
To install a specific pandas version:
conda install pandas=0.20.3
To install other packages, IPython for example:
conda install ipython
To install the full Anaconda distribution:
conda install anaconda
If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:
conda install pip
pip install django
Installing from PyPI
pandas can be installed via pip from PyPI.
pip install pandas
Installing with ActivePython
Hope this helps.
Another way to get a subset of columns from your DataFrame, assuming you want all the rows, would be to do:
data[['a','b']]
and data[['c','d','e']]
If you want to use numerical column indexes you can do:
data[data.columns[:2]]
and data[data.columns[2:]]
This is actually a multi-step process. First you'll need to add all your files to the current stage:
git add .
You can verify that your files will be added when you commit by checking the status of the current stage:
git status
The console should display a message that lists all of the files that are currently staged, like this:
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: README
# new file: src/somefile.js
#
If it all looks good then you're ready to commit. Note that the commit action only commits to your local repository.
git commit -m "some message goes here"
If you haven't connected your local repository to a remote one yet, you'll have to do that now. Assuming your remote repository is hosted on GitHub and named "Some-Awesome-Project", your command is going to look something like this:
git remote add origin [email protected]:username/Some-Awesome-Project
It's a bit confusing, but by convention we refer to the remote repository as 'origin' and the initial local repository as 'master'. When you're ready to push your commits to the remote repository (origin), you'll need to use the 'push' command:
git push origin master
For more information check out the tutorial on GitHub: http://learn.github.com/p/intro.html
ENV
OS: fedora 29 x86_64 workstation
Docker:
[user@localhost ~]$ docker --version
Docker version 19.03.5, build 633a0ea838
Image info: "DockerVersion": "18.09.7"
The images should stored in /var/lib/docker/overlay2
by default.
MY EXAMPLE
Show images:
[user@localhost ~]$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
neo4j latest 8ed7463b8476 12 months ago 548MB
hello-world latest fce289e99eb9 2 years ago 1.84kB
The image size is 548M.
See the image information of 8ed7463b8476
.
[user@localhost ~]$ docker image inspect 8ed7463b8476
... ... ... ...
"DockerVersion": "18.09.7",
... ... ... ...
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2
/66dc24704d7ea5f1a5dee0bf4a5297cb78bcbd0d4b36206b8cca62cd4de7f2b1/diff:
/var/lib/docker/overlay2
/5ab91cf721359d43d01038233d397fd9ed1c4b3857c0c7d9a2dd7f2ac5eccad0/diff:
/var/lib/docker/overlay2
/e82fdf7ee3e37db0a11d9ca309245ae852425d24d6f5d3313dcf604cdddb397b/diff:
/var/lib/docker/overlay2
/9394543085d467010d0468fffb388e5616a89e2cf16c1c2b7b31aee4e542ae69/diff:
/var/lib/docker/overlay2
/c7c7a16e3dbaeea1a3a3b0bbca39f34f08f6b8ab15d753e6e68f9851c80d95b4/diff:
/var/lib/docker/overlay2
/3b470afdf8939b45159f3171f0bef2a27085b4b980e09f0c666fbdc58b944d97/diff:
/var/lib/docker/overlay2
/463ba63f79eb6b2f5466e7b71041bc346a8e9c4ebddd34d23422c719824a2340/diff",
... ... ... ...
Let's see the size of these folders.
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/66dc24704d7ea5f1a5dee0bf4a5297cb78bcbd0d4b36206b8cca62cd4de7f2b1
141M /var/lib/docker/overlay2/66dc24704d7ea5f1a5dee0bf4a5297cb78bcbd0d4b36206b8cca62cd4de7f2b1
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/5ab91cf721359d43d01038233d397fd9ed1c4b3857c0c7d9a2dd7f2ac5eccad0/
28K /var/lib/docker/overlay2/5ab91cf721359d43d01038233d397fd9ed1c4b3857c0c7d9a2dd7f2ac5eccad0/
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/e82fdf7ee3e37db0a11d9ca309245ae852425d24d6f5d3313dcf604cdddb397b/
100K /var/lib/docker/overlay2/e82fdf7ee3e37db0a11d9ca309245ae852425d24d6f5d3313dcf604cdddb397b/
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/9394543085d467010d0468fffb388e5616a89e2cf16c1c2b7b31aee4e542ae69/
310M /var/lib/docker/overlay2/9394543085d467010d0468fffb388e5616a89e2cf16c1c2b7b31aee4e542ae69/
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/c7c7a16e3dbaeea1a3a3b0bbca39f34f08f6b8ab15d753e6e68f9851c80d95b4/
36K /var/lib/docker/overlay2/c7c7a16e3dbaeea1a3a3b0bbca39f34f08f6b8ab15d753e6e68f9851c80d95b4/
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/3b470afdf8939b45159f3171f0bef2a27085b4b980e09f0c666fbdc58b944d97/
9.5M /var/lib/docker/overlay2/3b470afdf8939b45159f3171f0bef2a27085b4b980e09f0c666fbdc58b944d97/
[user@localhost ~]$ sudo du -sh /var/lib/docker/overlay2/463ba63f79eb6b2f5466e7b71041bc346a8e9c4ebddd34d23422c719824a2340/
76M /var/lib/docker/overlay2/463ba63f79eb6b2f5466e7b71041bc346a8e9c4ebddd34d23422c719824a2340/
We can see the size that is close to 548M.
We also can save image to an output file.
[user@localhost ~]$ docker save -o neo4j.image.tar 8ed7463b8476
[user@localhost ~]$ du -sh neo4j.image.tar
528M neo4j.image.tar
We can extract the package file and check the sizes of files in the package.
[user@localhost neo4j.image]$ du -sh *
16K 2f0dd5fb60a940719a3e781133611cc64c2acded03bd47e04b0997fd0c1dae50
8.7M 73819037a38eabeb7c622533e4058c84f5ff106475a1aba78a278f8b36c172f7
309M 8d31d715b324a2ae3ccb1577e981d492f40e34db6371f0858da925ef02b5762e
12K 8ed7463b84760f09b1b86a732ee6f295baaadffe72ce4fdb7ad306fe5e096bbb.json
36K 966e726ff1d9be9dca68014cda6f1ecf974365c553b82ea3834fff5d73ea593e
70M a32776b9621e916e8714389b1037bf47253a2d3d1c806ad515623d2150c92485
60K d82868a318b95466f213136f81cd7258518744da72f46ca51b04b35f2351f46a
16K e62169d79fab44bebb0a455b01af5f636bace7673a1d38fc092daad77d51cd0e
141M fe8014622f7933e178b9005deffda3eb4828703eb7eca93b5485232930e3916b
4.0K manifest.json
We also can archive the folder /var/lib/docker/overlay2/
to compare the size of the package to image files. The size is close to the image size either.
Some time has passed since this was asked.
Now it is possible to not only specify number to window.scroll function, but also pass an object with three properties: top, left and behavior. So if we would like to have a smooth scroll up with native JavaScript, we can now do something like this:
let button = document.querySelector('button-id');
let options = {top: 0, left: 0, behavior: 'smooth'}; // left and top are coordinates
button.addEventListener('click', () => { window.scroll(options) });
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
Here is the solution I'm using:
const result = `${ window.location.protocol }//${ window.location.host }`;
EDIT:
To add cross-browser compatibility, use the following:
const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;