I was having same problem.
I followed this steps, problem solved.
run command line (CMD) with Administrator Permission.
cd c:/wamp64/bin/apache/apache2.4.27/bin
httpd.exe -k uninstall
httpd.exe -k install
at last restart all services from wamp system tray icon
It's easy way to use .match()
method to string.
var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));
Wish you a nice day, sir!
Simply use
$(document).height() // - $('body').offset().top
and / or
$(window).height()
instead of $('body').height();
Successive insertions can be described by:
T = O(log(1) + log(2) + .. + log(n)) = O(log(n!))
By starling approximation, n! =~ O(n^(n + O(1)))
, therefore T =~ O(nlog(n))
Hope this helps, the optimal way O(n)
is using the build heap algorithm for a given set (ordering doesn't matter).
These are the preferred methods:
var item = Items.SingleOrDefault(x => x.Id == 123);
Or
var item = Items.Single(x => x.Id == 123);
Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process
You could also achieve this with the parse_date_time
or fast_strptime
functions from the lubridate
-package:
> parse_date_time(dates1, "ym")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
> fast_strptime(dates1, "%Y-%m")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
The difference between those two is that parse_date_time
allows for lubridate-style format specification, while fast_strptime
requires the same format specification as strptime
.
For specifying the timezone, you can use the tz
-parameter:
> parse_date_time(dates1, "ym", tz = "CET")
[1] "2009-01-01 CET" "2009-02-01 CET" "2009-03-01 CET"
When you have irregularities in your date-time data, you can use the truncated
-parameter to specify how many irregularities are allowed:
> parse_date_time(dates2, "ymdHMS", truncated = 3)
[1] "2012-06-01 12:23:00 UTC" "2012-06-01 12:00:00 UTC" "2012-06-01 00:00:00 UTC"
Used data:
dates1 <- c("2009-01","2009-02","2009-03")
dates2 <- c("2012-06-01 12:23","2012-06-01 12",'2012-06-01")
Also remember that you can pass a second argument to the .forEach()
function specifying the object to use as the this
keyword.
// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
// element is the name of the key.
// key is just a numerical value for the array
// _array is the array of all the keys
// this keyword = secondArg
this.foo;
this.bar();
}, secondArg);
You can use attachEvent(ie8) and addEventListener instead
addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });
function addEvent(element, eventName, fn) {
if (element.addEventListener)
element.addEventListener(eventName, fn, false);
else if (element.attachEvent)
element.attachEvent('on' + eventName, fn);
}
Declare value attribute for input tag (i.e value= {this.state.name}
) and if you want to clear this input vale you have to use this.setState({name : ''})
PFB working code for your reference :
<script type="text/babel">
var StateComponent = React.createClass({
resetName : function(event){
this.setState({
name : ''
});
},
render : function(){
return (
<div>
<input type="text" value= {this.state.name}/>
<button onClick={this.resetName}>Reset</button>
</div>
)
}
});
ReactDOM.render(<StateComponent/>, document.getElementById('app'));
</script>
As a rule, if your "underline" is not the same color as your text [and the 'color:' is not overridden inline] it is not coming from "text-decoration:" It has to be "border-bottom:"
Don't forget to take the border off your pseudo classes too!
a, a:link, a:visited, a:active, a:hover {border:0!important;}
This snippet assumes its on an anchor, change to it's wrapper accordingly... and use specificity instead of "!important" after you track down the root cause.
Yet another way to do this:
(Get-Date).AddDays(-1).Date.AddHours(22)
Since many answers here explained well ::
behaviour, additionally I would like to clarify that ::
operator doesnt need to have exactly same signature as the referring Functional Interface if it is used for instance variables. Lets assume we need a BinaryOperator which has type of TestObject. In traditional way its implemented like this:
BinaryOperator<TestObject> binary = new BinaryOperator<TestObject>() {
@Override
public TestObject apply(TestObject t, TestObject u) {
return t;
}
};
As you see in anonymous implementation it requires two TestObject argument and returns a TestObject object as well. To satisfy this condition by using ::
operator we can start with a static method:
public class TestObject {
public static final TestObject testStatic(TestObject t, TestObject t2){
return t;
}
}
and then call:
BinaryOperator<TestObject> binary = TestObject::testStatic;
Ok it compiled fine. What about if we need an instance method? Lets update TestObject with instance method:
public class TestObject {
public final TestObject testInstance(TestObject t, TestObject t2){
return t;
}
public static final TestObject testStatic(TestObject t, TestObject t2){
return t;
}
}
Now we can access instance as below:
TestObject testObject = new TestObject();
BinaryOperator<TestObject> binary = testObject::testInstance;
This code compiles fine, but below one not:
BinaryOperator<TestObject> binary = TestObject::testInstance;
My eclipse tell me "Cannot make a static reference to the non-static method testInstance(TestObject, TestObject) from the type TestObject ..."
Fair enough its an instance method, but if we overload testInstance
as below:
public class TestObject {
public final TestObject testInstance(TestObject t){
return t;
}
public final TestObject testInstance(TestObject t, TestObject t2){
return t;
}
public static final TestObject testStatic(TestObject t, TestObject t2){
return t;
}
}
And call:
BinaryOperator<TestObject> binary = TestObject::testInstance;
The code will just compile fine. Because it will call testInstance
with single parameter instead of double one. Ok so what happened our two parameter? Lets printout and see:
public class TestObject {
public TestObject() {
System.out.println(this.hashCode());
}
public final TestObject testInstance(TestObject t){
System.out.println("Test instance called. this.hashCode:"
+ this.hashCode());
System.out.println("Given parameter hashCode:" + t.hashCode());
return t;
}
public final TestObject testInstance(TestObject t, TestObject t2){
return t;
}
public static final TestObject testStatic(TestObject t, TestObject t2){
return t;
}
}
Which will output:
1418481495
303563356
Test instance called. this.hashCode:1418481495
Given parameter hashCode:303563356
Ok so JVM is smart enough to call param1.testInstance(param2). Can we use testInstance
from another resource but not TestObject, i.e.:
public class TestUtil {
public final TestObject testInstance(TestObject t){
return t;
}
}
And call:
BinaryOperator<TestObject> binary = TestUtil::testInstance;
It will just not compile and compiler will tell: "The type TestUtil does not define testInstance(TestObject, TestObject)". So compiler will look for a static reference if it is not the same type. Ok what about polymorphism? If we remove final modifiers and add our SubTestObject class:
public class SubTestObject extends TestObject {
public final TestObject testInstance(TestObject t){
return t;
}
}
And call:
BinaryOperator<TestObject> binary = SubTestObject::testInstance;
It will not compile as well, compiler will still look for static reference. But below code will compile fine since it is passing is-a test:
public class TestObject {
public SubTestObject testInstance(Object t){
return (SubTestObject) t;
}
}
BinaryOperator<TestObject> binary = TestObject::testInstance;
*I am just studying so I have figured out by try and see, feel free to correct me if I am wrong
Run this command in your terminal:
$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$
You should be able to do something like this:
var http = require('http');
var url = require('url');
http.createServer(function(req,res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query); //{Object}
res.end("End")
})
While @Jared's answer for incrementing works for 0.5
step size, it fails for other step sizes due to rounding issues:
np.arange(11, 17, 0.1).tolist()
# [11.0,11.1,11.2,11.299999999999999, ... 16.79999999999998, 16.899999999999977]
Instead I needed something like this myself, working not just for 0.5
:
# Example 11->16 step 0.5
s = 11
e = 16
step = 0.5
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
# Example 0->1 step 0.1
s = 0
e = 1
step = 0.1
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
This will work in all versions of jquery.
//-- Check if there's no checked radio button
if ($('#radio_button').is(':checked') === false ) {
//-- if none, Do something here
}
To activate some function when a certain radio button is checked.
// get it from your form or parent id
if ($('#your_form').find('[name="radio_name"]').is(':checked') === false ) {
$('#your_form').find('[name="radio_name"]').filter('[value=' + checked_value + ']').prop('checked', true);
}
your html
$('document').ready(function() {
var checked_value = 'checked';
if($("#your_form").find('[name="radio_name"]').is(":checked") === false) {
$("#your_form")
.find('[name="radio_name"]')
.filter("[value=" + checked_value + "]")
.prop("checked", true);
}
}
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="your_form">
<input id="user" name="radio_name" type="radio" value="checked">
<label for="user">user</label>
<input id="admin" name="radio_name" type="radio" value="not_this_one">
<label for="admin">Admin</label>
</form>
_x000D_
If your element is not directly on you scene go back to Parent to remove it
function removeEntity(object) {
var selectedObject = scene.getObjectByName(object.name);
selectedObject.parent.remove( selectedObject );
}
You can use primitive collections from Eclipse Collections and avoid boxing altogether.
DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();
If you can't or don't want to initialize a DoubleList
:
List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();
Note: I am a contributor to Eclipse Collections.
dynamic np = Py.Import("numpy")
dynamic
when applying numerical operators on them. This provides type safety and avoids limitations of generics. This is in essence *duck typing:T y = x * (dynamic)x
, where typeof(x) is T
If you want to create a new A
you can use INTO
;
select * into A from dbo.myView
let plainString = "foo"
let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v
if let decodedData = Data(base64Encoded: base64String!),
let decodedString = String(data: decodedData, encoding: .utf8) {
print(decodedString) // foo
}
let plainString = "foo"
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo
NSString *plainString = @"foo";
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo
Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found". A, B
means "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e. X=3, write('X is 3'),nl
will print 'X is 3' when X=3, and will do nothing if X=2).
Use brackets to group the OR statements.
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
You can also use IN
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");
A complete answer for React Router v6 or version 6 just in case needed.
import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";
/*Routes is used to be Switch*/
const Router = () => {
return (
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="games" element={<Games />} />
<Route path="game-details/:id" element={<GameDetails />} />
<Route path="dashboard" element={<Dashboard />}>
<Route path="/" element={<DashboardDefaultContent />} />
<Route path="inbox" element={<Inbox />} />
<Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
<Route path="*" element={<NotFound />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
);
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";
const Dashboard = () => {
return (
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<DashboardSidebarNavigation />
<Outlet />
</Grid>
);
};
export default Dashboard;
Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo
I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:
Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.
Parent container has to have this:
position: relative;
Button itself has to have this:
position: relative;
bottom: 20px;
right: 20px;
or whatever you like
// Java 8
int vInt = Integer.parseUnsignedInt("4294967295");
System.out.println(vInt); // -1
String sInt = Integer.toUnsignedString(vInt);
System.out.println(sInt); // 4294967295
long vLong = Long.parseUnsignedLong("18446744073709551615");
System.out.println(vLong); // -1
String sLong = Long.toUnsignedString(vLong);
System.out.println(sLong); // 18446744073709551615
// Guava 18.0
int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
System.out.println(vIntGu); // -1
String sIntGu = UnsignedInts.toString(vIntGu);
System.out.println(sIntGu); // 4294967295
long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
System.out.println(vLongGu); // -1
String sLongGu = UnsignedLongs.toString(vLongGu);
System.out.println(sLongGu); // 18446744073709551615
/**
Integer - Max range
Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1
Long - Max range
Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
*/
Absolutely.
If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.
The following are some ways you can create lists.
This will create a list with fixed size, adding/removing elements is not possible, it will throw a java.lang.UnsupportedOperationException
if you try to do so.
List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
The following version is a simple list where you can add/remove any number of elements.
List<String> list = new ArrayList<>();
This is how to create a LinkedList
in java, If you need to do frequent insertion/deletion of elements on the list, you should use LinkedList
instead of ArrayList
List<String> linkedList = new LinkedList<>();
Isn't it better with a group by? Something like:
SELECT COUNT(*) FROM t1 GROUP BY keywork;
You could also just compile the following program and run it on your machine.
#include <gtk/gtk.h>
#include <glib/gprintf.h>
int main(int argc, char *argv[])
{
/* Initialize GTK */
gtk_init (&argc, &argv);
g_printf("%d.%d.%d\n", gtk_major_version, gtk_minor_version, gtk_micro_version);
return(0);
}
compile with ( assuming above source file is named version.c):
gcc version.c -o version `pkg-config --cflags --libs gtk+-2.0`
When you run this you will get some output. On my old embedded device I get the following:
[root@n00E04B3730DF n2]# ./version
2.10.4
[root@n00E04B3730DF n2]#
Given the R data.frame:
> df1
a b c
1 1 1 0
2 1 0 0
3 0 1 0
4 0 0 0
Shuffle row-wise:
> df2 <- df1[sample(nrow(df1)),]
> df2
a b c
3 0 1 0
4 0 0 0
2 1 0 0
1 1 1 0
By default sample()
randomly reorders the elements passed as the first argument. This means that the default size is the size of the passed array. Passing parameter replace=FALSE
(the default) to sample(...)
ensures that sampling is done without replacement which accomplishes a row wise shuffle.
Shuffle column-wise:
> df3 <- df1[,sample(ncol(df1))]
> df3
c a b
1 0 1 1
2 0 1 0
3 0 0 1
4 0 0 0
A static variable declared in a header file outside of the class would be file-scoped
in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.
A static class variable on the other hand is class-scoped
and the same static variable is available to every compilation unit that includes the header containing the class with static variable.
to match both 48-bit EUI-48 and 64-bit EUI-64 MAC addresses:
/\A\h{2}([:\-]?\h{2}){5}\z|\A\h{2}([:\-]?\h{2}){7}\z/
where \h is a character in [0-9a-fA-F]
or:
/\A[0-9a-fA-F]{2}([:\-]?[0-9a-fA-F]{2}){5}\z|\A[0-9a-fA-F]{2}([:\-]?[0-9a-fA-F]{2}){7}\z/
this allows '-' or ':' or no separator to be used
The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.
For example:
user_model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name:String,
email:String,
password:String,
phone:Number,
_enabled:Boolean
});
module.exports = mongoose.model('users', userSchema);
check.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
User.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere
})
});
insert.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
mongoose.connect('mongodb://localhost/event-db');
var new_user = new User({
name:req.body.name
, email: req.body.email
, password: req.body.password
, phone: req.body.phone
, _enabled:false
});
new_user.save(function(err){
if(err) console.log(err);
});
To enable msbuild
in Command Prompt, you simply have to add the directory of the msbuild.exe
install on your machine to the PATH
environment variable.
You can access the environment variables by:
PATH
For reference, my path was C:\Windows\Microsoft.NET\Framework\v4.0.30319
As of MSBuild 12 (2013)/VS 2013/.NET 4.5.1+ and onward MSBuild is now installed as a part of Visual Studio.
For VS2015 the path was %ProgramFiles(x86)%\MSBuild\14.0\Bin
For VS2017 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin
For VS2019 the path was %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin
Push only single file
git commit -m "Message goes here" filename
Push only two files.
git commit -m "Message goes here" file1 file2
colrm x
For example, if you need the first 100 characters:
cat file |colrm 101
It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm
.
You can use
call script.bat
or just
script.bat
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
I use sym links all the time between my document root and git repo directory. I like to keep them separate. On windows I use mklink /j option. The junction seems to let git behave normally:
>mklink /j <location(path) of link> <source of link>
for example:
>mklink /j c:\gitRepos\Posts C:\Bitnami\wamp\apache2\htdocs\Posts
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.
A common convention is to put the result of a build into a build
, target
or bin
directory.
The Jenkins archiver can use globs (target/*.jar
) to easily pick up the right file even if you have a unique name per build.
I know this is an old question but I figured out I should pitch my answer anyways.
The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.
using System;
private bool ValidateText(string text){
char[] characters = text.ToCharArray();
foreach(char c in characters){
if(!char.IsNumber(c))
return false;
}
return true;
}
Below are the commands for Ubuntu user to authorise devices once developer option is ON.
sudo ~/Android/Sdk/platform-tools/adb kill-server
sudo ~/Android/Sdk/platform-tools/adb start-server
On Device:
Connect your device now and you must only accept request, on your phone.
use g++
instead of gcc
.
Lookup pom.xml > project tag > build tag.
I would like solution below.
<artifactId>bird</artifactId>
<name>bird</name>
<build>
...
<finalName>${project.artifactId}</finalName>
OR
<finalName>${project.name}</finalName>
...
</build>
Worked for me. ^^
Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:
<div id="outer">
<div id="inner">
content
</div>
</div>
The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.
#outer {
position: fixed;
left: 50%; // % of window
}
#inner {
position: relative;
left: -50%; // % of outer (which auto-matches inner width)
}
This approach is similar to Quentin's, but inner can be of variable size.
Suggesting an alternative answer here:
Making a separate module for the Pipe is not required, but is definitely an alternative. Check the official docs footnote: https://angular.io/guide/pipes#custom-pipes
You use your custom pipe the same way you use built-in pipes.
You must include your pipe in the declarations array of the AppModule . If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.
All you have to do is add your pipe to the declarations array, and the providers array in the module
where you want to use the Pipe.
declarations: [
...
CustomPipe,
...
],
providers: [
...
CustomPipe,
...
]
Try Catch exists via workaround in VBScript:
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
try this
.+?efg
Query :
select REGEXP_REPLACE ('abcdefghijklmn','.+?efg', '') FROM dual;
output :
hijklmn
What about a new end point > /api/members/count which just calls Members.Count() and returns the result
Thank you all for the help. Here is a breakdown of how I fixed my problem:
Right click on your project > Properties
Under Application change the target Framework. In my case ImageSharp was using .Net 4.6.1. You can find this in your packages.config.
Go to your project references. You'll notice SixLabors has a yellow triangle. You have to update the NuGet package.
Right click on References > Manage NuGet Packages.
Update SixLabors.
You might have slight code updates (see below) but this fixed my problem.
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT()
in the same way.
Bear in mind if you are using this in a WHERE
clause that the RIGHT()
can't use any indexes.
Use entrySet
,
/**
*Output:
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08
B's new balance: 1123.22
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String args[]) {
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("A", new Double(3434.34));
hm.put("B", new Double(123.22));
hm.put("C", new Double(1378.00));
hm.put("D", new Double(99.22));
hm.put("E", new Double(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("B");
hm.put("B", balance + 1000);
System.out.println("B's new balance: " + hm.get("B"));
}
}
see complete example here:
Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:
@"first" @"second"
And it will result in:
@"firstsecond"
You can not use it with NSString objects, only with literals, but it can be useful in some cases.
Request-scoped beans can be autowired with the request object.
private @Autowired HttpServletRequest request;
In my case the cause was AdBlock extension.
The request to server went through and I got the response but I could not see the request cookies due to "Provisional headers.." being shown in Dev tools. After disabling AdBlock for the site, the warning went away and dev tools started to show the cookies again.
For the change to take effect, it was also necessary to close the Dev tools and refresh the page
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
You can do almost everything from a utility provided as part of WAMPServer.
Create a folder inside to contain your project.site. This can be under the C:\wamp\www\
directory or in a completely seperate folder like C:\websites
.
Create a folder inside the location you have chosen EG C:\websites\project1\www
or under the c:\wamp\www\project1\www
Now open localhost wampmanager->localhost
and click on the link Add a Virtual Host
under the TOOLS section on the homepage.
You will see a page like this:
Fill in the fields as specified by the instructions above each field
The Virtual Host config will have been created for you.
Now you must restart the DNS Cache. You can do this from the wampmanager menus like this right click wampmanager->Tools->Restart DNS
. The DNS Cache will be restarted and then Apache will also be stopped and restarted. When the wampmanager icon goes green again all is completed.
Now you must create a simple index.php
file or install your site into the folder you created above.
Assuming your VH was called project.dev
You should see that name under the Your Virtual Hosts Section of the WAMPServer homepage.
You can launch the site from this menu, or just use the new Domain Name in the address bar EG project1.dev
and the site shoudl launch.
There has been a change of concept in WampServer 2.5 and above and there is a good reason for this change!
In WampServer it is now STRONGLY encouraged to create a Virtual Host for each of your projects, even if you hold them in a \wamp\www\subfolder
structure.
The WampServer home page ( \wamp\www\index.php
) now expects you to have created a Virtual Host for all your projects and will therefore work properly only if you do so.
History
In order to make life easier for beginners using WampServer to learn PHP Apache and MySQL it was suggested that you create subfolders under the \wamp\www\
folder.
wamp
|-- www
|-- Chapter1
|-- Chapter2
|-- etc
These subfolders would then show as links in the WampServer Homepage under a menu called 'Your Projects' and these links would contain a link to localhost/subfoldername
.
Acceptable only for simple tutorials
This made life easy for the complete beginner, and was perfectly acceptable for example for those following tutorials to learn PHP coding. However it was never intended for use when developing a real web site that you would later want to copy to your live hosted server. In fact if you did use this mechanism it often caused problems as the live sites configuration would not match your development configuration.
The Problem for real website development.
The reason for this is of course that the default DocumentRoot setting for wamp is
DocumentRoot "c:/wamp/www/"
regardless of what your subfolder was called. This ment that often used PHP code that queried the structure or your site received different information when running on your development WampServer to what it would receive when running on a live hosted server, where the DocumentRoot configuration points to the folder at the top of the website file hierarchy. This kind of code exists in many frameworks and CMS's for example WordPress and Joomla etc.
For Example
Lets say we have a project called project1 held in wamp\www\project1
and run incorrectly as localhost/project1/index.php
This is what would be reported by some of the PHP command in question:
$_SERVER['HTTP_HOST'] = localhost
$_SERVER['SERVER_NAME'] = localhost
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www
Now if we had correctly defined that site using a Virtual Host definition and ran it as http://project1
the results on the WAMPServer devlopment site will match those received when on a live hosted environment.
$_SERVER['HTTP_HOST'] = project1
$_SERVER['SERVER_NAME'] = project1
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www/project1
Now this difference may seem trivial at first but if you were to use a framework like WordPress or one of the CMS's like Joomla for example, this can and does cause problems when you move your site to a live server.
Actually this should work basically the same for any wndows Apache server, with differences only in where you may find the Apache config files.
There are 3 steps to create your first Virtual Host in Apache, and only 2 if you already have one defined.
Step 1, Create the Virtual Host definition(s)
Edit the file called httpd-hosts.conf
which for WampServer lives in
\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
(Apache version numbers may differ, engage brain before continuing)
If this is the first time you edit this file, remove the default example code, it is of no use.
I am assuming we want to create a definition for a site called project1 that lives in
\wamp\www\project1
Very important, first we must make sure that localhost still works so that is the first VHOST definition we will put in this file.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www"
ServerName localhost
ServerAlias localhost
<Directory "c:/wamp/www">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
Now we define our project: and this of course you do for each of your projects as you start a new one.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www/project1"
ServerName project1
<Directory "c:/wamp/www/project1">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
NOTE: That each Virtual Host as its own DocumentRoot
defined. There are also many other parameters you can add to a Virtual Hosts definition, check the Apache documentation.
Small aside
The way virtual hosts work in Apache: The first definition in this file will also be the default site, so should the domain name used in the browser not match any actually defined virtually hosted domain, making localhost the first domain in the file will therefore make it the site that is loaded if a hack attempt just uses your IP Address. So if we ensure that the Apache security for this domain is ALWAYS SET TO
Require local
any casual hack from an external address will receive an error and not get into your PC, but should you misspell a domain you will be shown the WampServer homepage, because you are on the same PC as WampServer and therfore local
.
Step 2:
Add your new domain name to the HOSTS file. Now we need to add the domain name that we have used in the Virtual Host definition to the HOSTS file so that windows knows where to find it. This is similiar to creating a DNS A record, but it is only visible in this case on this specific PC.
Edit C:\windows\system32\drivers\etc\hosts
The file has no extension and should remain that way. Watch out for notepad, as it may try and add a .txt
extension if you have no better editor.
I suggest you download Notepad++, its free and a very good editor.
Also this is a protected file so you must edit it with administrator privileges, so launch you editor using the Run as Administrator menu option.
The hosts file should look like this when you have completed these edits
127.0.0.1 localhost
127.0.0.1 project1
::1 localhost
::1 project1
Note that you should have definitions in here for the IPV4 loopback address 127.0.0.1
and also the IPV6 loopback address ::1
as Apache is now IPV6 aware and the browser will use either IPV4 or IPV6 or both. I have no idea how it decides which to use, but it can use either if you have the IPV6 stack turned on, and most window OS's do as of XP SP3.
Now we must tell windows to refresh its domain name cache, so launch a command window again using the Run as Administrator menu option again, and do the following.
net stop dnscache
net start dnscache
This forces windows to clear its domain name cache and reload it, in reloading it will re-read the HOSTS file so now it knows about the domain project1
.
Step 3: Uncomment the line in httpd.conf that includes the Virtual Hosts definition file.
Edit your httpd.conf, use the wampmanager.exe menus to make sure you edit the correct file.
Find this line in httpd.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
And just remove the #
to uncomment that line.
To activate this change in you running Apache we must now stop and restart the Apache service.
wampmanager.exe -> Apache -> Service -> Restart Service
Now if the WAMP icon in the system tray does not go GREEN again, it means you have probably done something wrong in the \wamp\bin\apache\apache2.4.9\conf\extra\httpd-hosts.conf
file.
If so here is a useful mechanism to find out what is wrong. It uses a feature of the Apache exe (httpd.exe) to check its config files and report errors by filename and line numbers.
Launch a command window.
cd \wamp\bin\apache\apache2.4.9\bin
httpd -t
So fix the errors and retest again until you get the output
Syntax OK
Now there is one more thing.
There are actually 2 new menu items on the wampmanager menu system. One called 'My Projects' which is turned on by default. And a second one, called 'My Virtual Hosts', which is not activated by default.
'My Projects' will list any sub directory of the \wamp\www directory and provide a link to launch the site in that sub directory. As I said earlier, it launches 'project1` and not 'localhost/project1' so to make the link work we must create a Virtual Host definition to make this link actually launch that site in your browser, without the Virtual Host definition it's likely to launch a web search for the site name as a keyword or just return a site not found condition.
The 'My Virtual Hosts' menu item is a little different. It searches the file that is used to define Virtual Hosts ( we will get to that in a minute ) and creates menu links for each ServerName parameter it finds and creates a menu item for each one. This may seem a little confusing as once we create a Virtual Host definition for the sub directories of the \wamp\www folder some items will appear on both of the 'My Projects' menu and the 'My Virtual Hosts' menu's.
How do I turn this other 'My Virtual Hosts' menu on?
;WAMPPROJECTSUBMENU
, its in the '[Menu.Left]' section.;WAMPVHOSTSUBMENU
either before or after the ;WAMPPROJECTSUBMENU
parameter.Big Note The new menu will only appear if you already have some Virtual Hosts defined! Otherwise you will see no difference until you define a VHOST.
Now if you take this to its logical extension
You can now move your web site code completely outside the \wamp\
folder structure simply by changing the DocumentRoot parameter in the VHOST definition. So for example you could do this:
Create a folder on the wamp disk or any other disk ( beware of network drive, they are a bit more complicated)
D:
MD websites
CD websites
MD example.com
CD example.com
MD www
You now copy your site code to, or start creating it in the \websites\example.com\www
folder and define your VHOST like this:
<VirtualHost *:80>
DocumentRoot "d:/websites/example.com/www"
ServerName example.dev
ServerAlias www.example.dev
<Directory "d:/websites/example.com/www">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
php_flag display_errors Off
php_flag log_errors On
php_value max_upload_size 40M
php_value max_execution_time 60
php_value error_log "d:/wamp/logs/example_com_phperror.log"
</VirtualHost>
Then add this new development domain to the HOSTS file:
127.0.0.1 localhost
::1 localhost
127.0.0.1 project1
::1 project1
127.0.0.1 example.dev
::1 example.dev
NOTE: It is not a good idea to use a ServerName or ServerAlias that is the same as your live domain name, as if we had used example.com as the ServerName it would mean we could no longer get to the real live site from this PC as it would direct example.com to 127.0.0.1 i.e. this PC and not out onto the internet.
ALSO: See that I have allowed this site to be accessed from the internet from within the VHOST definitions, this change will apply to only this site and no other. Very useful for allowing a client to view your changes for an hour or so without having to copy them to the live server. This does mean that we have to edit this file manually to turn this access on and off rather than use the Put Online/Offline menu item on wampmanager.
Also I have added some modifications to the PHP config, again that will only apply to this one site. Very useful when maintaining a site with specific requirement unlike all the other sites you maintain. I guess we can assume from the parameters used that it has a long running page in it somewhere and it is very badly written and will not run with errors being displayed on the browser without making a horrible mess of the page. Believe me sites like this exist and people still want them maintained badly. But this mean we only have to change these parameters for this specific site and not globally to all Virtual sites running on WampServer.
You can do something like this:
.flex {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.flex>div {_x000D_
flex: 1 0 50%;_x000D_
}_x000D_
_x000D_
.flex>div:first-child {_x000D_
flex: 0 1 100%;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div>Hi</div>_x000D_
<div>Hello</div>_x000D_
<div>Hello 2</div>_x000D_
</div>
_x000D_
Here is a demo: http://jsfiddle.net/73574emn/1/
This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basis
to be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;
Like Luc-Oliver, NullData, and a few others have said here, let
defines immutable data while var
defines mutable data. Any func
that can be called on the variable that is marked mutating
can only be called if it is a var
variable (compiler will throw error). This also applies to func
's that take in an inout
variable.
However, let
and var
also mean that the variable cannot be reassigned. It has two meanings, both with very similar purposes
The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css
file.
Firstly, in case of using a default navigation bar (the gray one), the .navbar-default
class will be used and the text is colored as dark gray.
.navbar-default .navbar-text {
color: #777;
}
The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.
.navbar-inverse .navbar-text {
color: #999;
}
So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.
NOTE: you could also use the customizer provided by Twitter Bootstrap
, in the Navbar
section.
JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. Before Stack-Walking API, common ways of accessing stack frames were:
Throwable::getStackTrace
andThread::getStackTrace
return an array ofStackTraceElement
objects, which contain the class name and method name of each stack-trace element.
SecurityManager::getClassContext
is a protected method, which allows aSecurityManager
subclass to access the class context.JDK-internal
sun.reflect.Reflection::getCallerClass
method which you shouldn't use anyway
Using these APIs are usually inefficient:
These APIs require the VM to eagerly capture a snapshot of the entire stack, and they return information representing the entire stack. There is no way to avoid the cost of examining all the frames if the caller is only interested in the top few frames on the stack.
In order to find the immediate caller's class, first obtain a StackWalker
:
StackWalker walker = StackWalker
.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Then either call the getCallerClass()
:
Class<?> callerClass = walker.getCallerClass();
or walk
the StackFrame
s and get the first preceding StackFrame
:
walker.walk(frames -> frames
.map(StackWalker.StackFrame::getDeclaringClass)
.skip(1)
.findFirst());
Highlight the cells, format cells, select Custom then select zero.
Just for punctuality purpose and extend a bit Tim answer.
From official documentation:
The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.
This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:
app.listen = function() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
If you want to set filemode to false in config files recursively (including submodules) :
find -name config | xargs sed -i -e 's/filemode = true/filemode = false/'
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
A one line example using Joda-Time library:
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(new DateTime().toGregorianCalendar());
Credit to Nicolas Mommaerts from his comment in the accepted answer.
I solved this problem through the following:
string userId="";
for example: in C#
userId= "5,44,72,81,126";
and Send to SQL-Server
SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
NVARCHAR(Max)
) to Table.CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL );
SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');
You can use Array.prototype.find function in javascript. Array find MDN.
So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.
Ex.
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find(
function(str) {
return str == value;
}
);
or using lambda expression it will become much shorter
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find((str) => str === value);
Let me explain with an example and you would be able to see how it works.
Assuming you have the following table DIM_EQUIPMENT:
VIN MAKE MODEL YEAR COLOR
-----------------------------------------
1234ASDF Ford Taurus 2008 White
1234JKLM Chevy Truck 2005 Green
5678ASDF Ford Mustang 2008 Yellow
Run below SQL
SELECT VIN,
MAKE,
MODEL,
YEAR,
COLOR ,
COUNT(*) OVER (PARTITION BY YEAR) AS COUNT2
FROM DIM_EQUIPMENT
The result would be as below
VIN MAKE MODEL YEAR COLOR COUNT2
----------------------------------------------
1234JKLM Chevy Truck 2005 Green 1
5678ASDF Ford Mustang 2008 Yellow 2
1234ASDF Ford Taurus 2008 White 2
See what happened.
You are able to count without Group By on YEAR and Match with ROW.
Another Interesting WAY to get same result if as below using WITH Clause, WITH works as in-line VIEW and can simplify the query especially complex ones, which is not the case here though since I am just trying to show usage
WITH EQ AS
( SELECT YEAR AS YEAR2, COUNT(*) AS COUNT2 FROM DIM_EQUIPMENT GROUP BY YEAR
)
SELECT VIN,
MAKE,
MODEL,
YEAR,
COLOR,
COUNT2
FROM DIM_EQUIPMENT,
EQ
WHERE EQ.YEAR2=DIM_EQUIPMENT.YEAR;
Same as accepted answer, But note that it works even with .crt
file and not just .pem
file, just in case if you are not able to find .pem
file location.
openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt
Result:
notAfter=Mar 29 06:15:00 2020 GMT
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
I have the same situation: Visual Studio 2010, no NuGet installed, and an ASP.NET application using System.Web.Mvc version 3.
What worked for me, was to set each C# project that uses System.Web.Mvc, to go to References in the Solution Explorer, and set properties on System.Web.Mvc, with Copy Local to true, and Specific Version to false - the last one caused the Version field to show the current version on that machine.
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
If you are using Bootstrap responsive table, just want to set the maximum width for one particular column and make text wrapping, making the the style of this column as following also works
max-width:someValue;
word-wrap:break-word
Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/
Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.
@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront
. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.
Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..
Method I used to split first_name into first_name and last_name when the data arrived all in the first_name field. This will put only the last word in the last name field, so "john phillips sousa" will be "john phillips" first name and "sousa" last name. It also avoids overwriting any records that have been fixed already.
set last_name=trim(SUBSTRING_INDEX(first_name, ' ', -1)), first_name=trim(SUBSTRING(first_name,1,length(first_name) - length(SUBSTRING_INDEX(first_name, ' ', -1)))) where list_id='$List_ID' and length(first_name)>0 and length(trim(last_name))=0
You could try using Insight a graphical front-end for gdb written by Red Hat Or if you use GNOME desktop environment, you can also try Nemiver.
To disable a warning locally in a block, add
# pylint: disable=C0321
to that block.
Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.
You can use list comprehension:
l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]
or just do the C-style
for loop:
for index, item in enumerate(l):
l[index] = item.strip()
Variation on the builder pattern, using call():
function asyncMethod(arg) {
function innerPromise() { return new Promise((...)=> {...}) }
innerPromise().then(result => {
this.setStuff(result);
}
}
const getInstance = async (arg) => {
let instance = new Instance();
await asyncMethod.call(instance, arg);
return instance;
}
Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances).
// Create marker
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(53, -2.5),
title: 'Some location'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc (full API).
See more source code and example screenshots.
Here is my function for convert a second
,millisecond
to day,hour,minute,second
public static String millisecondToFullTime(long millisecond) {
return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}
public static String secondToFullTime(long second) {
return timeUnitToFullTime(second, TimeUnit.SECONDS);
}
public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
long day = timeUnit.toDays(time);
long hour = timeUnit.toHours(time) % 24;
long minute = timeUnit.toMinutes(time) % 60;
long second = timeUnit.toSeconds(time) % 60;
if (day > 0) {
return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
} else if (hour > 0) {
return String.format("%d:%02d:%02d", hour, minute, second);
} else if (minute > 0) {
return String.format("%d:%02d", minute, second);
} else {
return String.format("%02d", second);
}
}
Testing
public static void main(String[] args) {
System.out.println("60 => " + secondToFullTime(60));
System.out.println("101 => " + secondToFullTime(101));
System.out.println("601 => " + secondToFullTime(601));
System.out.println("7601 => " + secondToFullTime(7601));
System.out.println("36001 => " + secondToFullTime(36001));
System.out.println("86401 => " + secondToFullTime(86401));
}
Output
60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01
Hope it help
Also one can use this:
{% if forloop.first %}
or
{% if forloop.last %}
/// Returns true if its simulator and not a device
public static var isSimulator: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return false
#endif
}
You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/
(very rough example)
#!/usr/bin/expect
set pass "mysecret"
spawn /usr/bin/passwd
expect "password: "
send "$pass"
expect "password: "
send "$pass"
The columns
parameter accepts a collection of column names. You're passing a list containing a dataframe with two rows:
>>> [df[1:]]
[ viz a1_count a1_mean a1_std
1 n 0 NaN NaN
2 n 2 51 50]
>>> df.as_matrix(columns=[df[1:]])
array([[ nan, nan],
[ nan, nan],
[ nan, nan]])
Instead, pass the column names you want:
>>> df.columns[1:]
Index(['a1_count', 'a1_mean', 'a1_std'], dtype='object')
>>> df.as_matrix(columns=df.columns[1:])
array([[ 3. , 2. , 0.816497],
[ 0. , nan, nan],
[ 2. , 51. , 50. ]])
The point of the google-services plugin is to simplify integration of Google features.
Since it only generates android-resources from the google-services.json file, over-complicated gradle-logic negates this point, I think.
So if the Google-docs don’t say which resources are needed for specific Google-features, I would suggest to generate the JSON-file for each relevant buildtype/flavor, see what resources get generated by the plugin and then put those resources manually into their respective src/buildtypeORflavor/res directories.
Delete the references to google-services plugin and the JSON-file after that, and you are done.
For detailed information about the inner workings of google-services gradle-plugin see my other answer:
There is another way to install the pip3: just reinstall 3.6.
For those on OSX, I used the following binary to get libpng and libjpeg installed systemwide:
Because I already had PIL installed (via pip on a virtualenv), I ran:
pip uninstall PIL
pip install PIL --upgrade
This resolved the decoder JPEG not available
error for me.
UPDATE (4/24/14):
Newer versions of pip require additional flags to download libraries (including PIL) from external sources. Try the following:
pip install PIL --allow-external PIL --allow-unverified PIL
See the following answer for additional info: pip install PIL dont install into virtualenv
UPDATE 2:
If on OSX Mavericks, you'll want to set the ARCHFLAGS
flag as @RicardoGonzales comments below:
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install PIL --allow-external PIL --allow-unverified PIL
There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List
Here some basics points about scenarios and functions:
Hope this is of assistance...
Expanding the grep
a bit to give more information in the output, for example, to get the line number in the file where the text is can be done as follows:
find . -type f -name "*.*" -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"
And if you have an idea what the file type is you can narrow your search down by specifying file type extensions to search for, in this case .pas
OR .dfm
files:
find . -type f \( -name "*.pas" -o -name "*.dfm" \) -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searchtext"
Short explanation of the options:
.
in the find
specifies from the current directory.-name
"*.*
" : for all files
( -name "*.pas
" -o -name "*.dfm
" ) : Only the *.pas
OR *.dfm
files, OR specified with -o
-type f
specifies that you are looking for files-print0
and --null
on the other side of the |
(pipe) are the crucial ones, passing the filename from the find
to the grep
embedded in the xargs
, allowing for the passing of filenames WITH spaces in the filenames, allowing grep to treat the path and filename as one string, and not break it up on each space.There is no built in date type in JSON. This looks like the number of seconds / milliseconds from some epoch. If you know the epoch you can create the date by adding on the right amount of time.
You can do it like:
tvHide.setText(Html.fromHtml("<p><span style='text-decoration: underline'>Hide post</span></p>").toString());
Hope this helps
Using GPS with latitude and longitude, we can get the Country code.
If we use telephony, it won't work if we are not using sim card and in locale, based on language, it show the country code in wrong way.
MainActivity.java:
GPSTracker gpsTrack;
public static double latitude = 0;
public static double longitude = 0;
gpsTrack = new GPSTracker(TabHomeActivity.this);
if (gpsTrack.canGetLocation()) {
latitude = gpsParty.getLatitude();
longitude = gpsParty.getLongitude();
Log.e("GPSLat", "" + latitude);
Log.e("GPSLong", "" + longitude);
} else {
gpsTrack.showSettingsAlert();
Log.e("ShowAlert", "ShowAlert");
}
countryCode = getAddress(TabHomeActivity.this, latitude, longitude);
Log.e("countryCode", ""+countryCode);
public String getAddress(Context ctx, double latitude, double longitude) {
String region_code = null;
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
region_code = address.getCountryCode();
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return region_code;
}
GPSTracker.java:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
mContext.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Log:
E/countryCode: IN
Edit: Use Fused Location Provider to get latitude and longitude update for better result.
You can simply use theatol()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *c = "5";
int d = atol(c);
printf("%d\n", d);
}
You can also get through it by the code below:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
For those using Gradle (instead of Maven) :
springBoot {
mainClass = "com.example.Main"
}
Try taking Toolbar and tittle in a separate view. Take a view on right end and given them weight equal to the toolbar weight. In this way your tittle will come in center.
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay"
android:background="@color/white_color">
<LinearLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white_color">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="@color/white_color"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:layout_weight="0.2"
app:contentInsetStartWithNavigation="0dp"
app:navigationIcon="@color/greyTextColor">
</android.support.v7.widget.Toolbar>
<com.an.customfontview.CustomTextView
android:id="@+id/headingText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center"
android:text="Heading"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/keyboard_number"
android:layout_gravity="center_horizontal|center_vertical"
app:textFontPath="fonts/regular.ttf" />
<ImageView
android:id="@+id/search_icon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:layout_weight="0.2"
android:layout_gravity="center_horizontal|center_vertical"
android:src="@drawable/portfolio_icon"/>
</LinearLayout>
</android.support.design.widget.AppBarLayout>
In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting
In your Model just set:
protected $casts = [
'my_custom_datetime_field' => 'datetime'
];
And then in your blade template you can use the format()
method:
{{ $my_custom_datetime_field->format('d. m. Y') }}
You could also use regex to delete all the console.log() calls in your code if they're no longer required. Any decent IDE will allow you to search and replace these across an entire project, and allow you to preview the matches before committing the change.
\s*console\.log\([^)]+\);
There's a distinction to me that scp
is always encrypted with ssh (secure shell), while rsync
isn't necessarily encrypted. More specifically, rsync
doesn't perform any encryption by itself; it's still capable of using other mechanisms (ssh for example) to perform encryption.
In addition to security, encryption also has a major impact on your transfer speed, as well as the CPU overhead. (My experience is that rsync
can be significantly faster than scp
.)
Check out this post for when rsync
has encryption on.
I needed to get both USB and TCPIP working for ADB (don't ask), so I did the following (using directions others have posted from xda-developers)
Using adb shell
:
su
#Set the port number for adbd
setprop service.adb.tcp.port 5555
#Run the adbd daemon *again* instead of doing stop/start, so there
#are two instances of adbd running.
adbd &
#Set the port back to USB, so the next time ADB is started it's
#on USB again.
setprop service.adb.tcp.port -1
exit
If you are using Java, you could just replace the x00 characters before the insert like following:
myValue.replaceAll("\u0000", "")
The solution was provided and explained by Csaba in following post:
https://www.postgresql.org/message-id/1171970019.3101.328.camel%40coppola.muc.ecircle.de
Respectively:
in Java you can actually have a "0x0" character in your string, and that's valid unicode. So that's translated to the character 0x0 in UTF8, which in turn is not accepted because the server uses null terminated strings... so the only way is to make sure your strings don't contain the character '\u0000'.
I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
Change it to
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
</web-app>
save the project, and your error would gone.
After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.
Hopefully error would be gone then.
Thanks
I did some searching on the web, and this are some ways that I found:
The easiest way is using curve without predefined function
curve(x^2, from=1, to=50, , xlab="x", ylab="y")
You can also use curve when you have a predfined function
eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")
If you want to use ggplot,
library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) +
stat_function(fun=eq)
ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
You can look for regular expression
Regex.IsMatch(str, @"^[a-zA-Z]+$");
Use something like this
$.getJSON("../../data/file.json", function(json) {
console.log(json); // this will show the info in firebug console
alert(json);
});
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
If this is the offending line:
db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
Then it's because there is no object in Responses
for which the ResponseId == item.ResponseId
, and you can't get the First()
record if there are no matches.
Try this instead:
var response
= db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();
if (response != null)
{
// take some alternative action
}
else
temp.Response = response;
The FirstOrDefault()
extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null
.
If any of your markn
columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.
This is what i would consider to be the correct answer.
SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks`
IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?
SUM-ing the entire calculation is tidier than SUM-ing each column individually.
SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks`
FROM student_scorecard
GROUP BY `student`
This issue may be due to the flags of chrome browser. Reset it, it worked for me. chrome://flags Right corner 'Reset all to defaults' button.
Well i found a bit faster and easier version to use
shell_exec('screen -dmS $name_of_screen $command');
and it works.
You can do it converting by the constructor to a string using .toString() :
function getObjectClass(obj){
if (typeof obj != "object" || obj === null) return false;
else return /(\w+)\(/.exec(obj.constructor.toString())[1];}
You can installing the provider dynamically:
1) Download these jars:
bcprov-jdk15on-152.jar
bcprov-ext-jdk15on-152.jar
2) Copy jars to WEB-INF/lib
(or your classpath)
3) Add provider dynamically:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
Security.addProvider(new BouncyCastleProvider());
This will get you the PID of a process by name:
pidof name
Which you can then plug back in to ps for more detail:
ps -p $(pidof name)
Do not include the '.exe' in your file path.
For example:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='path/to/folder/chromedriver')
I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.
After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.
Then just execute your add-migrations or any other commands, it should work.
Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force
The best option would be to put any element you want to be centered in a div
like this:
<div class="center"> <img src="images/logo.png" /> </div>
and css or inline style:
.center { text-align:center }
If you go to C:\Windows\system32\Windowspowershell\v1.0
(and C:\Windows\syswow64\Windowspowershell\v1.0
on x64 machines) in Windows Explorer and double-click powershell.exe
you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe
can be set independently from the default properties.
To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.
Running start powershell
from cmd.exe should start a new console with your default settings.
/*sorry this is the correct */
public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
{
final ByteBuffer bb ;
bb = ByteBuffer.allocate( sizeofintarray * 4);
for(int k = 0; k < sizeofintarray ; k++)
bb.putInt(k * 4, iar[k]);
return bb.array();
}
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
When you are using second approach you are initializing arraylist with its predefined values. Like generally we do ArrayList listofStrings = new ArrayList<>(); Let's say you have an array with values, now you want to convert this array into arraylist.
you need to first get the list from the array using Arrays utils. Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.
List<String> listofOptions = (List<String>) Arrays.asList(options);
then you can user constructoru of an arraylist to instantiate with predefined values.
ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
So your second approach is working that you have passed values which will intantiate arraylist with the list elements.
More over
ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list. If you try to add or remove over Arrays.asList it will give you
UnsupportedOperationException
I think assembly plugin puts the file on class path. The location will be different in in the JAR than you see on disk. Unpack the resulting JAR and look where the file is located there.
the impoved version by @Czarek Tomczak.
allow both std::string
and std::wstring
.
template <typename charType>
void ReplaceSubstring(std::basic_string<charType>& subject,
const std::basic_string<charType>& search,
const std::basic_string<charType>& replace)
{
if (search.empty()) { return; }
typename std::basic_string<charType>::size_type pos = 0;
while((pos = subject.find(search, pos)) != std::basic_string<charType>::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.
Here is how I did it:
d3.select("div#chartId")_x000D_
.append("div")_x000D_
// Container class to make it responsive._x000D_
.classed("svg-container", true) _x000D_
.append("svg")_x000D_
// Responsive SVG needs these 2 attributes and no width and height attr._x000D_
.attr("preserveAspectRatio", "xMinYMin meet")_x000D_
.attr("viewBox", "0 0 600 400")_x000D_
// Class to make it responsive._x000D_
.classed("svg-content-responsive", true)_x000D_
// Fill with a rectangle for visualization._x000D_
.append("rect")_x000D_
.classed("rect", true)_x000D_
.attr("width", 600)_x000D_
.attr("height", 400);
_x000D_
.svg-container {_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
width: 100%;_x000D_
padding-bottom: 100%; /* aspect ratio */_x000D_
vertical-align: top;_x000D_
overflow: hidden;_x000D_
}_x000D_
.svg-content-responsive {_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
top: 10px;_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
svg .rect {_x000D_
fill: gold;_x000D_
stroke: steelblue;_x000D_
stroke-width: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<div id="chartId"></div>
_x000D_
Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.
More info / tutorials:
http://thenewcode.com/744/Make-SVG-Responsive
http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php
Disclaimer: I work for a company, Particle Code, that makes a cross-platform framework. There are a ton of companies in this space. New ones seem to spring up every week. Good news for you: you have a lot of choices.
These frameworks take different approaches, and many of them are fundamentally designed to solve different problems. Some are focused on games, some are focused on apps. I would ask the following questions:
What do you want to write? Enterprise application, personal productivity application, puzzle game, first-person shooter?
What kind of development environment do you prefer? IDE or plain ol' text editor?
Do you have strong feelings about programming languages? Of the frameworks I'm familiar with, you can choose from ActionScript, C++, C#, Java, Lua, and Ruby.
My company is more in the game space, so I haven't played as much with the JavaScript+CSS frameworks like Titanium, PhoneGap, and Sencha. But I can tell you a bit about some of the games-oriented frameworks. Games and rich internet applications are an area where cross-platform frameworks can shine, because these applications tend to place more importance of being visually unique and less on blending in with native UIs. Here are a few frameworks to look for:
Unity www.unity3d.com is a 3D games engine. It's really unlike any other development environment I've worked in. You build scenes with 3D models, and define behavior by attaching scripts to objects. You can script in JavaScript, C#, or Boo. If you want to write a 3D physics-based game that will run on iOS, Android, Windows, OS X, or consoles, this is probably the tool for you. You can also write 2D games using 3D assets--a fine example of this is indie game Max and the Magic Marker, a 2D physics-based side-scroller written in Unity. If you don't know it, I recommend checking it out (especially if there are any kids in your household). Max is available for PC, Wii, iOS and Windows Phone 7 (although the latter version is a port, since Unity doesn't support WinPhone). Unity comes with some sample games complete with 3D assets and textures, which really helps getting up to speed with what can be a pretty complicated environment.
Corona www.anscamobile.com/corona is a 2D games engine that uses the Lua scripting language and supports iOS and Android. The selling point of Corona is the ability to write physics-based games very quickly in few lines of code, and the large number of Corona-based games in the iOS app store is a testament to its success. The environment is very lean, which will appeal to some people. It comes with a simulator and debugger. You add your text editor of choice, and you have a development environment. The base SDK doesn't include any UI components, like buttons or list boxes, but a CoronaUI add-on is available to subscribers.
The Particle SDK www.particlecode.com is a slightly more general cross-platform solution with a background in games. You can write in either Java or ActionScript, using a MVC application model. It includes an Eclipse-based IDE with a WYSIWYG UI editor. We currently support building for Android, iOS, webOS, and Windows Phone 7 devices. You can also output Flash or HTML5 for the web. The framework was originally developed for online multiplayer social games, such as poker and backgammon, and it suits 2D games and apps with complex logic. The framework supports 2D graphics and includes a 2D physics engine.
NB:
Today we announced that Particle Code has been acquired by Appcelerator, makers of the Titanium cross-platform framework.
...
As of January 1, 2012, [Particle Code] will no longer officially support the [Particle SDK] platform.
In terms of learning curve, I'd say that Unity had the steepest learning curve (for me), Corona was the simplest, and Particle and Airplay are somewhere in between.
Another interesting point is how the frameworks handle different form factors. Corona supports dynamic scaling, which will be familiar to Flash developers. This is very easy to use but means that you end up wasting screen space when going from a 4:3 screen like the iPhone to a 16:9 like the new qHD Android devices. The Particle SDK's UI editor lets you design flexible layouts that scale, but also lets you adjust the layouts for individual screen sizes. This takes a little more time but lets you make the app look custom made for each screen.
Of course, what works for you depends on your individual taste and work style as well as your goals -- so I recommend downloading a couple of these tools and giving them a shot. All of these tools are free to try.
Also, if I could just put in a public service announcement -- most of these tools are in really active development. If you find a framework you like, by all means send feedback and let them know what you like, what you don't like, and features you'd like to see. You have a real opportunity to influence what goes into the next versions of these tools.
Hope this helps.
I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" />
seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.
None of the answers so far describe when one can use a forward declaration of a class template. So, here it goes.
A class template can be forwarded declared as:
template <typename> struct X;
Following the structure of the accepted answer,
Here's what you can and cannot do.
What you can do with an incomplete type:
Declare a member to be a pointer or a reference to the incomplete type in another class template:
template <typename T>
class Foo {
X<T>* ptr;
X<T>& ref;
};
Declare a member to be a pointer or a reference to one of its incomplete instantiations:
class Foo {
X<int>* ptr;
X<int>& ref;
};
Declare function templates or member function templates which accept/return incomplete types:
template <typename T>
void f1(X<T>);
template <typename T>
X<T> f2();
Declare functions or member functions which accept/return one of its incomplete instantiations:
void f1(X<int>);
X<int> f2();
Define function templates or member function templates which accept/return pointers/references to the incomplete type (but without using its members):
template <typename T>
void f3(X<T>*, X<T>&) {}
template <typename T>
X<T>& f4(X<T>& in) { return in; }
template <typename T>
X<T>* f5(X<T>* in) { return in; }
Define functions or methods which accept/return pointers/references to one of its incomplete instantiations (but without using its members):
void f3(X<int>*, X<int>&) {}
X<int>& f4(X<int>& in) { return in; }
X<int>* f5(X<int>* in) { return in; }
Use it as a base class of another template class
template <typename T>
class Foo : X<T> {} // OK as long as X is defined before
// Foo is instantiated.
Foo<int> a1; // Compiler error.
template <typename T> struct X {};
Foo<int> a2; // OK since X is now defined.
Use it to declare a member of another class template:
template <typename T>
class Foo {
X<T> m; // OK as long as X is defined before
// Foo is instantiated.
};
Foo<int> a1; // Compiler error.
template <typename T> struct X {};
Foo<int> a2; // OK since X is now defined.
Define function templates or methods using this type
template <typename T>
void f1(X<T> x) {} // OK if X is defined before calling f1
template <typename T>
X<T> f2(){return X<T>(); } // OK if X is defined before calling f2
void test1()
{
f1(X<int>()); // Compiler error
f2<int>(); // Compiler error
}
template <typename T> struct X {};
void test2()
{
f1(X<int>()); // OK since X is defined now
f2<int>(); // OK since X is defined now
}
What you cannot do with an incomplete type:
Use one of its instantiations as a base class
class Foo : X<int> {} // compiler error!
Use one of its instantiations to declare a member:
class Foo {
X<int> m; // compiler error!
};
Define functions or methods using one of its instantiations
void f1(X<int> x) {} // compiler error!
X<int> f2() {return X<int>(); } // compiler error!
Use the methods or fields of one of its instantiations, in fact trying to dereference a variable with incomplete type
class Foo {
X<int>* m;
void method()
{
m->someMethod(); // compiler error!
int i = m->someField; // compiler error!
}
};
Create explicit instantiations of the class template
template struct X<int>;
Since you mentioned $.each()
, here's a handy approach that would work in jQuery 1.6+:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
Here's a quick code snippet that will find the first non-empty line in a string:
string line1;
while (
((line1 = sr.ReadLine()) != null) &&
((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }
if(line1 == null){ /* Error - no non-empty lines in string */ }
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
You could use On Error Resume Next
then there is no need to loop through all the sheets in the workbook.
With On Error Resume Next
the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.
Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.
Dim book
Dim sht as Worksheet
set book= Workbooks("SomeBook.xlsx")
On Error Resume Next
Application.DisplayAlerts=False
Set sht = book.Worksheets("ID Sheet")
sht.Delete
Set sht = book.Worksheets("Summary")
sht.Delete
Application.DisplayAlerts=True
On Error GoTo 0
The %run
magic has a parameter file_finder
that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.
There doesn't seem to be a way to specify which file finder to use from the %run
magic, but there's nothing to stop you from defining your own magic command that calls into %run
with an appropriate file finder.
As a very nasty hack, you could override the default file_finder
with your own:
IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder
To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.
I have a similar thing going. I have a lot of cases where I do:
thedict = {}
for item in ('foo', 'bar', 'baz'):
mydict = thedict.get(item, {})
mydict = get_value_for(item)
thedict[item] = mydict
But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of
value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)
So instead, I made:
def dictgetter(thedict, default, *args):
totalargs = len(args)
for i,arg in enumerate(args):
if i+1 == totalargs:
thedict = thedict.get(arg, default)
else:
thedict = thedict.get(arg, {})
return thedict
Which has the same effect if you do:
value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')
Better? I think so.
Try this query -
SELECT
t2.company_name,
t2.expose_new,
t2.expose_used,
t1.title,
t1.seller,
t1.status,
CASE status
WHEN 'New' THEN t2.expose_new
WHEN 'Used' THEN t2.expose_used
ELSE NULL
END as 'expose'
FROM
`products` t1
JOIN manufacturers t2
ON
t2.id = t1.seller
WHERE
t1.seller = 4238
I suggest using PhantomJS. For more information, you may visit the Phantom Official Website.
As far as I know PhantomJS works only with Firefox...
After downloading PhantomJs.exe you need to import it to your project as you can see in the picture below PhantomJS.
I have placed mine inside: common ? Library ? phantomjs.exe
Now all you have to do inside your Selenium code is to change the line
browser = webdriver.Firefox()
To something like
import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
The path to PhantomJS may be different... change as you like :)
This hack worked for me, and I'm pretty sure it will work for u too ;)
What about this?
switch (true)
{
case (age >= 1 && age <= 8):
MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case (age >= 9 && age <= 15):
MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case (age >= 16 && age <= 100):
MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
MessageBox.Show("You an old person.");
break;
}
Cheers
Sharing my notes which I usually maintain while reading from Internet, I hope it may be helpful to someone
Candidate keys are those keys which is candidate for primary key of a table. In simple words we can understand that such type of keys which full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.
Such type of candidate key which is chosen as a primary key for table is known as primary key. Primary keys are used to identify tables. There is only one primary key per table. In SQL Server when we create primary key to any table then a clustered index is automatically created to that column.
Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. We can create more than one foreign key per table. Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.
If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Like here we can take a very simple example to understand the concept of alternate key. Suppose we have a table named Employee which has two columns EmpID and EmpMail, both have not null attributes and unique value. So both columns are treated as candidate key. Now we make EmpID as a primary key to that table then EmpMail is known as alternate key.
When we create keys on more than one column then that key is known as composite key. Like here we can take an example to understand this feature. I have a table Student which has two columns Sid and SrefNo and we make primary key on these two column. Then this key is known as composite key.
A natural key is one or more existing data attributes that are unique to the business concept. For the Customer table there was two candidate keys, in this case CustomerNumber and SocialSecurityNumber. Link http://www.agiledata.org/essays/keys.html
Introduce a new column, called a surrogate key, which is a key that has no business meaning. An example of which is the AddressID column of the Address table in Figure 1. Addresses don't have an "easy" natural key because you would need to use all of the columns of the Address table to form a key for itself (you might be able to get away with just the combination of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much better option in this case. Link http://www.agiledata.org/essays/keys.html
A unique key is a superkey--that is, in the relational model of database organization, a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set
When more than one column is combined to form a unique key, their combined value is used to access each row and maintain uniqueness. These keys are referred to as aggregate or compound keys. Values are not combined, they are compared using their data types.
Simple key made from only one attribute.
A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a super key can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
You can use node.js memoryUsage
const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`
const memoryData = process.memoryUsage()
const memoryUsage = {
rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
}
console.log(memoryUsage)
/*
{
"rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
"heapTotal": "102.3 MB -> total size of the allocated heap",
"heapUsed": "94.3 MB -> actual memory used during the execution",
"external": "3.03 MB -> V8 external memory"
}
*/
All saved Authentication Data for all projects is deleted.
You will have to re-enter credentials to reconnect.
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
An easier solution (tested on SQL Server 2014 SP1 CU6)
Code:
DECLARE @Date date = SYSDATETIME();
DECLARE @Time time(0) = SYSDATETIME();
SELECT CAST(CONCAT(@Date, ' ', @Time) AS datetime2(0));
This would also work given a table with a specific date and a specific time field. I use this method frequently given that we have vendor data that uses date and time in two separate fields.
Also, spark is a nice little bar graph in your shell.
you have to open a port of the service in you router then try you puplic ip out of your all network cause if you try it from your network , the puplic ip will always redirect you to your router but from the outside it will redirect to the server you have
UPDATE: As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check Environment.Is64BitOperatingSystem
.
IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).
As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.
Microsoft's Raymond Chen: How to detect programmatically whether you are running on 64-bit Windows
My solution:
static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);
public static bool InternalCheckIsWow64()
{
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool retVal;
if (!IsWow64Process(p.Handle, out retVal))
{
return false;
}
return retVal;
}
}
else
{
return false;
}
}
I do think requests
is the best option. Also note the possibility of setting encoding manually.
import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text
I solved this way, when I had to use the foreach index and value in the same context:
$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {
echo $letter; //Here $letter content is the actual index
echo $array[$letter]; // echoes the array value
}//foreach
$('option', '#theSelect').remove();
It should be:
SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
Regarding your initial query:
Edit:
And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):
;WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
FROM AXDelNotesNoTracking
)
SELECT *
FROM cte
WHERE cte.Num > 1
Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.
Edit2:
The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.
SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
( SELECT SalesID
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
)
ORDER BY SalesID
The reason everyone always says to avoid System.gc()
is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.
You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.
Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.
The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"
EDIT to address a few concerns from the other thread:
After reading the thread you linked, there's a few more things I'd like to point out.
First, someone suggested that calling gc()
may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.
As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.
To show that it's possible that System.gc()
does nothing, view:
http://bugs.sun.com/view_bug.do?bug_id=6668279
and in particular that there's a -XX:DisableExplicitGC VM option.
I do not think C# supports the Range semantics. You could write an extension method though, like:
public static IEnumerator<Byte> Range(this byte[] array, int start, int end);
But like others have said if you do not need to set a start index then Take
is all you need.
I recently wrote a directive that supports native multiple file uploads. The solution I've created relies on a service to fill the gap you've identified with the $http service. I've also included a directive, which provides an easy API for your angular module to use to post the files and data.
Example usage:
<lvl-file-upload
auto-upload='false'
choose-file-button-text='Choose files'
upload-file-button-text='Upload files'
upload-url='http://localhost:3000/files'
max-files='10'
max-file-size-mb='5'
get-additional-data='getData(files)'
on-done='done(files, data)'
on-progress='progress(percentDone)'
on-error='error(files, type, msg)'/>
You can find the code on github, and the documentation on my blog
It would be up to you to process the files in your web framework, but the solution I've created provides the angular interface to getting the data to your server. The angular code you need to write is to respond to the upload events
angular
.module('app', ['lvl.directives.fileupload'])
.controller('ctl', ['$scope', function($scope) {
$scope.done = function(files,data} { /*do something when the upload completes*/ };
$scope.progress = function(percentDone) { /*do something when progress is reported*/ };
$scope.error = function(file, type, msg) { /*do something if an error occurs*/ };
$scope.getAdditionalData = function() { /* return additional data to be posted to the server*/ };
});
In addition to the example given in the Advanced Bash Scripting Guide referenced by Jefromi, these examples show how pipes create subshells:
$ echo $$ $BASHPID | cat -
11656 31528
$ echo $$ $BASHPID
11656 11656
$ echo $$ | while read line; do echo $line $$ $BASHPID; done
11656 11656 31497
$ while read line; do echo $line $$ $BASHPID; done <<< $$
11656 11656 11656
var arr = ["1", "2", "3"];_x000D_
arr = arr.map(Number);_x000D_
console.log(arr); // [1, 2, 3]
_x000D_
terminal 1
dd if=/dev/sda of=debian.img
terminal 2
killall -SIGUSR1 dd
go back to terminal 1
34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s
as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)
you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key
also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.
Here's a different way of doing it.
If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.
filepath = 'textfile.txt'
import os
os.startfile(filepath)
Example:
import os
os.startfile('textfile.txt')
This will open textfile.txt with Notepad if Notepad is associated with .txt files.
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
Next the Ajax ActionLink and the div were we want to render the results:
@Ajax.ActionLink(
"Click Here to Load the Partial View",
"ActionName",
null,
new AjaxOptions { UpdateTargetId = "toUpdate" }
)
<div id="toUpdate"></div>
The “depth” (or equivalently the “level number”) of a node is the number of edges on the “path” from the root node
The “height” of a node is the number of edges on the longest path from the node to a leaf node.
One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():
In UI thread also known as the JavaFX Application thread:
...
listView.itemsProperty().bind(myListService.resultProperty());
...
in Service implementation (background worker):
...
Platform.runLater(() -> result.add("Element " + finalI));
...
Removing outline
is terrible for accessibility! Ideally, the focus ring shows up only when the user intends to use the keyboard.
Use :focus-visible. It's currently a W3C proposal for styling keyboard-only focus using CSS, and is supported in Firefox (caniuse). Until other major browsers support it, you can use this robust polyfill.
/* Remove outline for non-keyboard :focus */
*:focus:not(.focus-visible) {
outline: none;
}
/* Optional: Customize .focus-visible */
.focus-visible {
outline-color: lightgreen;
}
I also wrote a more detailed post just in case you need more info.
You can either set
border-bottom: none;
or
border-bottom: 0;
One sets the border-style
to none
.
One sets the border-width
to 0px
.
div {_x000D_
border: 3px solid #900;_x000D_
_x000D_
background-color: limegreen; _x000D_
width: 28vw;_x000D_
height: 10vw;_x000D_
margin: 1vw;_x000D_
text-align: center;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.stylenone {_x000D_
border-bottom: none;_x000D_
}_x000D_
.widthzero {_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div>_x000D_
(full border)_x000D_
</div>_x000D_
<div class="stylenone">_x000D_
(style)<br><br>_x000D_
_x000D_
border-bottom: none;_x000D_
</div>_x000D_
<div class="widthzero">_x000D_
(width)<br><br>_x000D_
border-bottom: 0;_x000D_
</div>
_x000D_
Side Note:
If you ever have to track down why a border is not showing when you expect it to,
It is also good to know that either of these could be the culprit.
Also verify the border-color
is not the same as the background-color
.
while (<@INC>)
This joins the paths in @INC together in a string, separated by spaces, then calls glob() on the string, which then iterates through the space-separated components (unless there are file-globbing meta-characters.)
This doesn't work so well if there are paths in @INC containing spaces, \, [], {}, *, ?, or ~, and there seems to be no reason to avoid the safe alternative:
for (@INC)
in my case i had a custom class-level constraint that was not being called.
@CustomValidation // not called
public class MyClass {
@Lob
@Column(nullable = false)
private String name;
}
as soon as i added a field-level constraint to my class, either custom or standard, the class-level constraint started working.
@CustomValidation // now it works. super.
public class MyClass {
@Lob
@Column(nullable = false)
@NotBlank // adding this made @CustomValidation start working
private String name;
}
seems like buggy behavior to me but easy enough to work around i guess
Just to add my thoughts. If you always initialize the private field when define it, this problem should be avoid. At least below code works like a charm:
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething()
{
}
}
class Child : Parent
{
private string foo = "HELLO";
public Child() { /*Originally foo initialized here. Removed.*/ }
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower());
}
}
You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:
disable_functions = exec
And remove the exec, shell_exec entries if there are there.
Good Luck!
This will give you the time in seconds + microseconds
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
tv.tv_sec // seconds
tv.tv_usec // microseconds
The updated dplyr solution, as for 2020
1: summarise_each_()
is deprecated as of dplyr 0.7.0.
and
2: funs()
is deprecated as of dplyr 0.8.0.
ag.dplyr <- DF %>% group_by(ID) %>% summarise(across(.cols = everything(),list(mean = mean, sd = sd)))
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
table.test td {
background-color: lime;
padding: 12px;
border:2px solid #fff;border-collapse:separate;
}
In jQuery 1.6+ it's better to use:
$(selector).prop('href',"http://www...")
to set the value, and
$(selector).prop('href')
to get the value
In short, .prop
gets and sets values on the DOM object, and .attr
gets and sets values in the HTML. This makes .prop
a little faster and possibly more reliable in some contexts.
UPDATED!, Scroll Down
If you want something simple pretty to the end-user ... Also, fixed a small suffix issue in the first version below. Now properly returns suffix.
var objToday = new Date(),_x000D_
weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),_x000D_
dayOfWeek = weekday[objToday.getDay()],_x000D_
domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return "th"; a = parseInt((a + "").charAt(1)); return 1 == a ? "st" : 2 == a ? "nd" : 3 == a ? "rd" : "th" }(),_x000D_
dayOfMonth = today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,_x000D_
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),_x000D_
curMonth = months[objToday.getMonth()],_x000D_
curYear = objToday.getFullYear(),_x000D_
curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),_x000D_
curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),_x000D_
curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),_x000D_
curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";_x000D_
var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;_x000D_
_x000D_
document.getElementsByTagName('h1')[0].textContent = today;
_x000D_
<h1></h1>
_x000D_
UBBER UPDATE After much procrastination, I've finally GitHubbed and updated this with the final solution I've been using for myself. It's even had some last-minute edits to make it sweeter! If you're looking for the old jsFiddle, please see this.
This update comes in 2 flavors, still relatively small, though not as small as my above, original answer. If you want extremely small, go with that.
Also Note: This is still less bloated than moment.js. While moment.js is nice, imo, it has too many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP: date.
Flavor 1
new Date().format(String)
My Personal Fav. I know the taboo but works great on the Date Object. Just be aware of any other mods you may have to the Date Object.
// use as simple as
new Date().format('m-d-Y h:i:s'); // 07-06-2016 06:38:34
Flavor 2
dateFormat(Date, String)
More traditional all-in-one method. Has all the ability of the previous, but is called via the method with Date param.
// use as simple as
dateFormat(new Date(), 'm-d-Y h:i:s'); // 07-06-2016 06:38:34
BONUS Flavor (requires jQuery)
$.date(Date, String)
This contains much more than just a simpleformat
option. It extends the base Date object and includes methods such asaddDays
. For more information, please see the Git.
In this mod, the format characters are inspired by PHP: date. For a complete list, please see my README
This mod also has a much longer list of pre-made formats. To use a premade format, simply enter its key name. dateFormat(new Date(), 'pretty-a');
As you may notice, you can use double \
to escape a character.
The maven dependency plugin saved me a lot of time fondling with ant tasks:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install-jar</id>
<phase>install</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>...</groupId>
<artifactId>...</artifactId>
<version>...</version>
</artifactItem>
</artifactItems>
<outputDirectory>...</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
The dependency:copy is documentend, and has more useful goals like unpack.
var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');
Or a little bit simplified
var $th = $td.closest('table').find('th').eq($td.index());
onclick="history.go(-1)"
Simply
In Bootstrap 4
In my case I have just changed the .navbar
min-height
and the links font-size
and it decreased the navbar.
For example:
.navbar{
min-height:12px;
}
.navbar a {
font-size: 11.2px;
}
And this also worked for increasing the navbar height.
This also helps to change the navbar size when scrolling down the browser.
As other answer mentioned depcheck
is good for check unused dependecies in your porject. Use npm outdated
command to check the outdated library.
You can try:
<label id ="label_id"></label>
$("#label_id").html('value');
None of the existing answers worked for me, but I found what did work for me by comparing the .csproj
files of different projects. The following manual edit to the .csproj
XML-file solved the Razor-intellisense problem for me, maybe this can help someone else who has tried all the other answers to no avail. Key is to remove any instances of <Private>False</Private>
in the <Reference>
's:
<ItemGroup>
<Reference Include="Foo">
<HintPath>path\to\Foo</HintPath>
<!-- <Private>False</Private> -->
</Reference>
<Reference Include="Bar">
<HintPath>path\to\Bar</HintPath>
<!-- <Private>True</Private> -->
</Reference>
</ItemGroup>
I don't know how those got there or exactly what they do, maybe someone smarter than me can add that information. I was just happy to finally solve this problem.
I know this is an old thread but I think the Blaze library is worth checking out. It's built for these types of situations.
From the docs:
Blaze extends the usability of NumPy and Pandas to distributed and out-of-core computing. Blaze provides an interface similar to that of the NumPy ND-Array or Pandas DataFrame but maps these familiar interfaces onto a variety of other computational engines like Postgres or Spark.
Edit: By the way, it's supported by ContinuumIO and Travis Oliphant, author of NumPy.
How does your .NET Webservice look like?
I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)
And everytime I used
Integer result = (Integer)envelope.getResponse();
to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive
exception.
I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.
[SoapRpcMethod(), WebMethod]
public Object GetInteger1(int i)
{
// android device will throw exception
return 0;
}
[WebMethod]
public Object GetInteger2(int i)
{
// android device will get the value
return 0;
}
Then I changed my Android code to:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString()
method, so I use Integer.parseInt(result.toString())
to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.
Here is the full source:
private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";
public int GetInteger2() throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("i");
pi.setValue(123);
request.addProperty(pi);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Integer.parseInt(result.toString());
}
Try this
var myarray = ["item 1", "item 2", "item 3", "item 4"];
//removes the first element of the array, and returns that element apart from item 1.
myarray.shift();
console.log(myarray);
you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable
<input type="text" name="lat" value="22.2222" readonly="readonly" />
Short snippet for future visitors - how to center horizontal table-cell (+ vertically)
html, body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center; /* the key */_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: inline-block; /* important !! */_x000D_
width: 100px;_x000D_
background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
<div class="cell">_x000D_
<div class="content" id="a">_x000D_
<p>Content</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
To set https
globally instead of git://
:
git config --global url.https://github.com/.insteadOf git://github.com/