use it:
.CopyToDataTable()
example:
string _sqlWhere = "Nachname = 'test'";
string _sqlOrder = "Nachname DESC";
DataTable _newDataTable = yurDateTable.Select(_sqlWhere, _sqlOrder).CopyToDataTable();
unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(
I used
btn.setBackgroundColor(Color.TRANSPARENT);
and
android:background="@android:color/transparent"
I have encountered the same problem and in my case it was happening as a result of this problem:
I had the controllers defined in a separate module (called 'myApp.controllers') and injected to the main app module (called 'myApp') like this:
angular.module('myApp', ['myApp.controllers'])
A colleague pushed another controller module in a separate file but with the exact same name as mine (i.e. 'myApp.controllers' ) which caused this error. I think because Angular got confused between those controller modules. However the error message was not very helpful in discovering what is going wrong.
You can also overload the increment/decrement operators for your enumerated type.
routerLink
directive as used like this:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
is just a wrapper around imperative navigation using router
and its navigateByUrl method:
router.navigateByUrl('/inbox/33/messages/44')
as can be seen from the sources:
export class RouterLink {
...
@HostListener('click')
onClick(): boolean {
...
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
So wherever you need to navigate a user to another route, just inject the router
and use navigateByUrl
method:
class MyComponent {
constructor(router: Router) {
this.router.navigateByUrl(...);
}
}
There's another method on the router that you can use - navigate:
router.navigate(['/inbox/33/messages/44'])
Using
router.navigateByUrl
is similar to changing the location bar directly–we are providing the “whole” new URL. Whereasrouter.navigate
creates a new URL by applying an array of passed-in commands, a patch, to the current URL.To see the difference clearly, imagine that the current URL is
'/inbox/11/messages/22(popup:compose)'
.With this URL, calling
router.navigateByUrl('/inbox/33/messages/44')
will result in'/inbox/33/messages/44'
. But calling it withrouter.navigate(['/inbox/33/messages/44'])
will result in'/inbox/33/messages/44(popup:compose)'
.
Read more in the official docs.
You have to Import the Scanner and Timer Package Properly using the java.util classes.
import java.util.Scanner;
import java.util.Timer;
This will finally solve your problems:
lets say you have many buttons on a page and you want to change one of them with jQuery Ajax (or not ajax) depending on their ID.
lets also say that you have many different type of buttons (for forms, for approval and for like purposes), and you want the jQuery to treat only the "like" buttons.
here is a code that is working: the jQuery will treat only the buttons that are of class .cls-hlpb, it will take the id of the button that was clicked and will change it according to the data that comes from the ajax.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$(".clshlpbtn").on('click',function(e){
var id = $(e.target).attr('id');
alert("The id of the button that was clicked: "+id);
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
//parsing the data should come here:
//var obj = jQuery.parseJSON(data);
//$("#"+id).val(obj.name);
//etc.
if (id=="btnhlp-1")
$("#"+id).attr("style","color:red");
$("#"+id).val(data);
});
});
});
</script>
</head>
<body>
<input type="button" class="clshlpbtn" id="btnhlp-1" value="first btn"> </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-2" value="second btn"> </input>
<br />
<input type="button" class="clshlpbtn" id="btnhlp-9" value="ninth btn"> </input>
</body>
</html>
code was taken from w3schools and changed.
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
Important: This issue drove me crazy for a couple days and I couldn't figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.
I'm sure this is the issue for some of you.
Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:
"Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle."
Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.
Maybe try this? It seems the problem is solved after remove all the handlers in my case.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename='output.log', level=logging.INFO)
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Create a class which extends HttpServlet
and put @WebServlet
annotation on it containing the desired URL the servlet should listen on.
@WebServlet("/yourServletURL")
public class YourServlet extends HttpServlet {}
And just let <form action>
point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified the name
attribute of the HTML form input fields (<input>
, <select>
, <textarea>
and <button>
). This represents the HTTP request parameter name. Finally, you also need to make sure that the input fields of interest are enclosed inside the desired form and thus not outside.
Here are some examples of various HTML form input fields:
<form action="${pageContext.request.contextPath}/yourServletURL" method="post">
<p>Normal text field.
<input type="text" name="name" /></p>
<p>Secret text field.
<input type="password" name="pass" /></p>
<p>Single-selection radiobuttons.
<input type="radio" name="gender" value="M" /> Male
<input type="radio" name="gender" value="F" /> Female</p>
<p>Single-selection checkbox.
<input type="checkbox" name="agree" /> Agree?</p>
<p>Multi-selection checkboxes.
<input type="checkbox" name="role" value="USER" /> User
<input type="checkbox" name="role" value="ADMIN" /> Admin</p>
<p>Single-selection dropdown.
<select name="countryCode">
<option value="NL">Netherlands</option>
<option value="US">United States</option>
</select></p>
<p>Multi-selection listbox.
<select name="animalId" multiple="true" size="2">
<option value="1">Cat</option>
<option value="2">Dog</option>
</select></p>
<p>Text area.
<textarea name="message"></textarea></p>
<p>Submit button.
<input type="submit" name="submit" value="submit" /></p>
</form>
Create a doPost()
method in your servlet which grabs the submitted input values as request parameters keyed by the input field's name
(not id
!). You can use request.getParameter()
to get submitted value from single-value fields and request.getParameterValues()
to get submitted values from multi-value fields.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String gender = request.getParameter("gender");
boolean agree = request.getParameter("agree") != null;
String[] roles = request.getParameterValues("role");
String countryCode = request.getParameter("countryCode");
String[] animalIds = request.getParameterValues("animalId");
String message = request.getParameter("message");
boolean submitButtonPressed = request.getParameter("submit") != null;
// ...
}
Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.
User user = new User(name, pass, roles);
userDAO.save(user);
iPhone OS 3.0 and later supports the cornerRadius
property on the CALayer
class. Every view has a CALayer
instance that you can manipulate. This means you can get rounded corners in one line:
view.layer.cornerRadius = 8;
You will need to #import <QuartzCore/QuartzCore.h>
and link to the QuartzCore framework to get access to CALayer's headers and properties.
One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:
UIView
subclass and name it something like RoundRectView
.RoundRectView
's drawRect:
method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.UILabel
instance and make it a subview of the RoundRectView.label.frame = CGRectInset(roundRectView.bounds, 8, 8);
)You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.
If you change baudrate for example back and forth it clears the Serial Monitor window in version 1.5.3 of Arduino IDE for Intel Galileo development
Since the column may be null in the database, the rs.getString() will throw a NullPointerException()
No.
rs.getString
will not throw NullPointer
if the column is present in the selected result set (SELECT query columns)
For a particular record if value for the 'comumn is null in db, you must do something like this -
String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
myValue = ""; // set it to empty string as you desire.
}
You may want to refer to wasNull()
documentation -
From java.sql.ResultSet
boolean wasNull() throws SQLException;
* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* @return <code>true</code> if the last column value read was SQL
* <code>NULL</code> and <code>false</code> otherwise
* @exception SQLException if a database access error occurs or this method is
* called on a closed result set
*/
Without root, you can use debug proxies like Charlesproxy&Co.
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
A node is defined as:
the smallest unit of a valid, complete structure in a document.
or as:
An object in the tree view that serves as a container to hold related objects.
Now their are many different kinds of nodes as an elements node, an attribute node etc.
The reason this is happening is because buffering is turned on by default, and IIS 6 cannot handle the large response.
In Classic ASP, at the top of your page, after <%@Language="VBScript"%>
add:
<%Response.Buffer = False%>
In ASP.NET, you would add Buffer="False"
to your Page directive.
For example:
<%@Page Language="C#" Buffer="False"%>
If you are talking about the current transaction nesting level, then you would use @@TRANCOUNT
.
If you are talking about transaction isolation level, use DBCC USEROPTIONS
and look for an option of isolation level. If it isn't set, it's read committed.
setattr(x, attr, 'magic')
For help on it:
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
You can change the background of the canvas by doing this:
<head>
<style>
canvas {
background-color: blue;
}
</style>
</head>
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
Consider:
int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length // Gives the length of the array
myString.length() // Gives the length of the string
myList.size() // Gives the length of the list
It's very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally, a method, length()
, was used to avoid duplication of the same information. Another is that using a method length()
helps emphasize the immutability of strings, even though the size of an array is also unchangeable.
Ultimately this is just an inconsistency that evolved that would definitely be fixed if the language were ever redesigned from the ground up. As far as I know no other languages (C#, Python, Scala, etc.) do the same thing, so this is likely just a slight flaw that ended up as part of the language.
You'll get an error if you use the wrong one anyway.
It is best to NOT use @import
to include CSS in a page for speed reasons. See this excellent article to learn why not: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Also it is often harder to minify and combine css files that are served via the @import tag, because minify scripts cannot "peel out" the @import lines from other css files. When you include them as <link tags you can use existing minify php/dotnet/java modules to do the minification.
So: use <link />
instead of @import
.
As said before, switch can be used only with integer values. So, you just need to convert your "case" values to integer. You can achieve it by using constexpr from c++11, thus some calls of constexpr functions can be calculated in compile time.
something like that...
switch (str2int(s))
{
case str2int("Value1"):
break;
case str2int("Value2"):
break;
}
where str2int is like (implementation from here):
constexpr unsigned int str2int(const char* str, int h = 0)
{
return !str[h] ? 5381 : (str2int(str, h+1) * 33) ^ str[h];
}
Another example, the next function can be calculated in compile time:
constexpr int factorial(int n)
{
return n <= 1 ? 1 : (n * factorial(n-1));
}
int f5{factorial(5)};
// Compiler will run factorial(5)
// and f5 will be initialized by this value.
// so programm instead of wasting time for running function,
// just will put the precalculated constant to f5
If you want to change a color to single column try this:
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;
As mentioned before, you can't use inline elements for styling pseudo classes. Before and after pseudo classes are states of elements, not actual elements. You could only possibly use JavaScript for this.
try this way .eregi("[^A-Za-z0-9.]", $value)
You can simply go Netbeans, in the design view, go to JFrame
property, choose icon image property, Choose Set Form's iconImage
property using: "Custom code" and then in the Form.SetIconImage()
function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.
select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate= (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;
That should work.
num = int(input('Size of elements : '))
arr = list()
for i in range(num) :
ele = int(input())
arr.append(ele)
print(arr)
First, you should use any WebSocket or polling mechanics to notify the frontend part about changes that happened. I use Flask-SocketIO
wrapper, and very happy with async messaging for my tiny apps.
Nest, you can do all logic which you need in a separate thread(s), and notify the frontend via SocketIO
object (Flask holds continuous open connection with every frontend client).
As an example, I just implemented page reload on backend file modifications:
<!doctype html>
<script>
sio = io()
sio.on('reload',(info)=>{
console.log(['sio','reload',info])
document.location.reload()
})
</script>
class App(Web, Module):
def __init__(self, V):
## flask module instance
self.flask = flask
## wrapped application instance
self.app = flask.Flask(self.value)
self.app.config['SECRET_KEY'] = config.SECRET_KEY
## `flask-socketio`
self.sio = SocketIO(self.app)
self.watchfiles()
## inotify reload files after change via `sio(reload)``
def watchfiles(self):
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def __init__(self,sio):
super().__init__()
self.sio = sio
def on_modified(self, event):
print([self.on_modified,self,event])
self.sio.emit('reload',[event.src_path,event.event_type,event.is_directory])
self.observer = Observer()
self.observer.schedule(Handler(self.sio),path='static',recursive=True)
self.observer.schedule(Handler(self.sio),path='templates',recursive=True)
self.observer.start()
It turns out that I needed to use gulp-rename
and also output the concatenated file first before 'uglification'. Here's the code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
Coming from grunt
it was a little confusing at first but it makes sense now. I hope it helps the gulp
noobs.
And, if you need sourcemaps, here's the updated code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify'),
gp_sourcemaps = require('gulp-sourcemaps');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_sourcemaps.init())
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gp_sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
See gulp-sourcemaps for more on options and configuration.
Use a list comprehension:
results = [int(i) for i in results]
e.g.
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
If you just want to remove one of a group of variables, then you can create a list and keep just the variable you need. The rm function can be used to remove all the variables apart from "data". Here is the script:
0->data
1->data_1
2->data_2
3->data_3
#check variables in workspace
ls()
rm(list=setdiff(ls(), "data"))
#check remaining variables in workspace after deletion
ls()
#note: if you just use rm(list) then R will attempt to remove the "list" variable.
list=setdiff(ls(), "data")
rm(list)
ls()
Java - Editor - Mark Occurrences
Eclipse Java EE IDE for Web Developers. Version: Photon Release (4.8.0)
For OSX users:
If you use ls *.{mp3,exe,mp4}
, it will throw an error if one of those extensions has no results.
Using ls *.(mp3|exe|mp4)
will return all files matching those extensions, even if one of the extensions had 0 results.
I don't know the real reason but Maven pushes developers to install all libraries (custom too) into some maven repositories, so scope:system
is not well liked, A simple workaround is to use maven-install-plugin
follow the usage:
write your dependency in this way
<dependency>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
</dependency>
then, add maven-install-plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<executions>
<execution>
<id>install-external</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/mylib-core-0.0.1.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
</executions>
</plugin>
pay attention to phase:clean
, to install your custom library into your repository, you have to run mvn clean
and then mvn install
I recommend you to add the contentDescription.
android:contentDescription="@string/contentDescriptionXxxx"
but, let's be realistic. Most people don't maintain literal for accessibility. Still, with little effort, you can implement something to help people with disability.
<string name="contentDescriptionUseless">deco</string>
<string name="contentDescriptionAction">button de action</string>
<string name="contentDescriptionContent">image with data</string>
<string name="contentDescriptionUserContent">image from an other user</string>
.
The most important thing the blind user will need to know is "Where is the button that I need to click to continue"
Use contentDescriptionAction for anything clickable.
use contentDescriptionContent for image with information (graph, textAsImage, ...)
use contentDescriptionUserContent for all user provided content.
use contentDescriptionUseless for all the rest.
You may try to use the following form:
select * from table1 where ID in (1,2,3,4,...,1000)
union all
select * from table1 where ID in (1001,1002,...)
pg_basebackup
seems to be the better way of doing this now, especially for large databases.
You can copy a database from a server with the same or older major version. Or more precisely:
pg_basebackup
works with servers of the same or an older major version, down to 9.1. However, WAL streaming mode (-X stream
) only works with server version 9.3 and later, and tar format mode (--format=tar
) of the current version only works with server version 9.5 or later.
For that you need on the source server:
listen_addresses = '*'
to be able to connect from the target server. Make sure port 5432 is open for that matter.max_wal_senders = 1
(-X fetch
), 2
for -X stream
(the default in case of PostgreSQL 12), or more.wal_level = replica
or higher to be able to set max_wal_senders > 0
.host replication postgres DST_IP/32 trust
in pg_hba.conf
. This grants access to the pg
cluster to anyone from the DST_IP
machine. You might want to resort to a more secure option.Changes 1, 2, 3 require server restart, change 4 requires reload.
On the target server:
# systemctl stop postgresql@VERSION-NAME
postgres$ pg_basebackup -h SRC_IP -U postgres -D VERSION/NAME --progress
# systemctl start postgresql@VERSION-NAME
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
You need to first change the constraint and then animate the update.
This should be in the superview.
self.nameInputConstraint.constant = 8
Swift 2
UIView.animateWithDuration(0.5) {
self.view.layoutIfNeeded()
}
Swift 3, 4, 5
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
You could try:
$rows = array();
while($row = mysql_fetch_array($result)){
array_push($rows, $row);
}
echo json_encode($rows);
you must add in your MODULE-LEVEL build.gradle file with:
//module-level build.gradle file
repositories {
maven {
url 'https://maven.google.com'
}
}
see: Google's Maven repository
I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:
//project-level build.gradle file
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0
Try this:
String str="name=john age=13 year=2001";
String s[]=str.split(" ");
StringBuilder v=new StringBuilder();
for (String string : s) {
v.append(string);
}
str=v.toString();
On my Mobo (ASRock A320M-HD with Ryzen 3 2200G) I have to:
SR-IOV support: enabled
IOMMU: enabled
SVM: enabled
On the OS enable Hyper V.
Try this:
INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'
Note:
Here if id is the primary key then after first insertion with id='1'
every time attempt to insert id='1'
will update name and age and previous name age will change.
$(window).bind('resize', function () {
alert('resize');
});
You can use:
<option value="someValue" selected>Some Value</option>
instead of,
<option value="someValue" selected = "selected">Some Value</option>
both are equally correct.
The only thing missing hidden from Rob W's excellent answer is how to communicate between the injected page script and the content script.
On the receiving side (either your content script or the injected page script) add an event listener:
document.addEventListener('yourCustomEvent', function (e) {
var data = e.detail;
console.log('received', data);
});
On the initiator side (content script or injected page script) send the event:
var data = {
allowedTypes: 'those supported by structured cloning, see the list below',
inShort: 'no DOM elements or classes/functions',
};
document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));
Notes:
In Firefox, to send an object (i.e. not a primitive value) from the content script to the page context you have to explicitly clone it into the target using cloneInto
(a built-in function), otherwise it'll fail with a security violation error.
document.dispatchEvent(new CustomEvent('yourCustomEvent', {
detail: cloneInto(data, document.defaultView),
}));
Multiple commands can be put in parenthesis and spread over numerous lines; so something like echo hi && echo hello
can be put like this:
( echo hi
echo hello )
Also variables can help:
set AFILEPATH="C:\SOME\LONG\PATH\TO\A\FILE"
if exist %AFILEPATH% (
start "" /b %AFILEPATH% -option C:\PATH\TO\SETTING...
) else (
...
Also I noticed with carets (^
) that the if
conditionals liked them to follow only if a space was present:
if exist ^
When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:
current thread:
Dispatcher.CurrentDispatcher.Invoke(MethodName,
new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.
Main UI thread:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(() => MethodName(parameter)));
Played with Boo's approach, however don't like the fact that user got kicked off only once another digest is run, which means user stays logged in until he tries to do something within the page, and then immediatelly kicked off.
I am trying to force the logoff using interval which checks every minute if last action time was more than 30 minutes ago. I hooked it on $routeChangeStart, but could be also hooked on $rootScope.$watch as in Boo's example.
app.run(function($rootScope, $location, $interval) {
var lastDigestRun = Date.now();
var idleCheck = $interval(function() {
var now = Date.now();
if (now - lastDigestRun > 30*60*1000) {
// logout
}
}, 60*1000);
$rootScope.$on('$routeChangeStart', function(evt) {
lastDigestRun = Date.now();
});
});
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
Solution for me was to set the "form" attribute of button
<form id="form_id_name"><button name="btnSubmit" form="form_id_name" /></form>
or is js:
YOURFORMOBJ.getElementsByTagName("button")[0].setAttribute("form", "form_id_name");
YOURFORMOBJ.submit();
Try using if tracked file.
git rm <path to file>
git reset <path to file>
git checkout <path to file>
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
I tried an above answer and didn't work until I switched the statements. This is what worked for me:
myEditText.setSelectAllOnFocus(true);
myEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickMyEditText();
}
});
private void onClickMyEditText() {
if(myEditText.isFocused()){
myEditText.clearFocus();
myEditText.requestFocus();
}else{
myEditText.requestFocus();
myEditText.clearFocus();
}
}
I had to ask if the focus is on the EditText, and if not request the focus first and then clear it. Otherwise the next times I clicked on the EditText the virtual keyboard would never appear
Use
Time.now + 10.days
or even
10.days.from_now
Both definitely work. Are you sure you're in Rails and not just Ruby?
If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.
http://www.w3schools.com/tags/tag_ul.asp
ul {
display: block;
list-style-type: disc;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 0;
margin-right: 0;
padding-left: 40px;
}
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
"Best" is such a subjective term :-)
I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:
public Boolean anyUnset() {
if ( id == null) return true;
if (name == null) return true;
return false;
}
Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.
Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap
) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.
If you do not want to depend on throwing exception (which you probably should not) you can try this:
public static <T> T cast(Object o, Class<T> clazz) {
return clazz.isInstance(o) ? clazz.cast(o) : null;
}
You can pass the value back into the component by creating a reference variable on the select tag #device
and passing it into the change handler onChange($event, device.value)
should have the new value
<select [(ng-model)]="selectedDevice" #device (change)="onChange($event, device.value)">
<option *ng-for="#i of devices">{{i}}</option>
</select>
onChange($event, deviceValue) {
console.log(deviceValue);
}
A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach
method is available. [...form.elements].forEach
Update: Array.from
is a nicer alternative to spread Array.from(form.elements)
it's slightly clearer behaviour.
An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"
const forms = document.querySelectorAll('form');
const form = forms[0];
Array.from(form.elements).forEach((input) => {
console.log(input);
});
_x000D_
<div>
<h1>Input Form Selection</h1>
<form>
<label>
Foo
<input type="text" placeholder="Foo" name="Foo" />
</label>
<label>
Password
<input type="password" placeholder="Password" />
</label>
<label>
Foo
<input type="text" placeholder="Bar" name="Bar" />
</label>
<span>Ts & Cs</span>
<input type="hidden" name="_id" />
<input type="submit" name="_id" />
</form>
</div>
_x000D_
export default
is used to export a single class, function or primitive from a script file.
The export can also be written as
export default function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = function() {
return "" + this.string;
};
This is used to import this function in another script file
Say in app.js, you can
import SafeString from './handlebars/safe-string';
As the name says, it's used to export functions, objects, classes or expressions from script files or modules
Utiliites.js
export function cube(x) {
return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;
This can be imported and used as
App.js
import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
Or
import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo); // 4.555806215962888
When export default is used, this is much simpler. Script files just exports one thing. cube.js
export default function cube(x) {
return x * x * x;
};
and used as App.js
import Cube from 'cube';
console.log(Cube(3)); // 27
You can give like this
public static function getAll()
{
return $posts = $this->all()->take(2)->get();
}
And when you call statically inside your controller function also..
Just use the array of options, to see, which option is currently selected.
$options = array( 'one', 'two', 'three' );
$output = '';
for( $i=0; $i<count($options); $i++ ) {
$output .= '<option '
. ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>'
. $options[$i]
. '</option>';
}
Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.
Don't include header.php. You should not output HTML when you are going to redirect.
Make a new file, eg. "pre.php". Put this in it:
<?php
include('class.user.php');
include('class.Connection.php');
?>
Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.
Ask yourself these questions:
What do they do?
What do they decouple/couple?
When should you use them?
When should you not use them?
What missing language feature would make them go away?
What technical debt do you incur by using it?
Is there a simpler way to get the job done?
In base R, we can select the columns which we want to test using grep
, compare the data with 0, use rowSums
to select rows which has all non-zero values.
cols <- grep("^Mac", names(df))
df[rowSums(df[cols] != 0) == length(cols), ]
# DateTime Mac1 Mac2 Mac3 Mac4
#1 2011-04-02 06:05 21 21 21 21
#2 2011-04-02 06:10 22 22 22 22
#3 2011-04-02 06:20 24 24 24 24
Doing this with inverted logic but giving the same output
df[rowSums(df[cols] == 0) == 0, ]
In dplyr
, we can use filter_at
to test for specific columns and use all_vars
to select rows where all the values are not equal to 0.
library(dplyr)
df %>% filter_at(vars(starts_with("Mac")), all_vars(. != 0))
data
df <- structure(list(DateTime = structure(1:6, .Label = c("2011-04-02 06:00",
"2011-04-02 06:05", "2011-04-02 06:10", "2011-04-02 06:15", "2011-04-02 06:20",
"2011-04-02 06:25"), class = "factor"), Mac1 = c(20L, 21L, 22L,
23L, 24L, 0L), Mac2 = c(0L, 21L, 22L, 23L, 24L, 25L), Mac3 = c(20L,
21L, 22L, 0L, 24L, 25L), Mac4 = c(20L, 21L, 22L, 23L, 24L, 0L
)), class = "data.frame", row.names = c(NA, -6L))
At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4
is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.
Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin
https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr
contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.
What about %n
using a formatter like String.format()
?:
String s = String.format("I%nam%na%nboy");
As this answer says, its available from java 1.5 and is another way to System.getProperty("line.separator")
or System.lineSeparator()
and, like this two, is OS independent.
yes yes, git gc
is the solution, naturally,
and locally - you can just delete the local repository and clone it again,
the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,
Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,
but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff, you can still store the old git & externals somewhere, if you get nostalgic :]
but, at some point you really have to move along :]
your team will thank you!
C is the core language that most closely resembles and directly translates into CPU machine code. CPUs follow instructions that move, add, logically combine, compare, jump, push and pop. C does exactly this using much easier syntax. If you study the disassembly, you can learn to write C code that is just as fast and compact as assembly. It is my preferred language on 8 bit micro controllers with limited memory. If you write a large PC program in C you will get into trouble because of its limited organization. That is where object oriented programming becomes powerful. The ability of C++ and C# classes to contain data and functions together enforces organization which in turn allows more complex operability over C. C++ was essential for quick processing in the past when CPUs only had one core. I am beginning to learn C# now. Its class only structure appears to enforce a higher degree of organization than C++ which should ultimately lead to faster development and promote code sharing. C# is not interpreted like VB. It is partially compiled at development time and then further translated at run time to become more platform friendly.
function formatTime(date){
d = new Date(date);
var h=d.getHours(),m=d.getMinutes(),l="AM";
if(h > 12){
h = h - 12;
}
if(h < 10){
h = '0'+h;
}
if(m < 10){
m = '0'+m;
}
if(d.getHours() >= 12){
l="PM"
}else{
l="AM"
}
return h+':'+m+' '+l;
}
Usage & result:
var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
This is an old question but encountered it myself.
I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")
If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.
If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.
Here is a crappy example just post into a html file to view.
<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
<div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
<div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
</div>
</div>
There is also the rather spiffy FileStream
, introduced in SQL Server 2008.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.
For JDK 7 users, Here using
Objects.requireNotNull(object[, optionalMessage]);
is not safe. This function throws NullPointerException
if it finds null
object and which is a RunTimeException
.
That will terminate the whole program!!. So better check null
using ==
or !=
.
Also, use List
instead of Array
. Although access speed is same, yet using Collections
over Array
has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector
without rewriting all your code.
public static double calculateInventoryTotal(List<Book> books) {
if (books == null || books.isEmpty()) {
return 0;
}
double total = 0;
for (Book book : books) {
if (book != null) {
total += book.getPrice();
}
}
return total;
}
Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.
Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException
. It defined a new class called Optional
. Have a look at this for detail
Finally, Pardon my bad English.
Yes, you can do it. you can either use css or javascript to hide the reCaptcha v3 badge.
display: none
or visibility: hidden
to hide the reCaptcha batch. It's easy and quick..grecaptcha-badge {
display:none !important;
}
var el = document.querySelector('.grecaptcha-badge');
el.style.display = 'none';
Hiding the badge is valid, according to the google policy and answered in faq here. It is recommended to show up the privacy policy and terms of use from google as shown below.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values.
The dataframes were produced using table function.
The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim.
My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.
Therefore, I made the following function. Maybe this function can help someone.
##########################################################
#### Dependencies #####
##########################################################
# Depends on Base R only
##########################################################
#### Example DF #####
##########################################################
# Example df
ex_df <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ),
c( seq(1, 7, 1), rep("NA", 3), seq(1, 12, 1) ),
c( seq(1, 3, 1), rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))
# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]
# Making an unequal list of dfs,
# without a common id column
list_of_df <- apply(ex_df=="NA", 2, ( table) )
it is following the function
##########################################################
#### The function #####
##########################################################
# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
length_df <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
max_no <- max(length_df[,1])
max_df <- length_df[max(length_df),]
name_df <- names(length_df[length_df== max_no,][1])
names_list <- names(list_of_dfs[ name_df][[1]])
df_dfs <- list()
for (i in 1:max_no ) {
df_dfs[[i]] <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))
}
df_cbind <- do.call( cbind, df_dfs )
rownames( df_cbind ) <- rownames (length_df)
colnames( df_cbind ) <- names_list
df_cbind
}
Running the example
##########################################################
#### Running the example #####
##########################################################
rbind_null_df_lists ( list_of_df )
Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.
For those that want to use reduce, the following will also work:
reduce(set.intersection, list_of_sets)
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
here it it
var ffversion = '18';
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox/'+ffversion) > -1;
alert(is_firefox);
I also have the same error. I have updated the jackson library version and error has gone.
<!-- Jackson to convert Java object to Json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
</dependencies>
and also check your data classes that have you created getters and setters for all the properties.
I resolved the issue by double checking the "libs" directory and removing redundant jars, even though those jars were not manually added in the dependencies.
The reason you are getting the unexpected result is that hist(...)
calculates the distribution from a numeric vector. In your code, table(animalFactor)
behaves like a numeric vector with three elements: 1, 3, 7. So hist(...)
plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.
Here's a way to do this using ggplot
:
library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))
You would get precisely the same result using animalFactor
instead of animals
in the code above.
select C.ComputerName, S.Version, A.Name from Computer C inner join Software_Computer SC on C.Id = SC.ComputerId Inner join Software S on SC.SoftwareID = S.Id Inner join Application A on S.ApplicationId = A.Id ;
In Notepad++ v7.8.9 you can use the Tab
key to increase the indention level, and use Shift + Tab
to decrease the indentation level.
I have come across the same problem and have a cleaner solution. Instead of creating an empty data.frame
you can instead save your data as a named list. Once you have added all results to this list you convert it to a data.frame after.
For the case of adding features one at a time this works best.
mylist = list()
for(column in 1:10) mylist$column = rnorm(10)
mydf = data.frame(mylist)
For the case of adding rows one at a time this becomes tricky due to mixed types. If all types are the same it is easy.
mylist = list()
for(row in 1:10) mylist$row = rnorm(10)
mydf = data.frame(do.call(rbind, mylist))
I haven't found a simple way to add rows of mixed types. In this case, if you must do it this way, the empty data.frame is probably the best solution.
The behavior of the dblclick
event is explained at Quirksmode.
The order of events for a dblclick
is:
The one exception to this rule is (of course) Internet Explorer with their custom order of:
As you can see, listening to both events together on the same element will result in extra calls to your click
handler.
This cannot be done in pure java. But you can run external programs using java and get the result.
Process p=Runtime.getRuntime().exec("systeminfo");
Scanner scan=new Scanner(p.getInputStream());
while(scan.hasNext()){
String temp=scan.nextLine();
if(temp.equals("Available Physical Memmory")){
System.out.println("RAM :"temp.split(":")[1]);
break;
}
}
Make sure to watch your selectors. You appear to have forgotten the #
for div2
. Additionally, you can toggle the visibility of many elements at once with .toggle()
:
// Short-form of `document.ready`
$(function(){
$("#div2").hide();
$("#preview").on("click", function(){
$("#div1, #div2").toggle();
});
});
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
I also hit this error…
The installation msi will try to create a new task in the Windows Task scheduler to remind you to give customer feedback. This install step executes regardless of whether you do or do not click the check box to participate in customer feedback. In many corporate environments (including mine) creating new windows tasks is denied to all but domain administrators. As a result, running as a local admin is not sufficient and the entire installation fails when adding the task returns “access denied”. This shows up in the install log as a 1603.
The only workaround we could find was to manually pull all the files out of the msi, remove the “add schedule task” from the install script, and then create a new msi. After that one line change, it worked fine.
style="position:absolute"
First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.
Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.
To get your old version of Java back you need to reverse these steps.
Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).
The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
You can also import as
from math import *
Then you can use any mathematical function without prefixing math. e.g.
sqrt(4)
Not enough reputation to comment yet so I'll just put this here:
To expand on Micah's answer - the browser runs your code top to bottom, so if you write:
<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>
The browser will create a div with id "chart", and then run your script, which will try to find that div, and, hurray, success.
Otherwise if you write:
<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>
The browser runs your script, and tries to find a div with id chart, but it hasn't been created yet so it fails.
THEN the browser creates a div with id "chart".
There is a way to do it slightly faster than in Yaroslav's answer by using get_operations. Here is a quick example:
import tensorflow as tf
a = tf.constant(1.3, name='const_a')
b = tf.Variable(3.1, name='variable_b')
c = tf.add(a, b, name='addition')
d = tf.multiply(c, a, name='multiply')
for op in tf.get_default_graph().get_operations():
print(str(op.name))
$ unset GOROOT
worked for me. As most answers suggest your GOROOT is invalid.
If you are serving the app in prod make sure you are serving the static files with service worker. I had this error when I was serving only static subfolder of React build on Django (without assets that have styles)
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
In order to create a cronjob, follow these steps:
run this command : SET GLOBAL event_scheduler = ON;
If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant
It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.
To disable the event scheduler, use one of the following two methods:
As a command-line option when starting the server:
--event-scheduler=DISABLED
In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):
event_scheduler=DISABLED
Read MySQL documentation for more information.
DROP EVENT IF EXISTS EVENT_NAME;
CREATE EVENT EVENT_NAME
ON SCHEDULE EVERY 10 SECOND/minute/hour
DO
CALL PROCEDURE_NAME();
To view entries in Drupal's own internal log system (the watchdog
database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.
Use the watchdog()
function to add an entry to this log from your own custom module.
When Drupal bootstraps it uses the PHP function set_error_handler()
to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog()
call at admin/reports/dblog
. If you look for PHP fatal errors, for example, in /var/log/apache/error.log
and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log
, or wherever you have it configured to log to.
This error means that at least one row in your Pickup_withoutproxy2.txt file has a value in its first column that is larger than an int (your PickupId field).
An Int can only accept values between -2147483648 to 2147483647.
Review your data to see what's going on. You could try to load it into a temp table with a varchar data type if your txt file is extremely large and difficult to see. Easy enough to check for an int once loaded in the database.
Good luck.
set -x
Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
[source]
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
expr
has been evaluated.echo
has been evaluated.To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
Just a quick comment: sometimes Maven does not copy the jstl-.jar to the WEB-INF folder even if the pom.xml has the entry for it.
I had to manually copy the JSTL jar to /WEB-INF/lib on the file system. That resolved the problem. The issue may be related to Maven war packaging plugin.
Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
const newSomething = new SomeEntity({_x000D_
_id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
somethingName:req.body.somethingName,_x000D_
theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
Hope it Helps
date
as background dedicated processIn order to make this kind of translation a lot quicker...
In this post, you will find
bc
, rot13
, sed
...).fifo=$HOME/.fifoDate-$$
mkfifo $fifo
exec 5> >(exec stdbuf -o0 date -f - +%s >$fifo 2>&1)
echo now 1>&5
exec 6< $fifo
rm $fifo
read -t 1 -u 6 now
echo $now
This must output current UNIXTIME. From there, you could compare
time for i in {1..5000};do echo >&5 "now" ; read -t 1 -u6 ans;done
real 0m0.298s
user 0m0.132s
sys 0m0.096s
and:
time for i in {1..5000};do ans=$(date +%s -d "now");done
real 0m6.826s
user 0m0.256s
sys 0m1.364s
From more than 6 seconds to less than a half second!!(on my host).
You could check echo $ans
, replace "now"
by "2019-25-12 20:10:00"
and so on...
Optionaly, you could, once requirement of date subprocess ended:
exec 5>&- ; exec 6<&-
Instead of running 1 fork by date to convert, run date
just 1 time and do all convertion with same process (this could become a lot quicker)!:
date -f - +%s <<eof
Apr 17 2014
May 21 2012
Mar 8 00:07
Feb 11 00:09
eof
1397685600
1337551200
1520464020
1518304140
Sample:
start1=$(LANG=C ps ho lstart 1)
start2=$(LANG=C ps ho lstart $$)
dirchg=$(LANG=C date -r .)
read -p "A date: " userdate
{ read start1 ; read start2 ; read dirchg ; read userdate ;} < <(
date -f - +%s <<<"$start1"$'\n'"$start2"$'\n'"$dirchg"$'\n'"$userdate" )
Then now have a look:
declare -p start1 start2 dirchg userdate
(may answer something like:
declare -- start1="1518549549" declare -- start2="1520183716" declare -- dirchg="1520601919" declare -- userdate="1397685600"
This was done in one execution!
We just need one fifo:
mkfifo /tmp/myDateFifo
exec 7> >(exec stdbuf -o0 /bin/date -f - +%s >/tmp/myDateFifo)
exec 8</tmp/myDateFifo
rm /tmp/myDateFifo
(Note: As process is running and all descriptors are opened, we could safely remove fifo's filesystem entry.)
Then now:
LANG=C ps ho lstart 1 $$ >&7
read -u 8 start1
read -u 8 start2
LANG=C date -r . >&7
read -u 8 dirchg
read -p "Some date: " userdate
echo >&7 $userdate
read -u 8 userdate
We could buid a little function:
mydate() {
local var=$1;
shift;
echo >&7 $@
read -u 8 $var
}
mydate start1 $(LANG=C ps ho lstart 1)
echo $start1
newConnector
functionWith functions for connecting MySQL/MariaDB
, PostgreSQL
and SQLite
...
You may find them in different version on GitHub, or on my site: download or show.
wget https://raw.githubusercontent.com/F-Hauri/Connector-bash/master/shell_connector.bash
. shell_connector.bash
newConnector /bin/date '-f - +%s' @0 0
myDate "2018-1-1 12:00" test
echo $test
1514804400
Nota: On GitHub, functions and test are separated files. On my site test are run simply if this script is not sourced.
# Exit here if script is sourced
[ "$0" = "$BASH_SOURCE" ] || { true;return 0;}
Using RxJs, you can declare a Subject
in your parent component and pass it as Observable
to child component, child component just need to subscribe to this Observable
.
Parent-Component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
Parent-HTML
<child [events]="eventsSubject.asObservable()"> </child>
Child-Component
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
I can modify the table field's datatype, with these following query: and also in the Oracle DB,
ALTER TABLE table_name
MODIFY column_name datatype;
What database are you connecting to? I know Oracle can be picky about date formats and likes ISO 8601 format.
**Note: Oops, I just read you are on MySQL. Just format the date and try it as a separate direct SQL call to test.
In Python, you can get an ISO date like
now.isoformat()
For instance, Oracle likes dates like
insert into x values(99, '31-may-09');
Depending on your database, if it is Oracle you might need to TO_DATE it:
insert into x
values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));
The general usage of TO_DATE is:
TO_DATE(<string>, '<format>')
If using another database (I saw the cursor and thought Oracle; I could be wrong) then check their date format tools. For MySQL it is DATE_FORMAT() and SQL Server it is CONVERT.
Also using a tool like SQLAlchemy will remove differences like these and make your life easy.
Just had the same error message, but when I was running a package.json with:
"scripts": {
"build": "tsc -p ./src",
}
tsc
is the command to run the TypeScript compiler.
I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install
didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev
) to solve the problem.
select count(1) into existence
from sales where sales_type = 'Accessories' and rownum=1;
Oracle plan says that it costs 1 if seles_type column is indexed.
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
I've added
<uses-permission android:name="android.permission.INTERNET" />
to debug/AndroidManifest.xml
and it started working! I've removed it from main/AndroidManifest.xml
and forgot to add in debug.
ReactNative version is 0.61.2
The Python standard library comes with an e-mail parsing function: email.utils.parseaddr()
.
It returns a two-tuple containing the real name and the actual address parts of the e-mail:
>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')
>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')
>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')
And if the parsing is unsuccessful, it returns a two-tuple of empty strings:
>>> parseaddr('[invalid!email]')
('', '')
An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:
>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')
>>> parseaddr('invalid-email')
('', 'invalid-email')
So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.
However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:
>>> '@' in parseaddr("invalid-email")[1]
False
If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX
servers:
>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NXDOMAIN
You can catch both NoAnswer
and NXDOMAIN
by catching dns.exception.DNSException
.
And Yes, foo@[email protected]
is a syntactically valid address. Only the last @
should be considered for detecting where the domain part starts.
<input name="submitBnt" type="submit" value="like"/>
name is useful when using $_POST
in php and also in javascript as document.getElementByName('submitBnt')
.
Also you can use name as a CS selector like input[name="submitBnt"]
;
Hope this helps
In Linux:
java -version
In Windows:
java.exe -version
If you need more info about the JVM you can call the executable with the parameter -XshowSettings:properties
. It will show a lot of System Properties. These properties can also be accessed by means of the static method System.getProperty(String)
in a Java class. As example this is an excerpt of some of the properties that can be obtained:
$ java -XshowSettings:properties -version
[...]
java.specification.version = 1.7
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.7.0_95
[...]
So if you need to access any of these properties from Java code you can use:
System.getProperty("java.specification.version");
System.getProperty("java.vendor");
System.getProperty("java.vendor.url");
System.getProperty("java.version");
Take into account that sometimes the vendor is not exposed as clear as Oracle or IBM. For example,
$ java version
"1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
HotSpot is what Oracle calls their implementation of the JVM. Check this list if the vendor does not seem to be shown with -version
.
It seems like your problem may be arising at
while(in.read(outputByte,0,4096)!=-1){
where it might go into an infinite loop for not advancing the offset (which is 0 always in the call). Try
while(in.read(outputByte)!=-1){
which will by default try to read upto outputByte.length into the byte[]
. This way you dont have to worry about the offset. See FileInputStrem's read method
To list all the process running on port 8080 do the following.
netstat -ano | find "8080"
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 10612
TCP [::]:8080 [::]:0 LISTENING 10612
Then to kill the process run the following command
taskkill /F /PID 10612
There is actually a comparison of the two in the official WebStorm FAQ. However, the version history of that page shows it was last updated December 13, so I'm not sure if it's maintained.
This is an extract from the FAQs for reference:
What is WebStorm & PhpStorm?
WebStorm & PhpStorm are IDEs (Integrated Development Environment) built on top of JetBrains IntelliJ platform and narrowed for web development.
Which IDE do I need?
PhpStorm is designed to cover all needs of PHP developer including full JavaScript, CSS and HTML support. WebStorm is for hardcore JavaScript developers. It includes features PHP developer normally doesn’t need like Node.JS or JSUnit. However corresponding plugins can be installed into PhpStorm for free.
How often new vesions (sic) are going to be released?
Preliminarily, WebStorm and PhpStorm major updates will be available twice in a year. Minor (bugfix) updates are issued periodically as required.
snip
IntelliJ IDEA vs WebStorm features
IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.
Swift 3
let indexpath = NSIndexPath(row: 0, section: 0)
let currentCell = tableView.cellForRow(at: indexpath as IndexPath)!
According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.
You can sum up the values of a BigDecimal
stream using a reusable Collector named summingUp
:
BigDecimal sum = bigDecimalStream.collect(summingUp());
The Collector
can be implemented like this:
public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
I've used the following JavaScript library with great success:
https://github.com/balupton/jquery-history
It supports the HTML5 history API as well as a fallback method (using #) for older browsers.
This library is essentially a polyfill around `history.pushState'.
Use the options
command, e.g. options(max.print=1000000)
.
See ?options
:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
One more variation wrapped up nicely where setAttribute isn't needed.
There are 3 lines that wouldn't be needed if Wetfox could dry off.
var saveAs = function (filename, content) {
if(filename === undefined) filename = "Unknown.txt";
if(content === undefined) content = "Empty?!";
let link = document.createElement('a');
link.style.display = "none"; // because Firefox sux
document.body.appendChild(link); // because Firefox sux
link.href = "data:application/octet-stream," + encodeURIComponent(content);
link.download = filename;
link.click();
document.body.removeChild(link); // because Firefox sux
};
Thanks for the help.
I personally prefer to just get them in one object hash, then I can access them anywhere. This could easily be set to an injectable variable and then everything could have it and it only grabbed once.
By wrapping the function this can also be done as a one liner.
var meta = (function () {
var m = document.querySelectorAll("meta"), r = {};
for (var i = 0; i < m.length; i += 1) {
r[m[i].getAttribute("name")] = m[i].getAttribute("content")
}
return r;
})();
If you have installed the Portable version of Chrome, or have it installed in a custom directory - the extensions won't be available in directory referenced in above answers.
Try right-clicking on Chrome's shortcut & Check the "Target" directory. From there, navigate to one directory above and you should be able to see the User Data
folder and then can use the answers mentioned above
Try this
static DataTable ConvertToDatatable(List<Item> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("URL");
foreach (var item in list)
{
var row = dt.NewRow();
row["Name"] = item.Name;
row["Price"] = Convert.ToString(item.Price);
row["URL"] = item.URL;
dt.Rows.Add(row);
}
return dt;
}
Try the following to see if you have the proper repository installed:
# yum search java | grep 'java-'
This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:
http://dag.wieers.com/rpm/FAQ.php#B
After you've got it installed try yum search again... This time you'll have a bunch of java stuff.
# yum search java | grep 'java-'
This will return the list of the available java packages. You can install one like this:
# yum install java-1.7.0-openjdk.x86_64
Because b + a ="someonedamage"
, try this to achieve :
if (d.Contains(b) && d.Contains(a))
{
Console.WriteLine(" " + d);
Console.ReadLine();
}
var parentDiv = pDoc.parentElement
edit: this is sometimes parentNode
in some cases.
https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement
sudo apt-get install curl-devel
sudo apt-get install libcurl-dev
(will install the default alternative)
OR
sudo apt-get install libcurl4-openssl-dev
(the OpenSSL variant)
OR
sudo apt-get install libcurl4-gnutls-dev
(the gnutls variant)
I believe this is quite language specific and for the C++ case a minor point for enum class type. Which appears more safe than traditional C enum. BUT
If you look at the implementation of std::byte its something like:
enum class byte : unsigned char {} ;
Source: https://en.cppreference.com/w/cpp/language/enum
And also consider this:
Otherwise, if T is a enumeration type that is either scoped or unscoped with fixed underlying type, and if the braced-init-list has only one initializer, and if the conversion from the initializer to the underlying type is non-narrowing, and if the initialization is direct-list-initialization, then the enumeration is initialized with the result of converting the initializer to its underlying type.
(since C++17)
Source: https://en.cppreference.com/w/cpp/language/list_initialization
This is an example of enum class representing values that are not defined enumerator. For this reason you cannot place complete trust in enums. Depending on application this might be important.
However, I really like what @Harlan Kassler said in his post and will start using that strategy in some situations myself.
Just an example of unsafe enum class:
enum class Numbers : unsigned
{
One = 1u,
Two = 2u
};
int main()
{
Numbers zero{ 0u };
return 0;
}
works for both hashes and arrays
module Helpers
module RecursiveCompact
extend self
def recursive_compact(hash_or_array)
p = proc do |*args|
v = args.last
v.delete_if(&p) if v.respond_to? :delete_if
v.nil? || v.respond_to?(:"empty?") && v.empty?
end
hash_or_array.delete_if(&p)
end
end
end
P.S. based on someones answer, cant find
usage - Helpers::RecursiveCompact.recursive_compact(something)
Yes, you will have to implement the constructors that make sense for each derivation and then use the base
keyword to direct that constructor to the appropriate base class or the this
keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like null
and only expose the necessary ones through their constructors.
In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.
Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.
In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:
mongoose.connect('mongodb://localhost/default');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('connected');
});
which is just how it is described in the docs. And then in your model files, do something like the following:
import mongoose, { Schema } from 'mongoose';
const userInfoSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: new Date(),
},
// ...other fields
});
const myDB = mongoose.connection.useDb('myDB');
const UserInfo = myDB.model('userInfo', userInfoSchema);
export default UserInfo;
Where myDB is your database name.
The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml
with you since these settings are user specific.
If you need to configure a proxy, have a look at the section about Proxies.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> ... <proxies> <proxy> <id>myproxy</id> <active>true</active> <protocol>http</protocol> <host>proxy.somewhere.com</host> <port>8080</port> <username>proxyuser</username> <password>somepassword</password> <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts> </proxy> </proxies> ... </settings>
id
: The unique identifier for this proxy. This is used to differentiate between proxy elements.active
: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.protocol, host, port
: The protocol://host:port of the proxy, seperated into discrete elements.username, password
: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.nonProxyHosts
: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common
The below code snippet will help evaluate primitive type holding NaN.
double dbl = Double.NaN;
Double.valueOf(dbl).isNaN() ? true : false;
This is the generic method that I use to convert any object that might be a DBNull.Value:
public static T ConvertDBNull<T>(object value, Func<object, T> conversionFunction)
{
return conversionFunction(value == DBNull.Value ? null : value);
}
usage:
var result = command.ExecuteScalar();
return result.ConvertDBNull(Convert.ToInt32);
shorter:
return command
.ExecuteScalar()
.ConvertDBNull(Convert.ToInt32);
Yes, as other answers have states, it cannot be done with Write-Output. Where PowerShell fails, turn to .NET, there are even a couple of .NET answers here but they are more complex than they need to be.
Just use:
[Console]::Write("Enabling feature XYZ.......")
Enable-SPFeature...
Write-Output "Done"
It is not purest PowerShell, but it works.
In order to wrap text in the code editor in IntelliJ IDEA 2020.1 community follow these steps:
Ctrl + Shift + "A" OR Help -> Find Action
Enter: "wrap" into the text box
Toggle: View | Active Editor Soft-Wrap "ON"
Note
In order to run apache server after upgradation PHP 7.4.x requires Microsoft Visual C++ Redistributable for Visual Studio 2019 which can be downloaded here under the heading Other Tools and Frameworks. otherwise apache server won't start.
SELECT * INTO [table_a] FROM dbo.myView
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
My solution is:
int[] spinnerLocation = {0,0};
spinner.getLocationOnScreen(spinnerLocation);
int[] scrollLocation = {0, 0};
scrollView.getLocationInWindow(scrollLocation);
int y = scrollView.getScrollY();
scrollView.smoothScrollTo(0, y + spinnerLocation[1] - scrollLocation[1]);
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
You can make a custom border using a span. Make a span with a class (Specifying the direction in which the border is going) and an id:
<html>
<body>
<div class="mdiv">
<span class="VerticalBorder" id="Span1"></span>
<header class="mheader">
<span class="HorizontalBorder" id="Span2"></span>
</header>
</div>
</body>
</html>
Then, go to you CSS and set the class to position:absolute
, height:100%
(For Vertical Borders), width:100%
(For Horizontal Borders), margin:0%
and background-color:#000000;
. Add everthing else that is necessary:
body{
margin:0%;
}
div.mdiv{
position:absolute;
width:100%;
height:100%;
top:0%;
left:0%;
margin:0%;
}
header.mheader{
position:absolute;
width:100%;
height:20%; /* You can set this to whatever. I will use 20 for easier calculations. You don't need a header. I'm using it to show you the difference. */
top:0%;
left:0%;
margin:0%;
}
span.HorizontalBorder{
position:absolute;
width:100%;
margin:0%;
background-color:#000000;
}
span.VerticalBorder{
position:absolute;
height:100%;
margin:0%;
background-color:#000000;
}
Then set the id that corresponds to class="VerticalBorder"
to top:0%;
, left:0%;
, width:1%;
(Since the width of the mdiv is equal to the width of the mheader at 100%, the width will be 100% of what you set it. If you set the width to 1% the border will be 1% of the window's width). Set the id that corresponds to the class="HorizontalBorder"
to top:99%
(Since it's in a header container the top refers to the position it is in according to the header. This + the height should add up to 100% if you want it to reach the bottom), left:0%;
and height:1%
(Since the height of the mdiv is 5 times greater than the mheader height [100% = 100, 20% = 20, 100/20 = 5], the height will be 20% of what you set it. If you set the height to 1% the border will be .2% of the window's height). Here is how it will look:
span#Span1{
top:0%;
left:0%;
width:.4%;
}
span#Span2{
top:99%;
left:0%;
width:1%;
}
DISCLAIMER: If you resize the window to a small enough size, the borders will disappear. A solution would be to cap of the size of the border if the window is resized to a certain point. Here is what I did:
window.addEventListener("load", Loaded);
function Loaded() {
window.addEventListener("resize", Resized);
function Resized() {
var WindowWidth = window.innerWidth;
var WindowHeight = window.innerHeight;
var Span1 = document.getElementById("Span1");
var Span2 = document.getElementById("Span2");
if (WindowWidth <= 800) {
Span1.style.width = .4;
}
if (WindowHeight <= 600) {
Span2.style.height = 1;
}
}
}
If you did everything right, it should look like how it is in this link: https://jsfiddle.net/umhgkvq8/12/ For some odd reason, the the border will disappear in jsfiddle but not if you launch it to a browser.
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
Another way to do this is to use the copy constructor:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);
Or create an empty set and add the elements:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);
Unlike clone
these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.
Note that the result of copying a Set
is a new Set
containing references to the objects that are elements if the original Set
. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection
APIs are designed to work: they don't copy the element objects.
The following tables are store WooCommerce products database :
wp_posts -
The core of the WordPress data is the posts. It is stored a post_type
like product or variable_product
.
wp_postmeta-
Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id
of product in wp_postmeta table.
Product categories, subcategories stored in this table :
following Query Return a list of product categories
SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat';
for more reference -
I am perplexed at the number of answers (all over the web) that say you need two methods: an "IsItThere()" method and a "GetItForMe()" method and so this leads to a race condition. What is wrong with a function that returns null, assigning it to a variable, and checking the variable for Null all in one test? My former C code was peppered with
if ( NULL != (variable = function(arguments...)) ) {
So you get the value (or null) in a variable, and the result all at once. Has this idiom been forgotten? Why?
Well there is a very easy way, but just setting android:animateLayoutChanges="true"
will not work. You need to enableTransitionType in you activity. Check this link for more info: http://www.thecodecity.com/2018/03/android-animation-on-view-visibility.html
Try following these steps:
Add the integratedSecurity=true
to JDBC URL like this:
Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true
Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:
java.sql.DatabaseMetaData metaData = connection.getMetaData();
System.out.println("Driver version:" + metaData.getDriverVersion());
Add the VM argument for your project:
Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86)
, or download from this link.
Place the dll file in your project folder and specify the VM argument like this:
VM Argument: -Djava.library.path="<<DLL File path till folder>>"
NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.
Difference between driver.close() & driver.quit()
driver.close – It closes the the browser window on which the focus is set.
driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.
in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File"
@fork2x
I have tried like this .Please review and update me whether it is right approach or not.
#/bin/sh
function pause(){
read -p "$*"
}
file="./apptest.properties"
if [ -f "$file" ]
then
echo "$file found."
dbUser=`sed '/^\#/d' $file | grep 'db.uat.user' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
echo database user = $dbUser
echo database pass = $dbPass
else
echo "$file not found."
fi
class Foo {
public:
Foo(int a) {
}
}
int func() {
int a1, a2;
std::cin >> a1;
std::cin >> a2;
Foo f1(a1);
__asm push a1;
__asm lea ecx, [this];
__asm call Foo::Foo(int);
Foo* f2 = new Foo(a2);
__asm push sizeof(Foo);
__asm call operator new;//there's a lot instruction here(depends on system)
__asm push a2;
__asm call Foo::Foo(int);
delete f2;
}
It would be like this in asm. When you're in func
, the f1
and pointer f2
has been allocated on stack (automated storage). And by the way, Foo f1(a1)
has no instruction effects on stack pointer (esp
),It has been allocated, if func
wants get the member f1
, it's instruction is something like this: lea ecx [ebp+f1], call Foo::SomeFunc()
. Another thing the stack allocate may make someone think the memory is something like FIFO
, the FIFO
just happened when you go into some function, if you are in the function and allocate something like int i = 0
, there no push happened.
There are two ways:
ax.set_xticks
and ax.set_xticklabels
) orplt.sca
to set the current axes for the pyplot state machine (i.e. the plt
interface).As an example (this also illustrates using setp
to change the properties of all of the subplots):
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=3, ncols=4)
# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
yticks=[1, 2, 3])
# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')
fig.tight_layout()
plt.show()
In XAMPP installation directory, open %XAMPP_HOME%/php/php.ini
file. Uncomment the following line:
extension=php_curl.dll
PS: If that doesn't work then check whether %XAMPP_HOME%/php/ext/php_curl.dll
file exist or not.
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple 'is a' fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
The article "Why is my list black? An Android optimization" in the Android Developers Blog has a thorough explanation of why the list background turns black when scrolling. Simple answer: set cacheColorHint on your list to transparent (#00000000).
You can also do it in the "mathematical" way without treating the number as a string:
var num = 278;_x000D_
var digits = [];_x000D_
while (num > 0) {_x000D_
digits.push(num % 10);_x000D_
num = parseInt(num / 10);_x000D_
}_x000D_
digits.reverse();_x000D_
console.log(digits);
_x000D_
One upside I can see is that you won't have to run parseInt()
on every digit, you're dealing with the actual digits as numeric values.
Basically it's like a DataReader, once read, data will be lost.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
String str = TempData["T"]; //Output - T
return View();
}
}
If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.
Check the output in Action Method Test 1 and Test 2
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
string Str = Convert.ToString(TempData["T"]);
TempData.Keep(); // Keep TempData
return RedirectToAction("Test2");
}
public ActionResult Test2()
{
string Str = Convert.ToString(TempData["T"]); //OutPut - T
return View();
}
}
If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep()
. is that
The Data will persist to the corresponding View
Using your example::
list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)
Use '[[' to retrieve an element of a list:
b = list_all[[1]]
b
[[1]]
[1] 1
[[2]]
[1] 2
class(b)
[1] "list"
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
Example:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c
is a list of list of strings, or whatever you designed this function to work with
For example you might get this error if you passed [c]
to the function instead of c
I had this issue and it was because of limited internet connection to source. You can use a proxy (VPN) but the better solution is download manually NodeJs from the source https://nodejs.org/download/ and Git, too.
after installation manually, aptana will check if they installed or not.
After attempting all of the above solutions to eliminate the "curl: (60) SSL certificate problem: unable to get local issuer certificate" error, the solution that finally worked for me on OSX 10.9 was:
Locate the curl certificate PEM file location 'curl-config --ca' -- > /usr/local/etc/openssl/cert.pem
Use the folder location to identify the PEM file 'cd /usr/local/etc/openssl'
Create a backup of the cert.pem file 'cp cert.pem cert_pem.bkup'
Download the updated Certificate file from the curl website 'sudo wget http://curl.haxx.se/ca/cacert.pem'
Copy the downloaded PEM file to replace the old PEM file 'cp cacert.pem cert.pem'
This is a modified version of a solution posted to correct the same issue in Ubuntu found here:
https://serverfault.com/questions/151157/ubuntu-10-04-curl-how-do-i-fix-update-the-ca-bundle
Here is an easy one:
$myVar > "c:\myfilepath\myfilename.myextension"
You can also try:
Get-content "c:\someOtherPath\someOtherFile.myextension" > "c:\myfilepath\myfilename.myextension"
This overview can be useful for someone: bin, dec, hex in python to convert between bin, dec, hex in python.
I would do:
dec_str = format(int('0000010010001101', 2),'x')
dec_str.rjust(4,'0')
Result: '048d'
You can use the string formatting mini language:
def binary(num, pre='0b', length=8, spacer=0):
return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:])
Demo:
print binary(1)
Output:
'0b00000001'
EDIT: based on @Martijn Pieters idea
def binary(num, length=8):
return format(num, '#0{}b'.format(length + 2))
This could be caused by a few things (most likely to least likely):
The server's SSL certificate is untrusted by the client. Easiest check is to point a browser at the URL and see if you get an SSL lock icon. If you get a broken lock, icon, click on it to see what the issue is:
Server is requiring Client SSL certificate - in this case you would have to update your code to sign the request with a client certificate.
If you get an exception java.awt.image.RasterFormatException in chrome, or you want to scroll a element into view then capture a screenshot.
Here is a solution from @Surya answer.
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
Long offsetTop = (Long) jsExecutor.executeScript("window.scroll(0, document.querySelector(\""+cssSelector+"\").offsetTop - 0); return document.querySelector(\""+cssSelector+"\").getBoundingClientRect().top;");
WebElement ele = driver.findElement(By.cssSelector(cssSelector));
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), Math.toIntExact(offsetTop),
eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
// Copy the element screenshot to disk
File screenshotLocation = new File("c:\\temp\\div_element_1.png");
FileUtils.copyFile(screenshot, screenshotLocation);
You can post below answer in your next post
var selectedTabIndex= $("#tabs").tabs('option', 'active');
Use out to denote that the parameter is not being used, only set. This helps the caller understand that you're always initializing the parameter.
Also, ref and out are not just for value types. They also let you reset the object that a reference type is referencing from within a method.
Changing from 32 to 64 bit worked for me - worth a try if you are on a 64 bit pc and it doesn't need to port.
i had similar issue just updated webdriver manager on mac use this in terminal to update webdriver manager-
sudo webdriver-manager update
Just as a complement of Reinout's answer.
The permanent way to solve this kind of problem is to edit .matplotlibrc file. Find it via
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
# This is the file location in Ubuntu
'/etc/matplotlibrc'
Then modify the backend in that file to backend : Agg
. That is it.
For Jackson 2+ (com.fasterxml.jackson
), the methods are little bit different:
Iterator<Entry<String, JsonNode>> nodes = rootNode.get("foo").fields();
while (nodes.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();
logger.info("key --> " + entry.getKey() + " value-->" + entry.getValue());
}
var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
var imgsrc = jQuery('.MulImage')[i];
var CurrentImgSrc = imgsrc.src;
img = jQuery('<img class="dynamic" style="width:100%;">');
img.attr('src', CurrentImgSrc);
jQuery('.YourDivClass').append(img);
}
You can use Modernizr to detect simply IE or not IE, by checking for SVG SMIL animation support.
If you've included SMIL feature detection in your Modernizr setup, you can use a simple CSS approach, and target the .no-smil class that Modernizr applies to the html element:
html.no-smil {
/* IE/Edge specific styles go here - hide HTML5 content and show Flash content */
}
Alternatively, you could use Modernizr with a simple JavaScript approach, like so:
if ( Modernizr.smil ) {
/* set HTML5 content */
} else {
/* set IE/Edge/Flash content */
}
Bear in mind, IE/Edge might someday support SMIL, but there are currently no plans to do so.
For reference, here's a link to the SMIL compatibility chart at caniuse.com.
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
The arrow module will steer you around and away from subtle mistakes, and it's easier to use that older products.
import arrow
def cleanWay(oneDate):
if currentDate.date().day > 25:
return currentDate.replace(months=+1,day=1)
else:
return currentDate.replace(day=1)
currentDate = arrow.get('25-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
currentDate = arrow.get('28-Feb-2017', 'DD-MMM-YYYY')
print (currentDate.format('DD-MMM-YYYY'), cleanWay(currentDate).format('DD-MMM-YYYY'))
In this case there is no need for you to consider the varying lengths of months, for instance. Here's the output from this script.
25-Feb-2017 01-Feb-2017
28-Feb-2017 01-Mar-2017
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install