I know this question is a little old but here is my solution.
// HTML
// <input type="checkbox" onClick="setcb1()"/>
// <input type="checkbox" onClick="setcb2()"/>
// cb1 = checkbox 1
// cb2 = checkbox 2
var cb1 = getId('cb1'),
cb2 = getId('cb2');
function getId(id) {
return document.getElementById(id);
}
function setcb1() {
if(cb1.checked === true) {
cb2.checked = false;
cb2.disabled = "disabled"; // You have to disable the unselected checkbox
} else if(cb1.checked === false) {
cb2.disabled = ""; // Then enable it if there isn't one selected.
}
}
function setcb2() {
if(cb2.checked === true) {
cb1.checked = false;
cb1.disabled = "disabled"
} else if(cb2.checked === false) {
cb1.disabled = ""
}
Hope this helps!
As Muhammad Sahputra suggested in this post, it is possible to run Windows OS inside VirtualBox (using VBoxHeadless - without graphical interface) inside Docker container.
Also, a NAT setup inside the VM network configurations can do a port forwarding which gives you the ability to pass-through any traffic that comes to and from the Docker container. This eventually, in a wide perspective, allows you to run any Windows-based service on top of Linux machine.
Maybe this is not a typical use-case of a Docker container, but it definitely an interesting approach to the problem.
For simple applications and maybe more complicated, you can try to use wine inside a docker container.
This docker hub page may help you to achieve your goal.
I hope that Docker will release a native solution soon, like they did with docker-machine on Windows several years ago.
In Python there is a method for doing this: driver.refresh()
. It may not be the same in Java.
Alternatively, you could driver.get("http://foo.bar");
, although I think the refresh method should work just fine.
In dash and other shells, you can use
printf "%d\n" (your hexadecimal number)
to convert a hexadecimal number to decimal. This is not bash, or ksh, specific.
set width attribute as: width: fit-content
for full url use
$('#imageContainerId').prop('src')
for relative image url use
$('#imageContainerId').attr('src')
function showImgUrl(){_x000D_
console.log('for full image url ' + $('#imageId').prop('src') );_x000D_
console.log('for relative image url ' + $('#imageId').attr('src'));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>_x000D_
_x000D_
<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
_x000D_
detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)
function onScale(el, callback) {
let hypo = undefined;
el.addEventListener('touchmove', function(event) {
if (event.targetTouches.length === 2) {
let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
(event.targetTouches[0].pageY - event.targetTouches[1].pageY));
if (hypo === undefined) {
hypo = hypo1;
}
callback(hypo1/hypo);
}
}, false);
el.addEventListener('touchend', function(event) {
hypo = undefined;
}, false);
}
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab
$query="SELECT * FROM contacts";
$result=mysql_query($query);
std::string a = "Hello ";
a += "World";
You can use the JSON stringify
method.
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'
There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.
If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.
Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast
(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Because char
is by default signed
declared that means the range of the variable is
-127 to +127>
your value is overflowed. To get the desired value you have to declared the unsigned
modifier. the modifier's (unsigned
) range is:
0 to 255
to get the the range of any data type follow the process 2^bit
example char
is 8 bit length to get its range just 2 ^(power) 8
.
Element.scrollHeight
is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow
and height
to auto
, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.
It declares parent reference, look at this page for definition:
I had the same problem in my Application.
System.web.http.webhost not found.
You just need to copy the system.web.http.webhost
file from your main project which you run in Visual Studio and paste it into your published project bin
directory.
After this it may show the same error but the directory name is changed it may be system.web.http
. Follow same procedure as above. It will work after all the files are uploaded. This due to the nuget package in Visual Studio they download from the internet but on server it not able to download it.
You can find this file in your project bin
directory.
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
A little clarity...
// Get a PropertyInfo of specific property type(T).GetProperty(....)
PropertyInfo propertyInfo;
propertyInfo = typeof(TypeWithTheStaticProperty)
.GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static);
// Use the PropertyInfo to retrieve the value from the type by not passing in an instance
object value = propertyInfo.GetValue(null, null);
// Cast the value to the desired type
ExpectedType typedValue = (ExpectedType) value;
Try the following:
str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;
if u subtract by char '0', the ASCII value needs not to be known.
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
One technique I think is a little easier and that hasn't been mentioned before here:
var asdf = new [] {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
}.ToList();
I think that's a little cleaner than:
var asdf = new List<Tuple<int, string>> {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
};
The equivalent of .live() in 1.7 looks like this:
$(document).on('click', '#child', function() ...);
Basically, watch the document for click events and filter them for #child.
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
In WPF, you use a DispatcherTimer
.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
This is an ancient question, but the accepted answer here doesn't really get to the root of the problem.
You can solve this two ways. First with jQuery:
$(document).ready( function() { // Wait until document is fully parsed
$("#cpa-form").on('submit', function(e){
e.preventDefault();
});
})
Or without jQuery:
// Gets a reference to the form element
var form = document.getElementById('cpa-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {
e.preventDefault();
});
You don't need to use return false
to solve this problem.
->getSingleScalarResult() will return a single value, instead of an array.
On a Mac (pdftex) I managed to include a png file simply with \includegraphics[width=1.2\textwidth]{filename.png}. But in order for that to work I had to comment out the following 2 packages:
%\usepackage[dvips]{epsfig}
%\usepackage[dvips]{graphicx}
...and simply use package graphicx:
\usepackage{graphicx}
It seems [dvips] is problematic when used with pdftex.
ES6 features like promises aren't defined when targeting ES5. There are other libraries, but core-js is the javascript library that the Angular team uses. It contains polyfills for ES6.
Angular 2 has changed a lot since this question was asked. Type declarations are much easier to use in Typescript 2.0.
npm install -g typescript
For ES6 features in Angular 2, you don't need Typings. Just use typescript 2.0 or higher and install @types/core-js with npm:
npm install --save-dev @types/core-js
Then, add the TypeRoots and Types attributes to your tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"typeRoots": [
"../node_modules/@types"
],
"types" : [
"core-js"
]
},
"exclude": [
"node_modules"
]
}
This is much easier than using Typings, as explained in other answers. See Microsoft's blog post for more info: Typescript: The Future of Declaration Files
Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.
Single quotes should be used for string values like in the VALUES()
list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.
MySQL also expects DATE
and DATETIME
literal values to be single-quoted as strings like '2001-01-01 00:00:00'
. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen -
as a segment delimiter in date strings.
So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'
. NULL
is a MySQL keyword, and a special (non)-value, and is therefore unquoted.
None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).
Functions native to the RDBMS (for example, NOW()
in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.
Backtick (`) table & column ------------------------------------------------------+ ? ? ? ? ? ? ? ? ? ? ? ? $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`) VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())"; ???? ? ? ? ? ? ? ????? Unquoted keyword --------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦¦¦¦¦ Single-quoted (') strings ------------------------+ ¦ ¦ ¦¦¦¦¦ Single-quoted (') DATE --------------------------------------+ ¦¦¦¦¦ Unquoted function ---------------------------------------------+
The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).
// Same thing with some variable replacements // Here, a variable table name $table is backtick-quoted, and variables // in the VALUES list are single-quoted $query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";
When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:
// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:
ASCII:
[0-9,a-z,A-Z$_]
(basic Latin letters, digits 0-9, dollar, underscore)
You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.
Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
public void showInput() {
OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
// Must use message queue to show keyboard
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(v, 0);
}
});
}
}
};
final EditText editTextName = new EditText(this);
editTextName.setHint("Name");
editTextName.setFocusable(true);
editTextName.setClickable(true);
editTextName.setFocusableInTouchMode(true);
editTextName.setSelectAllOnFocus(true);
editTextName.setSingleLine(true);
editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
editTextName.setOnFocusChangeListener(onFocusChangeListener);
final EditText editTextPassword = new EditText(this);
editTextPassword.setHint("Password");
editTextPassword.setFocusable(true);
editTextPassword.setClickable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setSelectAllOnFocus(true);
editTextPassword.setSingleLine(true);
editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
editTextPassword.setOnFocusChangeListener(onFocusChangeListener);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(editTextName);
linearLayout.addView(editTextPassword);
DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// Done button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// Cancel button clicked
break;
}
}
};
final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
.setView(linearLayout)
.setPositiveButton("Done", alertDialogClickListener)
.setNegativeButton("Cancel", alertDialogClickListener)
.create();
editTextName.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editTextPassword.requestFocus(); // Press Return to focus next one
return false;
}
});
editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Press Return to invoke positive button on alertDialog.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
return false;
}
});
// Must set password mode after creating alert dialog.
editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
alertDialog.show();
}
Echoing Data If It Exists
Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:
{{ isset($name) ? $name : 'Default' }}
However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:
{{ $name or 'Default' }}
In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
You need to change public void klik(PaintEventArgs pea, EventArgs e)
to public void klik(object sender, System.EventArgs e)
because there is no Click
event handler with parameters PaintEventArgs pea, EventArgs e
.
April 11, 2019
None of the answers above solved my problem so I wanted to include a current solution (as of April 2019) for people using Ubuntu 18.04. This is how I solved the question above...
/usr/lib/Android/
Search for where the SDK is installed and the version. In my case it was here:
/usr/lib/Android/Sdk/build-tools/28.0.3
Note: that I am using version 28.0.3, your version may differ.
Add ANDROID_HOME
to the environment path. To do this, open /etc/environment with a text editor:
sudo nano /etc/environment
Add a line for ANDROID_HOME
for your specific version and path. In my case it was:
ANDROID_HOME="/usr/lib/Android/Sdk/build-tools/28.0.3"
Finally, source the updated environment with: source /etc/environment
Confirm this by trying: echo $ANDROID_HOME
in the terminal. You should get the path of your newly created variable.
One additionally note about sourcing, I did have to restart my computer for the VScode terminal to recognize my changes. After the restart, the environment was set and I haven't had any issues since.
Just adding information which is not present in other answers.
/proc/self/cmdline
is availableIf you are running in an environment which provides procfs and therefore has the /proc
file system available (which means this is not a portable solution), you can have Java read /proc/self/cmdline
in order to restart itself, like this:
public static void restart() throws IOException {
new ProcessBuilder(getMyOwnCmdLine()).inheritIO().start();
}
public static String[] getMyOwnCmdLine() throws IOException {
return readFirstLine("/proc/self/cmdline").split("\u0000");
}
public static String readFirstLine(final String filename) throws IOException {
try (final BufferedReader in = new BufferedReader(new FileReader(filename))) {
return in.readLine();
}
}
On systems with /proc/self/cmdline
available, this probably is the most elegant way of how to "restart" the current Java process from Java. No JNI involved, and no guessing of paths and stuff required. This will also take care of all JVM options passed to the java
binary. The command line will be exactly identical to the one of the current JVM process.
Many UNIX systems including GNU/Linux (including Android) nowadays have procfs However on some like FreeBSD, it is deprecated and being phased out. Mac OS X is an exception in the sense that it does not have procfs. Windows also does not have procfs. Cygwin has procfs but it's invisible to Java because it's only visible to applications using the Cygwin DLLs instead of Windows system calls, and Java is unaware of Cygwin.
ProcessBuilder.inheritIO()
The default is that stdin
/ stdout
/ stderr
(in Java called System.in
/ System.out
/ System.err
) of the started Process are set to pipes which allow the currently running process to communicate with the newly started process. If you want to restart the current process, this is most likely not what you want. Instead you would want that stdin
/ stdout
/ stderr
are the same as those of the current VM. This is called inherited. You can do so by calling inheritIO()
of your ProcessBuilder
instance.
A frequent use case of a restart()
function is to restart the application after an update. The last time I tried this on Windows this was problematic. When overwrote the application's .jar
file with the new version, the application started to misbehave and giving exceptions about the .jar
file. I'm just telling, in case this is your use case. Back then I solved the issue by wrapping the application in a batch file and using a magic return value from System.exit()
that I queried in the batch file and had the batch file restart the application instead.
// for numbers
a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
$.unique(a)
[7, 6, 1, 8, 3, 2, 5, 4]
// for string
a = ["a", "a", "b"]
$.unique(a)
["b", "a"]
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.
Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.
I face the same problem while installing the NetBeans but I did the installation part properly simply you have do is 1-> GO and download the JRE file of java link -> https://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html
2-> After installing the JRE kindly go to directory where you have install the JRE 3-> And copy all the file of from the JRE folder 4-> And paste in the jdk folder but 5-> while copying the file make sure you replace-and-copy the file while any prompt pop out
6-> Then open the command prompt(cmd) and simply type 7->netbeans-8.2-windows.exe --javahome "path-of-your-jdk-file"
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
window.onload will work like this:
function codeAddress() {_x000D_
document.getElementById("test").innerHTML=Date();_x000D_
}_x000D_
window.onload = codeAddress;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>learning java script</title>_x000D_
<script src="custom.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<p id="test"></p>_x000D_
<li>abcd</li>_x000D_
</body>_x000D_
</html>
_x000D_
There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD
so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:
import java.time.Instant;
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
try {
Instant myDate = Instant.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant
directly, can be done via Calendar
in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:
myDate.toString().substring(0,4);
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not
`def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = str(readfile.readlines())
Type = readlines.split(",")
x = Type[1]
y = Type[2]
for points in Type:
print(x,y)
getQuakeData()`
All depends on exactly what you mean by "special". In a regex you can specify
I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.
It might be impossible since JavaScript doesn't have Perl's "\" operator to get a primitive by reference, but there is a way to create an "effectively a pointer" object for a primitive using this pattern.
This solution makes the most sense for when you already have the primitive(so you can't put it into an object anymore without needing to modify other code), but still need to pass a pointer to it for other parts of your code to tinker with its state; so you can still tinker with its state using the seamless proxy which behaves like a pointer.
var proxyContainer = {};
// | attaches a pointer-lookalike getter/setter pair
// | to the container object.
var connect = function(container) {
// | primitive, can't create a reference to it anymore
var cant_touch_this = 1337;
// | we know where to bind our accessor/mutator
// | so we can bind the pair to effectively behave
// | like a pointer in most common use cases.
Object.defineProperty(container, 'cant_touch_this', {
'get': function() {
return cant_touch_this;
},
'set': function(val) {
cant_touch_this = val;
}
});
};
// | not quite direct, but still "touchable"
var f = function(x) {
x.cant_touch_this += 1;
};
connect(proxyContainer);
// | looks like we're just getting cant_touch_this
// | but we're actually calling the accessor.
console.log(proxyContainer.cant_touch_this);
// | looks like we're touching cant_touch_this
// | but we're actually calling the mutator.
proxyContainer.cant_touch_this = 90;
// | looks like we touched cant_touch_this
// | but we actually called a mutator which touched it for us.
console.log(proxyContainer.cant_touch_this);
f(proxyContainer);
// | we kinda did it! :)
console.log(proxyContainer.cant_touch_this);
Ensure the browser and editor are using UTF-8 encoding instead of ISO-8859-1/Windows-1252.
Or use ’
.
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
You can use --targets ARG
option where ARG is the name of textfile containing the targets for commit.
svn ci --targets myfiles.txt -m "another commit"
Just make the anchor display: block
and width/height: 100%
. Eg:
.button a {
display: block;
width: 100%;
height: 100%;
}
jsFiddle: http://jsfiddle.net/4mHTa/
Go to the directory where you have your Vagrantfile
Then, edit your Vagrantfile
and add the following:
config.vm.synced_folder ".", "/vagrant", :mount_options => ['dmode=774','fmode=775']
"." means the directory you are currently in on your host machine
"/vagrant" refers to "/home/vagrant" on the guest machine(Vagrant machine).
Copy the files you need to send to guest machine to the folder where you have your Vagrantfile
Then open Git Bash and cd
to the directory where you have your Vagrantfile
and type:
vagrant scp config.json XXXXXXX:/home/vagrant/
where XXXXXXX is your vm name. You can get your vm name by running
vagrant global-status
try this code sample, I tested it, source: http://www.makelinux.net/alp/035
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
/* Allocate a shared memory segment. */
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Determine the segment's size. */
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
/* Write a string to the shared memory segment. */
sprintf (shared_memory, "Hello, world.");
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Reattach the shared memory segment, at a different address. */
shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
/* Print out the string from shared memory. */
printf ("%s\n", shared_memory);
/* Detach the shared memory segment. */
shmdt (shared_memory);
/* Deallocate the shared memory segment. */
shmctl (segment_id, IPC_RMID, 0);
return 0;
}
With Java 8:
Comparator.comparing((Person p)->p.firstName)
.thenComparing(p->p.lastName)
.thenComparingInt(p->p.age);
If you have accessor methods:
Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge);
If a class implements Comparable then such comparator may be used in compareTo method:
@Override
public int compareTo(Person o){
return Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge)
.compare(this, o);
}
If you have Windows 10 you can use Bash on Ubuntu on Windows to install subversion.
Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.
$('#btn').click(function() {
$('#wizard').toggle();
});
Refer to the JQuery website for more information.
This can also be done without JQuery. Using only standard JavaScript:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
Then add onclick="toggle_visibility('id_of_element_to_toggle');"
to the button that is used to show and hide the div.
Here you go
var yourString = "/installers/";_x000D_
var result = yourString.substring(1, yourString.length-1);_x000D_
_x000D_
console.log(result);
_x000D_
Or you can use .slice
as suggested by Ankit Gupta
var yourString = "/installers/services/";_x000D_
_x000D_
var result = yourString.slice(1,-1);_x000D_
_x000D_
console.log(result);
_x000D_
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
The original answer from https://github.com/philipwalton/flexbugs/issues/231#issuecomment-362790042
.flex-container{
min-height:100px;
display:flex;
align-items:center;
}
.flex-container:after{
content:'';
min-height:inherit;
font-size:0;
}
Something like this:
$.getJSON("http://mywebsite.com/json/get.php?cid=15",
function(data){
$.each(data.products, function(i,product){
content = '<p>' + product.product_title + '</p>';
content += '<p>' + product.product_short_description + '</p>';
content += '<img src="' + product.product_thumbnail_src + '"/>';
content += '<br/>';
$(content).appendTo("#product_list");
});
});
Would take a json object made from a PHP array returned with the key of products. e.g:
Array('products' => Array(0 => Array('product_title' => 'Product 1',
'product_short_description' => 'Product 1 is a useful product',
'product_thumbnail_src' => '/images/15/1.jpg'
)
1 => Array('product_title' => 'Product 2',
'product_short_description' => 'Product 2 is a not so useful product',
'product_thumbnail_src' => '/images/15/2.jpg'
)
)
)
To reload the list you would simply do:
$("#product_list").empty();
And then call getJSON again with new parameters.
This problem can also come up when you don't have your constructor immediately call super.
So this will work:
public Employee(String name, String number, Date date)
{
super(....)
}
But this won't:
public Employee(String name, String number, Date date)
{
// an example of *any* code running before you call super.
if (number < 5)
{
number++;
}
super(....)
}
The reason the 2nd example fails is because java is trying to implicitely call
super(name,number,date)
as the first line in your constructor.... So java doesn't see that you've got a call to super going on later in the constructor. It essentially tries to do this:
public Employee(String name, String number, Date date)
{
super(name, number, date);
if (number < 5)
{
number++;
}
super(....)
}
So the solution is pretty easy... Just don't put code before your super call ;-) If you need to initialize something before the call to super, do it in another constructor, and then call the old constructor... Like in this example pulled from this StackOverflow post:
public class Foo
{
private int x;
public Foo()
{
this(1);
}
public Foo(int x)
{
this.x = x;
}
}
Try something like:-
ALTER TABLE table_name ADD CONSTRAINT [DF_table_name_Created]
DEFAULT (getdate()) FOR [created_at];
replacing table_name
with the name of your table.
Just add background-attachment to your code
body {
background-position: center;
background-image: url(../images/images5.jpg);
background-attachment: fixed;
}
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
Benoit's solution works, but you really don't need to incur the overhead to draw a shape. Since colors can be drawables, just define a color in a /res/values/colors.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="semitransparent_white">#77ffffff</color>
</resources>
And then use as such in your selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/semitransparent_white" />
</selector>
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
You can delete all breakpoints using
del <start_breakpoint_num> - <end_breakpoint_num>
To view the start_breakpoint_num and end_breakpoint_num use:
info break
Try this...
def is_int(x):
absolute = abs(x)
rounded = round(absolute)
return absolute - rounded == 0
You can use both Kotlin and Java files in your application.
To switch between the two files, make sure you give them unique < action android:name="" in AndroidManifest.xml, like so:
<activity android:name=".MainActivityKotlin">
<intent-filter>
<action android:name="com.genechuang.basicfirebaseproject.KotlinActivity"/>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.genechuang.basicfirebaseproject.MainActivityJava"
android:label="MainActivityJava" >
<intent-filter>
<action android:name="com.genechuang.basicfirebaseproject.JavaActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Then in your MainActivity.kt (Kotlin file), to start an Activity written in Java, do this:
val intent = Intent("com.genechuang.basicfirebaseproject.JavaActivity")
startActivity(intent)
In your MainActivityJava.java (Java file), to start an Activity written in Kotlin, do this:
Intent mIntent = new Intent("com.genechuang.basicfirebaseproject.KotlinActivity");
startActivity(mIntent);
Use WITH ORDINALITY
for set-returning functions:
When a function in the
FROM
clause is suffixed byWITH ORDINALITY
, abigint
column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such asunnest()
.
In combination with the LATERAL
feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:
SELECT t.id, a.elem, a.nr
FROM tbl AS t
LEFT JOIN LATERAL unnest(string_to_array(t.elements, ','))
WITH ORDINALITY AS a(elem, nr) ON TRUE;
LEFT JOIN ... ON TRUE
preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL
:
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);
Or simpler if based off an actual array (arr
being an array column):
SELECT t.id, a.elem, a.nr
FROM tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);
Or even, with minimal syntax:
SELECT id, a, ordinality
FROM tbl, unnest(arr) WITH ORDINALITY a;
a
is automatically table and column alias. The default name of the added ordinality column is ordinality
. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.
With row_number() OVER (PARTITION BY id ORDER BY elem)
you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.
You can simply omit ORDER BY
:
SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;
While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY
. It happens to work due to an implementation detail.
To guarantee ordinal numbers of elements in the blank-separated string:
SELECT id, arr[nr] AS elem, nr
FROM (
SELECT *, generate_subscripts(arr, 1) AS nr
FROM (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
) sub;
Or simpler if based off an actual array:
SELECT id, arr[nr] AS elem, nr
FROM (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;
Related answer on dba.SE:
None of these features are available, yet: RETURNS TABLE
, generate_subscripts()
, unnest()
, array_length()
. But this works:
CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:
CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
RETURNS SETOF record
LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
FROM generate_series(array_lower($1,1), array_upper($1,1)) i';
SELECT id, arr, (rec).*
FROM (
SELECT *, f_unnest_ord_idx(arr) AS rec
FROM (VALUES (1, '{a,b,c}'::text[]) -- short for: '[1:3]={a,b,c}'
, (2, '[5:7]={a,b,c}')
, (3, '[-9:-7]={a,b,c}')
) t(id, arr)
) sub;
id | arr | val | ordinality | idx
----+-----------------+-----+------------+-----
1 | {a,b,c} | a | 1 | 1
1 | {a,b,c} | b | 2 | 2
1 | {a,b,c} | c | 3 | 3
2 | [5:7]={a,b,c} | a | 1 | 5
2 | [5:7]={a,b,c} | b | 2 | 6
2 | [5:7]={a,b,c} | c | 3 | 7
3 | [-9:-7]={a,b,c} | a | 1 | -9
3 | [-9:-7]={a,b,c} | b | 2 | -8
3 | [-9:-7]={a,b,c} | c | 3 | -7
Compare:
I had the same error after I posted a form of mine. they have a space in to my input name attributes. input name=' first_name'
Fixing that got rid of the error.
Please use the following
ddlCity.Items.Clear();
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.
By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:
@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });
Instead, in your GET Action method, the following needs to be done:
model.SomeBooleanProperty = true;
The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).
However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.
@Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });
UPDATE
//Get Method
public ActionResult CreateUser(int id)
{
model.SomeBooleanProperty = true;
}
Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.
As you specify in your attrs.xml
your adSize attribute belongs to the namespace com.google.ads.AdView
. Try to change:
android:adUnitId="a14bd6d2c63e055" android:adSize="BANNER"
to
ads:adUnitId="a14bd6d2c63e055" ads:adSize="BANNER"
and it should work.
In package.json
set the following command (example for running on port 82)
"start": "set PORT=82 && ng serve --ec=true"
then npm start
Simply use the Get-Content
and Set-Content
cmdlets:
Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt
You can concatenate more than two files with this style, too.
If the source files are named similarly, you can use wildcards:
Get-Content inputFile*.txt | Set-Content joinedFile.txt
Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat
and sc
for Get-Content
and Set-Content
respectively. However, these aliases are problematic because cat
is a system command in *nix systems, and sc
is a system command in Windows systems - therefore using them is not recommended, and in fact sc
is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.
Note 2: Be careful with wildcards - if you try to output to examples.txt
(or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)
Note 3: Outputting to a file with >
does not preserve character encoding! This is why using Set-Content
is recommended.
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
You can not make reference to static variable from non-static method. To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only. Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.
interface MyProps {
text: string;
optionalText?: string;
}
const defaultProps = {
optionalText = "foo";
}
const MyComponent = (props: MyProps) => {
props = { ...defaultProps, ...props }
}
This marks the session as Abandoned, but the session won't actually be Abandoned at that moment, the request has to complete first.
here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html
You can read also that Thomas Weingartner wrote:
Timeout: SqlException.Number == -2 (This is an ADO.NET error code)
General Network Error: SqlException.Number == 11
Deadlock: SqlException.Number == 1205 (This is an SQL Server error code)
...
We handle the "General Network Error" as a timeout exception too. It only occurs under rare circumstances e.g. when your update/insert/delete query will raise a long running trigger.
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
#div {
top: 50%;
left: 50%;
position:fixed;
}
just set the above three properties any of your element and there you Go!
Your div is exactly at the center of the screen
Its problem at bitbucket's end.
You can check status of their services at http://status.bitbucket.org/
Currently there is HTTPS
outage at bitbucket. see below
You can use SSH
option. I just used SSH
option with sourcetree
.
You use the available API of JTable
and do not try to mess with the colors.
Some selection methods are available directly on the JTable
(like the setRowSelectionInterval
). If you want to have access to all selection-related logic, the selection model is the place to start looking
A very quick solution to have dynamic style with an external css stylesheet, in case you are using the <object>
tag to embed your svg.
This example will add a class to the root <svg>
tag on click on a parent element.
file.svg :
<?xml-stylesheet type="text/css" href="../svg.css"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="">
<g>
<path/>
</g>
</svg>
html :
<a class="parent">
<object data="file.svg"></object>
</a>
Jquery :
$(function() {
$(document).on('click', '.parent', function(){
$(this).find('object').contents().find('svg').attr("class","selected");
}
});
on click parent element :
<svg xmlns="http://www.w3.org/2000/svg" viewBox="" class="selected">
then you can manage your css
svg.css :
path {
fill:none;
stroke:#000;
stroke-miterlimit:1.41;
stroke-width:0.7px;
}
.selected path {
fill:none;
stroke:rgb(64, 136, 209);
stroke-miterlimit:1.41;
stroke-width:0.7px;
}
The error says that there is a mismatch, assuming that you have a common contract based on the same WSDL, then the mismatch is in the configuration.
For example that the client is using nettcpip and the server is set up to use basic http.
There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....
What is the copy-and-swap idiom?
A way of implementing the assignment operator in terms of a swap function:
X& operator=(X rhs)
{
swap(rhs);
return *this;
}
The fundamental idea is that:
the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)
that acquisition can be attempted before modifying the current state of the object (i.e. *this
) if a copy of the new value is made, which is why rhs
is accepted by value (i.e. copied) rather than by reference
swapping the state of the local copy rhs
and *this
is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)
When should it be used? (Which problems does it solve [/create]?)
When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap
with strong exception guarantee, and ideally one that can't fail/throw
..†
When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap
and destructor functions.
† swap
throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp;
and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string
's as James comments on another answer:
@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24
‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x);
code where f
is (perhaps only for some #ifdef
branches) a macro ala #define f(x) x
or a function returning a reference to x
, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;
). For example:
struct X
{
T* p_;
size_t size_;
X& operator=(const X& rhs)
{
delete[] p_; // OUCH!
p_ = new T[size_ = rhs.size_];
std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
}
...
};
On self-assignment, the above code delete's x.p_;
, points p_
at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy
attempts a self-assignment to every just-destructed 'T'!
? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):
struct Client
{
IP_Address ip_address_;
int socket_;
X(const X& rhs)
: ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
{ }
};
Here, a hand-written Client::operator=
might check if *this
is already connected to the same server as rhs
(perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).
If you want to avoid modulo, you can also use a combination of the four basic operations :)
26 - (26 // 7 * 7) = 5
Yes, and unfortunately you cannot turn them off, or any other special characters. The options under \View\Show Symbols only turns on or off things like tabs, spaces, EOL, etc. So if you want to read some obscure coding with text in it - you actually need to look elsewhere. I also looked at changing the coding, ASCII is not listed, and that would not make the mess invisible anyway.
As an adaption of @Mike Fuchs answer, here's an even smaller solution. I'm using the Fody.AutoDependencyPropertyMarker
to reduce some of the boiler plate.
The Class
public class EventCommand : TriggerAction<DependencyObject>
{
[AutoDependencyProperty]
public ICommand Command { get; set; }
protected override void Invoke(object parameter)
{
if (Command != null)
{
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
}
The EventArgs
public class VisibleBoundsArgs : EventArgs
{
public Rect VisibleVounds { get; }
public VisibleBoundsArgs(Rect visibleBounds)
{
VisibleVounds = visibleBounds;
}
}
The XAML
<local:ZoomableImage>
<i:Interaction.Triggers>
<i:EventTrigger EventName="VisibleBoundsChanged" >
<local:EventCommand Command="{Binding VisibleBoundsChanged}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</local:ZoomableImage>
The ViewModel
public ICommand VisibleBoundsChanged => _visibleBoundsChanged ??
(_visibleBoundsChanged = new RelayCommand(obj => SetVisibleBounds(((VisibleBoundsArgs)obj).VisibleVounds)));
<%! String username=(String)session.getAttribute("username"); %>
form action="editinfo" method="post">
<table>
<tr>
<td>Username: </td><td> <input type="text" value="<%=username %>" /> </td>
</tr>
</table>
add <%! String username=(String)session.getAttribute("username"); %>
The simple way is to, Edit your migration file (cascadeDelete: true)
into (cascadeDelete: false)
then after assign the Update-Database command in your Package Manager Console.if it's problem with your last migration then all right. Otherwise check your earlier migration history, copy those things, paste into your last migration file, after that do it the same thing. it perfectly works for me.
You can use android:weightSum="2"
on the parent layout combined with android:layout_height="1"
on the child layout.
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:weightSum="2"
>
<ImageView
android:layout_height="1"
android:layout_width="wrap_content" />
</LinearLayout>
Something like this should work
CSS:
input {
float: left;
clear: left;
width: 50px;
line-height: 20px;
}
label {
float: left;
vertical-align: middle;
}
This is probably a habit learned from C, to avoid this sort of typo (single =
instead of a double ==
):
if (object = null) {
The convention of putting the constant on the left side of ==
isn't really useful in Java since Java requires that the expression in an if
evaluate to a boolean
value, so unless the constant is a boolean
, you'd get a compilation error either way you put the arguments. (and if it is a boolean, you shouldn't be using ==
anyway...)
The only difference between the two elements is semantics. Both elements, by default, have the CSS rule display: block (hence block-level) applied to them; nothing more (except somewhat extra margin in some instances). However, as aforementioned, they both different greatly in terms of semantics.
The <p>
element, as its name somewhat implies, is for paragraphs. Thus, <p>
should be used when you want to create blocks of paragraph text.
The <div>
element, however, has little to no meaning semantically and therefore can be used as a generic block-level element — most commonly, people use it within layouts because it is meaningless semantically and can be used for generally anything you might require a block-level element for.
One can also use nvtop
, which gives an interface very similar to htop
, but showing your GPU(s) usage instead, with a nice graph.
You can also kill processes directly from here.
Here is a link to its Github : https://github.com/Syllo/nvtop
It's better to add "overrides" in your .eslintrc.js config file. For example if you wont to disable camelcase rule for all js files ending on Actions add this code after rules scope in .eslintrc.js.
"rules": {
...........
},
"overrides": [
{
"files": ["*Actions.js"],
"rules": {
"camelcase": "off"
}
}
]
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
why not just ng-checked="true"
Just fyi . This is available as nuget package in visual studio environment. Please let me know if you need more information as I have used it. URL can be found Link to nuget
You can also find some information here. Blog with more details
If you need to hyperlink Sheet1 to all or corresponding sheets, then use simple vba code. If you wish to create a radio button, then assign this macro to that button ex "Home Page".
Here is it:
Sub HomePage()
'
' HomePage Macro
'
' This is common code to go to sheet 1 if do not change name for Sheet1
'Sheets("Sheet1").Select
' OR
' You can write you sheet name here in case if its name changes
Sheets("Monthly Reports Home").Select
Range("A1").Select
End Sub
Another case of this: Messing with the __repr__
function of an object where a format()
call fails non-transparently.
In our case, we used a @property
decorator on the __repr__
and passed that object to a format()
. The @property
decorator causes the __repr__
object to be turned into a string, which then results in the str
object is not callable error.
[STAThread]
static void Main() // args are OK here, of course
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important!
}
From: Ensuring a single instance of .NET Application
and: Single Instance Application Mutex
Same answer as @Smink and @Imjustpondering with a twist:
Jon Skeet's FAQ on C# to find out why GC.KeepAlive matters
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
This is how I do it:
df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)
Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.
Since version 1.3.0
AngularJS introduced extra filter parameter timezone
, like following:
{{ date_expression | date : format : timezone}}
But in versions 1.3.x
only supported timezone is UTC
, which can be used as following:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
Since version 1.4.0-rc.0
AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
Here you can find documentation of AngularJS date filters.
NOTE: this is working only with Angular 1.x
Here's working example
As a sidenote, have in mind that in other cases a codebase might use a border-bottom
css attribute, for example border-bottom: 1px;
, that creates an effect very similar to the text-decoration: underline
. In that case make sure that you set it to none, border-bottom: none;
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
While : your condition is at the begin of the loop block, and makes possible to never enter the loop.
Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.
You should use the for
command, here is an example:
@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"
and you can use call :output "Command goes here"
then the output will be in the %output%
variable.
Note: If you have a command output that is multiline, this tool will set
the output to the last line of your multiline command.
Depends on what you mean by emptying. If you just want an empty string, you could do
buffer[0] = 0;
If you want to set every element to zero, do
memset(buffer, 0, 80);
First run
import pip
pip.__version__
If the result is '10.0.0', then it means that you installed pip successfully
since pip 10.0.0 doesn't support pip.main() any more, you may find this helpful
https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program
Use something like
import subprocess
subprocess.check_call(["python", '-m', 'pip', 'install', 'pkg']) # install pkg
subprocess.check_call(["python", '-m', 'pip', 'install',"--upgrade", 'pkg']) # upgrade pkg
Edit: pip 10.0.1 still doesn't support main
You can choose to DOWNGRADE your pip version via following command:
python -m pip install --upgrade pip==9.0.3
Here is a lattice version:
library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
Use this method to check the network state:
private void checkInternetConnection() {
if (br == null) {
br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("TEST Internet", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver((BroadcastReceiver) br, intentFilter);
}
}
remember to unregister service in onDestroy.
Cheers!!
First Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Second way:
You created an empty file with the desired name, which then prevented you from creating the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Third way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fourth Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fifth way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Correct way:
File
for your desired directory (e.g., File path=new File(getFilesDir(),"myfolder");
)mkdirs()
on that File
to create the directory if it does not existFile
for the output file (e.g., File mypath=new File(path,"myfile.txt");
)File
(e.g., using new BufferedWriter(new FileWriter(mypath))
)I'm not sure it's worth it for me to type this all up from scratch since this article published in A List Apart does a pretty good job explaining it. MDN also has a handy guide for HTML5 forms and validation (covering the API and also the related CSS).
to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426
http://api.jquery.com/val/#val2
about val()
Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.
On the 16 vs 15 byte-count padding front, the actual number you need to add to get an alignment of N is max(0,N-M) where M is the natural alignment of the memory allocator (and both are powers of 2).
Since the minimal memory alignment of any allocator is 1 byte, 15=max(0,16-1) is a conservative answer. However, if you know your memory allocator is going to give you 32-bit int aligned addresses (which is fairly common), you could have used 12 as a pad.
This isn't important for this example but it might be important on an embedded system with 12K of RAM where every single int saved counts.
The best way to implement it if you're actually going to try to save every byte possible is as a macro so you can feed it your native memory alignment. Again, this is probably only useful for embedded systems where you need to save every byte.
In the example below, on most systems, the value 1 is just fine for MEMORY_ALLOCATOR_NATIVE_ALIGNMENT
, however for our theoretical embedded system with 32-bit aligned allocations, the following could save a tiny bit of precious memory:
#define MEMORY_ALLOCATOR_NATIVE_ALIGNMENT 4
#define ALIGN_PAD2(N,M) (((N)>(M)) ? ((N)-(M)) : 0)
#define ALIGN_PAD(N) ALIGN_PAD2((N), MEMORY_ALLOCATOR_NATIVE_ALIGNMENT)
Use the apache commons-lang3 lib
import org.apache.commons.lang3.exception.ExceptionUtils;
//...
String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
The method
setParams()
like
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
only adds HttpProtocol parameters.
To execute the httpGet you should append your parameters to the url manually
HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo¶m2=bar");
or use the post request the difference between get and post requests are explained here, if you are interested
Try:
alias lock='gnome-screensaver; gnome-screensaver-command --lock'
or
lock() {
gnome-screensaver
gnome-screensaver-command --lock
}
in your .bashrc
The second solution allows you to use arguments.
Well, as you are just looking to match the position of a character , regex is possibly overkill.
I presume all you want is, instead of "find first of these this character" , just find first of these characters.
This of course is the simple answer, but does what your question sets out to do, albeit without the regex part ( because you didn't clarify why specifically it had to be a regex )
function mIndexOf( str , chars, offset )
{
var first = -1;
for( var i = 0; i < chars.length; i++ )
{
var p = str.indexOf( chars[i] , offset );
if( p < first || first === -1 )
{
first = p;
}
}
return first;
}
String.prototype.mIndexOf = function( chars, offset )
{
return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching.
};
mIndexOf( "hello world", ['a','o','w'], 0 );
>> 4
mIndexOf( "hello world", ['a'], 0 );
>> -1
mIndexOf( "hello world", ['a','o','w'], 4 );
>> 4
mIndexOf( "hello world", ['a','o','w'], 5 );
>> 6
mIndexOf( "hello world", ['a','o','w'], 7 );
>> -1
mIndexOf( "hello world", ['a','o','w','d'], 7 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 10 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 11 );
>> -1
Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
More on wordpress.org:
TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple
and Pear
don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean
member. Because of structural typing, you don' need to inherit Apple
and Pear
from such an interface.
There are different ways to assign such a compatible type:
Assign type during variable declaration
This statement is implicitly typed to Apple[] | Pear[]
:
const fruits = fruitBasket[key];
You can simply use a compatible type explicitly in in your variable declaration:
const fruits: { isDecayed: boolean }[] = fruitBasket[key];
For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple
and Pear
interfaces don't need to be changed):
type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];
Cast to compatible type for the operation
The problem with the given solution is that it changes the type of the fruits
variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits
:
const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
Or with the reusable Fruit
type:
type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
The advantage of this solution is that both, fruits
and freshFruits
will be of type Apple[] | Pear[]
.
default_keys = [1, "name"]
To get dictionary with None as values:
dict.fromkeys(default_keys)
Output :
{1: None, 'name': None}
To get dictionary with default values:
dict.fromkeys(default_keys, [])
Output :
{1: [], 'name': []}
For me this error was solved by ensuring the app containing the tasks was included under django's INSTALLED_APPS setting.
This might help someone who use Zend_Oauth_Client to work with twitter api. This working config:
$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('accessToken');
$accessToken->setTokenSecret('accessTokenSecret');
$client = $accessToken->getHttpClient(array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0', // it was 1.1 and I got 215 error.
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => 'foo',
'consumerSecret' => 'bar',
'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
'timeout' => 30
));
It look like twitter api 1.0 allows oauth version to be 1.1 and 1.0, where twitter api 1.1 require only oauth version to be 1.0.
P.S We do not use Zend_Service_Twitter as it does not allow send custom params on status update.
You seem to misuse vim, but that's likely due to not being very familiar with it.
The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.
Here's a couple of use-cases:
But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.
Use display:none
to not show the items, then with JQuery you can use fadeIn()
and fadeOut()
to hide/unhide the elements.
If you don't want to use jquery, use this:
<script>
// without jquery
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
// run your open popup function after 5 sec = 5000
PopUp();
}, 5000)
});
</script>
OR With jquery
<script>
$(document).ready(function(){
setTimeout(function(){
// open popup after 5 seconds
PopUp();
},5000);
});
</script>
I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp
Xcode provides CFNetwork Diagnostic Logging. Apple doc
To enable it, add CFNETWORK_DIAGNOSTICS=3
in the Environment Variable section:
This will show requests from the App with its headers & body. Note that OS_ACTIVITY_MODE
must be set to enable
as shown. Otherwise no output will be shown on the Console.
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
As with any other python script, you may specify the python installation you'd like to run it with. You may put this in your shell profile to save the alias. The $1
refers to the first argument you pass to the script.
# PYTHON3 PIP INSTALL V2
alias pip_install3="python3 -m $(which pip) install $1"
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
Following your example code, try making a subclass of AbstractThing
without implementing the m2
method and see what errors the compiler gives you. It will force you to implement this method.
You can do like this
DELETE FROM table WHERE id NOT IN ( 2 )
OR
DELETE FROM table WHERE id <> 2
As @Frank Schmitt noted, you might want to be careful about the NULL values too. If you want to delete everything which is not 2
(including the NULLs) then add OR id IS NULL
to the WHERE clause.
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
You get this message when you've used async in your template, but are referring to an object that isn't an Observable.
So for examples sake, lets' say I had these properties in my class:
job:Job
job$:Observable<Job>
Then in my template, I refer to it this way:
{{job | async }}
instead of:
{{job$ | async }}
You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.
Steps using XAMPP GUI:
Step-1: Click on Config button
Step-2: Click on Service and Port Settings button
Final step: Change your port and Save
This probably will solve your problem:
<?php print_r(array_rand(range(1,50), 5)); ?>
Html:
@using (Html.BeginForm("StoreMyCompany", "MyCompany", FormMethod.Post, new { id = "formMyCompany", enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(model => model.modelMyCompany.Logo, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
<input type="file" name="Logo" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-offset-3 col-md-6">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
}
Code Behind:
public ActionResult StoreMyCompany([Bind(Exclude = "Logo")]MyCompanyVM model)
{
try
{
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase objFiles = Request.Files["Logo"];
using (var binaryReader = new BinaryReader(objFiles.InputStream))
{
imageData = binaryReader.ReadBytes(objFiles.ContentLength);
}
}
if (imageData != null && imageData.Length > 0)
{
//Your code
}
dbo.SaveChanges();
return RedirectToAction("MyCompany", "Home");
}
catch (Exception ex)
{
Utility.LogError(ex);
}
return View();
}
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
if ( ($name eq "tom" and $password eq "123!")
or ($name eq "frank" and $password eq "321!")) {
print "You have gained access.";
}
else {
print "Access denied!";
}
I was challenged by the same error message, with .net 4.7 installed.
The solution was to follow one earlier mentioned post to go with the "Turn Windows feature on or off", where the ".NET Framework 4.7 Advanced Services" --> "ASP.NET 4.7" already was checked.
Further down the list, there is the "Internet Information Services" and subnote "Application Development Features" --> "ASP.NET 4.7", that also needs to be checked.
When enabling this, allot of other features are enabled... I simply pressed the Ok button, and the issue was resolved. Screendump of the windows features dialog
UPDATE `MySQL_Table`
SET `MySQL_Table_Column` = REPLACE(`MySQL_Table_Column`, 'oldString', 'newString')
WHERE `MySQL_Table_Column` LIKE 'oldString%';
I got similar error msgs. I run svn clean-up, and then tried "get clock" for a few times. Then this error was gone.
You can try this. Override the OnPaint event of the TextBox.
protected override void OnPaint(PaintEventArgs e)
{
SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
// Draw string to screen.
e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}
set the ControlStyles to "UserPaint"
public MyTextBox()//constructor
{
// This call is required by the Windows.Forms Form Designer.
this.SetStyle(ControlStyles.UserPaint,true);
InitializeComponent();
// TODO: Add any initialization after the InitForm call
}
Or you can try this hack
In Enter event set the focus
int index=this.Controls.IndexOf(this.textBox1);
this.Controls[index-1].Focus();
So your control will not focussed and behave like disabled.
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
The below code not only shows how to do it, but also puts it in an easy to use function moving forward. It was written by "jesda". (I found it online)
PHP Code:
<?php
/* strpos that takes an array of values to match against a string
* note the stupid argument order (to match strpos)
*/
function strpos_arr($haystack, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false) return $pos;
}
return false;
}
?>
Usage:
$needle = array('something','nothing');
$haystack = "This is something";
echo strpos_arr($haystack, $needle); // Will echo True
$haystack = "This isn't anything";
echo strpos_arr($haystack, $needle); // Will echo False
I Created this simple program to get HSV Codes in realtime
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
def nothing(x):
pass
# Creating a window for later use
cv2.namedWindow('result')
# Starting with 100's to prevent error while masking
h,s,v = 100,100,100
# Creating track bar
cv2.createTrackbar('h', 'result',0,179,nothing)
cv2.createTrackbar('s', 'result',0,255,nothing)
cv2.createTrackbar('v', 'result',0,255,nothing)
while(1):
_, frame = cap.read()
#converting to HSV
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
# get info from track bar and appy to result
h = cv2.getTrackbarPos('h','result')
s = cv2.getTrackbarPos('s','result')
v = cv2.getTrackbarPos('v','result')
# Normal masking algorithm
lower_blue = np.array([h,s,v])
upper_blue = np.array([180,255,255])
mask = cv2.inRange(hsv,lower_blue, upper_blue)
result = cv2.bitwise_and(frame,frame,mask = mask)
cv2.imshow('result',result)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)
To make a custom "browse button" solution simply try making a hidden browse button, a custom button or element and some Jquery. This way I'm not modifying the actual "browse button" which is dependent on each browser/version. Here's an example.
HTML:
<div id="import" type="file">My Custom Button</div>
<input id="browser" class="hideMe" type="file"></input>
CSS:
#import {
margin: 0em 0em 0em .2em;
content: 'Import Settings';
display: inline-block;
border: 1px solid;
border-color: #ddd #bbb #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
font-weight: 700;
font: bold 12px/1.2 Arial,sans-serif !important;
/* fallback */
background-color: #f9f9f9;
/* Safari 4-5, Chrome 1-9 */
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#C2C1C1), to(#2F2727));
}
.hideMe{
display: none;
}
JS:
$("#import").click(function() {
$("#browser").trigger("click");
$('#browser').change(function() {
alert($("#browser").val());
});
});
If you have mysql install in your windows 10 try uninstall every myqsl app from your computer. Its work for me. exactly when i installed the mysql in my computer gulp command and some other commands stop working and then i have tried everything but not nothing worked for me.
If you are limited to ES6, the best option is Promise all. Promise.all(array)
also returns an array of promises after successfully executing all the promises in array
argument.
Suppose, if you want to update many student records in the database, the following code demonstrates the concept of Promise.all in such case-
let promises = students.map((student, index) => {
//where students is a db object
student.rollNo = index + 1;
student.city = 'City Name';
//Update whatever information on student you want
return student.save();
});
Promise.all(promises).then(() => {
//All the save queries will be executed when .then is executed
//You can do further operations here after as all update operations are completed now
});
Map is just an example method for loop. You can also use for
or forin
or forEach
loop. So the concept is pretty simple, start the loop in which you want to do bulk async operations. Push every such async operation statement in an array declared outside the scope of that loop. After the loop completes, execute the Promise all statement with the prepared array of such queries/promises as argument.
The basic concept is that the javascript loop is synchronous whereas database call is async and we use push method in loop that is also sync. So, the problem of asynchronous behavior doesn't occur inside the loop.
Go to File > Preferences > Settings
(or press Ctrl+,) then click the leftmost icon in the top right corner, "Open Settings (JSON)"
In the JSON settings window, add this (within the curly braces {}
):
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\bash.exe"`
(Here you can put any other custom settings you want as well)
Checkout that path to make sure your bash.exe file is there otherwise find out where it is and point to that path instead.
Now if you open a new terminal window in VS Code, it should open with bash instead of PowerShell.
Trying all mentioned here, I found curl-loader as best for my purposes. very easy interface, real-time monitoring, useful statistics, from which I build graphs of performance. All features of libcurl are included.
As an additional info: BOOT_COMPLETE is sent to applications before external storage is mounted. So if application is installed to external storage it won't receive BOOT_COMPLETE broadcast message.
More details here in section Broadcast Receivers listening for "boot completed"
You need mask
:
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
Another solution with loc
and boolean indexing
:
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
Sample:
import pandas as pd
import numpy as np
sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
PR
0 10
1 100
2 40
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
PR
0 NaN
1 100.0
2 NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
PR
0 NaN
1 100.0
2 NaN
EDIT:
Solution with apply
:
sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)
Timings len(df)=300k
:
sample = pd.concat([sample]*100000).reset_index(drop=True)
In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop
In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop
Sometimes I've made an unrelated change on my branch before I've committed it, and I want to move it to another branch and commit it separately (like master). I do this:
git stash
git checkout master
git stash pop
git add <files that you want to commit>
git commit -m 'Minor feature'
git stash
git checkout topic1
git stash pop
...<resume work>...
Note the first stash
& stash pop
can be eliminated, you can carry all of your changes over to the master
branch when you checkout, but only if there are no conflicts. Also if you are creating a new branch for the partial changes you will need the stash.
You can simplify it assuming no conflicts and no new branch:
git checkout master
git add <files that you want to commit>
git commit -m 'Minor feature'
git checkout topic1
...<resume work>...
Stash not even needed...
def rolling_window(list, degree):
for i in range(len(list)-degree+1):
yield [list[i+o] for o in range(degree)]
Made this for a rolling average function
For Django versions > 1.10, according to the documentation, a custom MIDDLEWARE can be written as a function, let's say in the file: yourproject/middleware.py
(as a sibling of settings.py
):
def open_access_middleware(get_response):
def middleware(request):
response = get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
return response
return middleware
and finally, add the python path of this function (w.r.t. the root of your project) to the MIDDLEWARE list in your project's settings.py
:
MIDDLEWARE = [
.
.
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'yourproject.middleware.open_access_middleware'
]
Easy peasy!
Thanks to the references shared here and elsewhere, I've made an online script / tool that one can use to obtain all videos of a channel.
It combines API calls to youtube.channels.list
, playlistItems
, videos
. It uses recursive functions to make the asynchronous callbacks run the next iteration upon getting a valid response.
This also serves to limit the actual number of requests made at a time, hence keeping you safe from violating YouTube API rules. Sharing shortened snippets and then a link to the full code. I got around the 50 max results per call limitation by using the nextPageToken value that comes in the response to fetch the next 50 results and so on.
function getVideos(nextPageToken, vidsDone, params) {
$.getJSON("https://www.googleapis.com/youtube/v3/playlistItems", {
key: params.accessKey,
part: "snippet",
maxResults: 50,
playlistId: params.playlistId,
fields: "items(snippet(publishedAt, resourceId/videoId, title)), nextPageToken",
pageToken: ( nextPageToken || '')
},
function(data) {
// commands to process JSON variable, extract the 50 videos info
if ( vidsDone < params.vidslimit) {
// Recursive: the function is calling itself if
// all videos haven't been loaded yet
getVideos( data.nextPageToken, vidsDone, params);
}
else {
// Closing actions to do once we have listed the videos needed.
}
});
}
This got a basic listing of the videos, including id, title, date of publishing and similar. But to get more detail of each video like view counts and likes, one has to make API calls to videos
.
// Looping through an array of video id's
function fetchViddetails(i) {
$.getJSON("https://www.googleapis.com/youtube/v3/videos", {
key: document.getElementById("accesskey").value,
part: "snippet,statistics",
id: vidsList[i]
}, function(data) {
// Commands to process JSON variable, extract the video
// information and push it to a global array
if (i < vidsList.length - 1) {
fetchViddetails(i+1) // Recursive: calls itself if the
// list isn't over.
}
});
See the full code here, and live version here. (Edit: fixed github link)
Edit: Dependencies: JQuery, Papa.parse
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
http://jsperf.com/best-of-string-to-number-conversion/2
Implicit
marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
An application is CPU-bound when the arithmetic/logical/floating-point (A/L/FP) performance during the execution is mostly near the theoretical peak-performance of the processor (data provided by the manufacturer and determined by the characteristics of the processor: number of cores, frequency, registers, ALUs, FPUs, etc.).
The peek performance is very difficult to be achieved in real-world applications, for not saying impossible. Most of the applications access memory in different parts of the execution and the processor is not doing A/L/FP operations during several cycles. This is called Von Neumann Limitation due to the distance that exists between the memory and the processor.
If you want to be near the CPU peak-performance a strategy could be to try to reuse most of the data in the cache memory in order to avoid requiring data from the main memory. An algorithm that exploits this feature is the matrix-matrix multiplication (if both matrices can be stored in the cache memory). This happens because if the matrices are size n x n
then you need to do about 2 n^3
operations using only 2 n^2
FP numbers of data. On the other hand matrix addition, for example, is a less CPU-bound or a more memory-bound application than the matrix multiplication since it requires only n^2
FLOPs with the same data.
In the following figure the FLOPs obtained with a naive algorithms for the matrix addition and the matrix multiplication in an Intel i5-9300H, is shown:
Note that as expected the performance of the matrix multiplication in bigger than the matrix addition. These results can be reproduced by running test/gemm
and test/matadd
available in this repository.
I suggest also to see the video given by J. Dongarra about this effect.
Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:
this.http.get('...')
.map(res => <Product[]>res.json());
See these questions:
You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:
this.http.get('...')
.map(res => {
var data = res.json();
return data.map(d => {
return new Product(d.productNumber,
d.productName, d.productDescription);
});
});
Use spring-boot:run command to start spring boot application:
Precondition: 1. Add following property to pom.xml
<property>
<start-class>com.package.name.YourApplicationMainClass</start-class>
</property>
2. Build your project
Then configure maven command with spring-boot:run.
Right Click Project | Run As | Run Configuration... | Add new Maven Configuration with command spring-boot:run
Fortunately a solution exists. You must add a wrapper for parent and change z-index of this wrapper for example 10, and set z-index for child to -1:
.parent {_x000D_
position: relative;_x000D_
width: 750px;_x000D_
height: 7150px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
z-index: initial;_x000D_
}_x000D_
_x000D_
.child {_x000D_
position: relative;_x000D_
background-color: blue;_x000D_
z-index: -1;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
position: relative;_x000D_
background: green;_x000D_
z-index: 10;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">parent parent_x000D_
<div class="child">child child child</div>_x000D_
</div>_x000D_
</div>
_x000D_
Try this for Windows:
npm uninstall -g cordova
Try this for MAC:
sudo npm uninstall -g cordova
You can also add Cordova like this:
If You Want To install the previous version of Cordova through the Node Package Manager (npm):
npm install -g [email protected]
If You Want To install the latest version of Cordova:
npm install -g cordova
Enjoy!
Original article: https://helpdeskgeek.com/networking/simulate-slow-internet-connection-testing/
Simulate Slow Connection using Chrome Go ahead and install Chrome if you don’t already have it installed on your system. Once you do, open a new tab and then press CTRL + SHIFT + I to open the developer tools window or click on the hamburger icon, then More tools and then Developer tools.
This will bring up the Developer Tools window, which will probably be docked on the right side of the screen. I prefer it docked at the bottom of the screen since you can see more data. To do this, click on the three vertical dots and then click on the middle dock position.
Now go ahead and click on the Network tab. On the right, you should see a label called No Throttling.
If you click on that, you’ll get a dropdown list of a pre-configured speed that you can use to simulate a slow connection.
The choices range from Offline to WiFi and the numbers are shown as Latency, Download, Upload. The slowest is GPRS followed by Regular 2G, then Good 2G, then Regular 3G, Good 3G, Regular 4G, DSL and then WiFi. Pick one of the options and then reload the page you are on or type in another URL in the address bar. Just make sure you are in the same tab where the developer tools are being displayed. The throttling only works for the tab you have it enabled for.
If you want to use your own specific values, you can click the Add button under Custom. Click on the Add Custom Profile button to add a new profile.
When using GPRS, it took www.google.com a whopping 16 seconds to load! Overall, this is a great tool that is built right into Chrome that you can use for testing your website load time on slower connections. If you have any questions, feel free to comment. Enjoy!
If you can, use boost shared_ptr and standard C++ auto_ptr. Those convey ownership semantics.
When you return an auto_ptr, you are telling the caller that you are giving them ownership of the memory.
When you return a shared_ptr, you are telling the caller that you have a reference to it and they take part of the ownership, but it isn't solely their responsibility.
These semantics also apply to parameters. If the caller passes you an auto_ptr, they are giving you ownership.
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github
sample output:
shm attach process list, group by shm key
##################################################################
0x2d5feab4: /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c: /home/curu/playd
0x77da6cfe: /home/curu/mem_dumper /home/curu/playd /home/curu/scand
##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]: 0x2d5feab4 0x77da6cfe
/home/curu/playd [3]: 0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]: 0x77da6cfe
Another solution is to mix valueChangeListener, ajax and process:
<p:selectManyCheckbox id="employees" value="#{employees}" columns="1" layout="grid" valueChangeListener="#{mybean.fireSelection}" >
<f:selectItems var="employee" value="#{employeesSI}" />
<p:ajax event="valueChange" immediate="true" process="@this"/>
</p:selectManyCheckbox>
Method in mybean is just :
public void fireSelection(ValueChangeEvent event) {
log.debug("New: "+event.getNewValue()+", Old: "+event.getOldValue());
}
Like this, valueChangeEvent is very light !
PS: Works fine with PrimeFaces 5.0
Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:
void caluculate(Person p){
p.dotheCalculate();
}
This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.
In my project I am using the following syntax in my app.component.html:
<img src="/assets/img/1.jpg" alt="image">
or
<img src='http://mruanova.com/img/1.jpg' alt='image'>
use [src] as a template expression when you are binding a property using interpolation:
<img [src]="imagePath" />
is the same as:
<img src={{imagePath}} />
If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.
string x = "text or int";
if (int.TryParse(x, out int output))
{
// Console.WriteLine(x);
// x is an int
// Do something
}
else
{
// x is not an int
}
If you also want to get the int values, you can write like this.
Method 1
string x = "text or int";
int value = 0;
if(int.TryParse(x, out value))
{
// x is an int
// Do something
}
else
{
// x is not an int
}
Method 2
string x = "text or int";
int num = Convert.ToInt32(x);
Console.WriteLine(num);
Referece: https://www.dotnetperls.com/parse
macOS 10.15.7
Prefrences...
Window
tabScrollback
to Limit number of rows to:
what your wanted.Just a small detail that I think is missing in above answers.
If your child activity can be opened from multiple parent activities then you can check if you need to do setResult
or not, based on if your activity was opened by startActivity
or startActivityForResult
. You can achieve this by using getCallingActivity()
. More info here.
A standard Maven
settings.xml
file is as follows:
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<proxies>
<proxy>
<active/>
<protocol/>
<username/>
<password/>
<port/>
<host/>
<nonProxyHosts/>
<id/>
</proxy>
</proxies>
<servers>
<server>
<username/>
<password/>
<privateKey/>
<passphrase/>
<filePermissions/>
<directoryPermissions/>
<configuration/>
<id/>
</server>
</servers>
<mirrors>
<mirror>
<mirrorOf/>
<name/>
<url/>
<layout/>
<mirrorOfLayouts/>
<id/>
</mirror>
</mirrors>
<profiles>
<profile>
<activation>
<activeByDefault/>
<jdk/>
<os>
<name/>
<family/>
<arch/>
<version/>
</os>
<property>
<name/>
<value/>
</property>
<file>
<missing/>
<exists/>
</file>
</activation>
<properties>
<key>value</key>
</properties>
<repositories>
<repository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</pluginRepository>
</pluginRepositories>
<id/>
</profile>
</profiles>
<activeProfiles/>
<pluginGroups/>
</settings>
To access a proxy
, you can find detailed information on the official Maven
page here:
I hope it helps for someone.
For me worked when I changed "directory" content into this:
<Directory "*YourLocation*">
Options All
AllowOverride All
Require all granted
</Directory>
In C++ the std::string class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
you have to call it like this
SELECT dbo.CheckIfSFExists(23, default)
From Technet:
When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.
Try this scenario:
Array = A1:C7
. A1-A3
have values, B2-B6
have value and C1
, C3
and C6
have values.
To get a count of the number of rows add a column D
(you can hide it after formulas are set up) and in D1
put formula =If(Sum(A1:C1)>0,1,0)
. Copy the formula from D1
through D7
(for others searching who are not excel literate, the numbers in the sum formula will change to the row you are on and this is fine).
Now in C8
make a sum formula that adds up the D
column and the answer should be 6
. For visually pleasing purposes hide column D
.
Being impatient, I created a new App Pool with the same settings and used that.
It can also be due to a duplicate entry in any of the tables that are used.
In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.
Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null
The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave
Append entry to the file contents if file exists, otherwise append the entry to an empty list and write in in the file:
a = []
if not os.path.isfile(fname):
a.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(a, indent=2))
else:
with open(fname) as feedsjson:
feeds = json.load(feedsjson)
feeds.append(entry)
with open(fname, mode='w') as f:
f.write(json.dumps(feeds, indent=2))