window.history.back();
Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.
I would use this below function for go back with the refresh.
function GoBackWithRefresh(event) {
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
}
In your html, use:
<a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>`
For more customization you can use history.js plugins.
This one normally catches me when I run from IIS and the app pool for the default site is set to .NET version 2.0. When using IIS from visual studio it creates a virtual directory but still runs under the default site's app pool. If using the build in web server, right click on your web project, go to properties and make sure you're running it under the right version of .NET. On IIS check the .NET version on your app pool.
Following on from my last comment about how the project was created - are you correctly including the assemblies, as below (taken from the default web.config file generated by the MVC3 project template in VS10):
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.
theoretically one server can only run as many requests concurrently as number of cores on it..
It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?
also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking
If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler
Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.
See this similar question also.
It is possible using ConfigTransform
build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/
All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.
The same applies to "app.*.config" transform files in non-web projects.
and then adding the following target to your *.csproj
.
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.
I recommend trying Kestrel, it's fast and simple as Beanstalk but supports fanout queues. Speaks memcached. It's built using Scala and used at Twitter.
file = request.FILES['filename']
file.name # Gives name
file.content_type # Gives Content type text/html etc
file.size # Gives file's size in byte
file.read() # Reads file
You can use local redirect. Following codes are jumping the HomeController's Index page:
public class SharedController : Controller
{
// GET: /<controller>/
public IActionResult _Layout(string btnLogout)
{
if (btnLogout != null)
{
return LocalRedirect("~/Index");
}
return View();
}
}
No. Java does not have this feature. You'd have to create your String using a StringBuilder, and a loop of some sort.
It can be done without find
as well by using grep's "--include"
option.
grep man page says:
--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
So to do a recursive search for a string in a file matching a specific pattern, it will look something like this:
grep -r --include=<pattern> <string> <directory>
For example, to recursively search for string "mytarget" in all Makefiles:
grep -r --include="Makefile" "mytarget" ./
Or to search in all files starting with "Make" in filename:
grep -r --include="Make*" "mytarget" ./
Here is an example of how you do it with expect
tool:
sub copyover {
$scp = Expect->spawn("/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file");
$scp->expect(30,"ssword: ") || die "Never got password prompt from $dest:$!\n";
print $scp 'password' . "\n";
$scp->expect(30,"-re",'$\s') || die "Never got prompt from parent system:$!\n";
$scp->soft_close();
return;
}
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.
using namespace std;
// returns number of replacements made in string
long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
if (from.empty()) return 0;
size_t startpos = str.find(from, start);
long replaceCount = 0;
while (startpos != string::npos){
str.replace(startpos, from.length(), to);
startpos += to.length();
replaceCount++;
if (count > 0 && replaceCount >= count) break;
startpos = str.find(from, startpos);
}
return replaceCount;
}
You could store your JSON inside of an array and then insert the JSON data into the array with push
Check this out https://jsfiddle.net/cx2rk40e/2/
$(document).ready(function(){
// using jQuery just to load function but will work without library.
$( "button" ).on( "click", go );
// Array of JSON we will append too.
var jsonTest = [{
"colour": "blue",
"link": "http1"
}]
// Appends JSON to array with push. Then displays the data in alert.
function go() {
jsonTest.push({"colour":"red", "link":"http2"});
alert(JSON.stringify(jsonTest));
}
});
Result of JSON.stringify(jsonTest)
[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]
This answer maybe useful to users who wish to emulate a similar result.
Use VBA's already existing Join
function. VBA functions aren't exposed in Excel, so I wrap Join
in a user-defined function that exposes its functionality. The simplest form is:
Function JoinXL(arr As Variant, Optional delimiter As String = " ")
'arr must be a one-dimensional array.
JoinXL = Join(arr, delimiter)
End Function
Example usage:
=JoinXL(TRANSPOSE(A1:A4)," ")
entered as an array formula (using Ctrl-Shift-Enter).
Now, JoinXL
accepts only one-dimensional arrays as input. In Excel, ranges return two-dimensional arrays. In the above example, TRANSPOSE
converts the 4×1 two-dimensional array into a 4-element one-dimensional array (this is the documented behaviour of TRANSPOSE
when it is fed with a single-column two-dimensional array).
For a horizontal range, you would have to do a double TRANSPOSE
:
=JoinXL(TRANSPOSE(TRANSPOSE(A1:D1)))
The inner TRANSPOSE
converts the 1×4 two-dimensional array into a 4×1 two-dimensional array, which the outer TRANSPOSE
then converts into the expected 4-element one-dimensional array.
This usage of TRANSPOSE
is a well-known way of converting 2D arrays into 1D arrays in Excel, but it looks terrible. A more elegant solution would be to hide this away in the JoinXL
VBA function.
I have jus this week come across this convention, which seems to be an excellent approach, but I cannot find it referenced anywhere. Is anyone familiar with it? Can you cite a source for it? I have not looked for hours and hours but am hoping someone will recognize this approach.
Example 1: =("012345678905") displays as 012345678905
Example 2: =("1954-12-12") displays as 1954-12-12, not 12/12/1954.
Android, Python !
When I saw these two keywords together in your question, Kivy is the one which came to my mind first.
Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.
Simple to use
With a python basics, you won't have trouble learning it.
Good community
It's well documented and has a great, active community.
Cross platform.
You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.
It is a free software
At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.
Accelerated graphics support
Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.
Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
$('#someButton').click(function() {
window.location.href = '/some/new/page';
return false;
});
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.
I use this short format for github repositories:
yarn add github_user/repository_name#commit_hash
(Using Redux for state management)
If user try to access any url, first i am going to check if access token available, if not redirect to login page,
Once user logs in using login page, we do store that in localstorage as well as in our redux state. (localstorage or cookies..we keep this topic out of context for now).
since redux state as updated and privateroutes will be rerendered. now we do have access token so we gonna redirect to home page.
Store the decoded authorization payload data as well in redux state and pass it to react context. (We dont have to use context but to access authorization in any of our nested child components it makes easy to access from context instead connecting each and every child component to redux)..
All the routes that don't need special roles can be accessed directly after login.. If it need role like admin (we made a protected route which checks whether he had desired role if not redirects to unauthorized component)
similarly in any of your component if you have to disable button or something based on role.
simply you can do in this way
const authorization = useContext(AuthContext);
const [hasAdminRole] = checkAuth({authorization, roleType:"admin"});
const [hasLeadRole] = checkAuth({authorization, roleType:"lead"});
<Button disable={!hasAdminRole} />Admin can access</Button>
<Button disable={!hasLeadRole || !hasAdminRole} />admin or lead can access</Button>
So what if user try to insert dummy token in localstorage. As we do have access token, we will redirect to home component. My home component will make rest call to grab data, since jwt token was dummy, rest call will return unauthorized user. So i do call logout (which will clear localstorage and redirect to login page again). If home page has static data and not making any api calls(then you should have token-verify api call in the backend so that you can check if token is REAL before loading home page)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Switch } from 'react-router-dom';
import history from './utils/history';
import Store from './statemanagement/store/configureStore';
import Privateroutes from './Privateroutes';
import Logout from './components/auth/Logout';
ReactDOM.render(
<Store>
<Router history={history}>
<Switch>
<Route path="/logout" exact component={Logout} />
<Route path="/" exact component={Privateroutes} />
<Route path="/:someParam" component={Privateroutes} />
</Switch>
</Router>
</Store>,
document.querySelector('#root')
);
History.js
import { createBrowserHistory as history } from 'history';
export default history({});
Privateroutes.js
import React, { Fragment, useContext } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { AuthContext, checkAuth } from './checkAuth';
import App from './components/App';
import Home from './components/home';
import Admin from './components/admin';
import Login from './components/auth/Login';
import Unauthorized from './components/Unauthorized ';
import Notfound from './components/404';
const ProtectedRoute = ({ component: Component, roleType, ...rest })=> {
const authorization = useContext(AuthContext);
const [hasRequiredRole] = checkAuth({authorization, roleType});
return (
<Route
{...rest}
render={props => hasRequiredRole ?
<Component {...props} /> :
<Unauthorized {...props} /> }
/>)};
const Privateroutes = props => {
const { accessToken, authorization } = props.authData;
if (accessToken) {
return (
<Fragment>
<AuthContext.Provider value={authorization}>
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" render={() => <Redirect to="/" />} />
<Route exact path="/home" component={Home} />
<ProtectedRoute
exact
path="/admin"
component={Admin}
roleType="admin"
/>
<Route path="/404" component={Notfound} />
<Route path="*" render={() => <Redirect to="/404" />} />
</Switch>
</App>
</AuthContext.Provider>
</Fragment>
);
} else {
return (
<Fragment>
<Route exact path="/login" component={Login} />
<Route exact path="*" render={() => <Redirect to="/login" />} />
</Fragment>
);
}
};
// my user reducer sample
// const accessToken = localStorage.getItem('token')
// ? JSON.parse(localStorage.getItem('token')).accessToken
// : false;
// const initialState = {
// accessToken: accessToken ? accessToken : null,
// authorization: accessToken
// ? jwtDecode(JSON.parse(localStorage.getItem('token')).accessToken)
// .authorization
// : null
// };
// export default function(state = initialState, action) {
// switch (action.type) {
// case actionTypes.FETCH_LOGIN_SUCCESS:
// let token = {
// accessToken: action.payload.token
// };
// localStorage.setItem('token', JSON.stringify(token))
// return {
// ...state,
// accessToken: action.payload.token,
// authorization: jwtDecode(action.payload.token).authorization
// };
// default:
// return state;
// }
// }
const mapStateToProps = state => {
const { authData } = state.user;
return {
authData: authData
};
};
export default connect(mapStateToProps)(Privateroutes);
checkAuth.js
import React from 'react';
export const AuthContext = React.createContext();
export const checkAuth = ({ authorization, roleType }) => {
let hasRequiredRole = false;
if (authorization.roles ) {
let roles = authorization.roles.map(item =>
item.toLowerCase()
);
hasRequiredRole = roles.includes(roleType);
}
return [hasRequiredRole];
};
DECODED JWT TOKEN SAMPLE
{
"authorization": {
"roles": [
"admin",
"operator"
]
},
"exp": 1591733170,
"user_id": 1,
"orig_iat": 1591646770,
"email": "hemanthvrm@stackoverflow",
"username": "hemanthvrm"
}
Go to Preferences
> Key Bindings
> User
and add the code below:
[
{ "keys": ["ctrl+shift+f"], "command": "reindent", "args": {"single_line": false} }
]
Usage
Ctrl + Shift + F
Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.
d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second
I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.
One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout
, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height
property (which must exist in your xml file) set to 0dp
. Seems like any other value would mess things up in some cases.
You want the %c
conversion specifier, which just reads a sequence of characters without special handling for whitespace.
Note that you need to fill the buffer with zeroes first, because the %c
specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):
memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);
Iif you want a particular <canvas id="canvasID">
to be always transparent you just have to set
#canvasID{
opacity:0.5;
}
Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.
context.fillStyle = "rgba(0, 0, 200, 0.5)";
As you are casting from Object to String I recommend you catch and report (in some way, here I just print a message, which is generally bad) the exception.
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
try{
newMap.put(entry.getKey(), (String) entry.getValue());
}
catch(ClassCastException e){
System.out.println("ERROR: "+entry.getKey()+" -> "+entry.getValue()+
" not added, as "+entry.getValue()+" is not a String");
}
}
If the object is actually a Boolean
instance, then just cast it:
boolean di = (Boolean) someObject;
The explicit cast will do the conversion to Boolean
, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:
boolean di = ((Boolean) someObject).booleanValue();
If someObject
doesn't refer to a Boolean value though, what do you want the code to do?
When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.
This will do it
<input id="button" type="submit" name="button" onclick="myFunction();" value="enter"/>
<script>
function myFunction(){
alert("You button was pressed");
};
</script>
What you can do to solve this is:
C:\xampp\php
.Add nil to the end of the declaration.
// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil
// Init the view
override init(frame: CGRect)
super.init(frame: frame)
...
This worked for my case, but may not work for yours
Give another go at force removing the brewed version of git
brew uninstall --force git
Then cleanup any older versions and clear the brew cache
brew cleanup -s git
Remove any dead symlinks
brew cleanup --prune-prefix
Then try reinstalling git
brew install git
If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix
directory (/usr/local
by default), you can simply rm -rf $(brew --prefix)
. Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh
Did you check the string concatenation function? Something like:
update table_c set column_a = column_b || column_c
should work. More here
Probably you are looking for JavaScript™ for Acrobat® API Reference.
This reference should be the most complete. But, as @Orbling said, not all PDF viewers might support all of the API.
EDIT:
It turns out there are newer versions of the reference in Acrobat SDK (thanks to @jss).
Acrobat Developer Center contains links to different versions of documentation. Current version of JavaScript reference from Acrobat DC SDK is available there too.
1) Update conda
Run the anaconda prompt as administrator
conda update -n base -c defaults conda
2) Create an environment for python new version say, 3.6
conda create --name py36 python=3.6
3) Activate the new environment
conda activate py36
4) Upgrade pip
pip install --upgrade pip
5) Install tensorflow
pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl
If it doesn't work
If you have problem with wheel at the environment location, or pywrap_tensorflow problem,
pip install tensorflow --upgrade --force-reinstall
Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.
I hope this helps you out.
<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
Now for the Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
....
....
}
}
Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.
The error message you saw was because self.whip
was a string, not a dictionary.
I first wrote that you could just feed the string into dict()
but that doesn't work! You need to do something else.
Here is the simplest way: feed the string into eval()
. Like so:
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = eval(s)
You can do it in one line, but I think it looks messy this way:
def reading(self):
self.whip = eval(open('deed.txt', 'r').read())
But eval()
is sometimes not recommended. The problem is that eval()
will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval()
on your own file, so it should be okay.
But because eval()
is useful, someone made an alternative to it that is safer. This is called literal_eval
and you get it from a Python module called ast
.
import ast
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = ast.literal_eval(s)
ast.literal_eval()
will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.
Actually, best practice in Python is to use a with
statement to make sure the file gets properly closed. Rewriting the above to use a with
statement:
import ast
def reading(self):
with open('deed.txt', 'r') as f:
s = f.read()
self.whip = ast.literal_eval(s)
In the most popular Python, known as "CPython", you usually don't need the with
statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with
, and I think it makes the code pretty easy to understand.
Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.
I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).
This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.
To demonstrate, see this example:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground):
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]
We created a "backing" array a
with length 10
. Then we create the x
destination slice by slicing this a
array, y
slice is created using the composite literal []int{3, 4}
. Now when we append y
to x
, the result is the expected [1 2 3 4]
, but what may be surprising is that the backing array a
also changed, because capacity of x
is 10
which is sufficient to append y
to it, so x
is resliced which will also use the same a
backing array, and append()
will copy elements of y
into there.
If you want to avoid this, you may use a full slice expression which has the form
a[low : high : max]
which constructs a slice and also controls the resulting slice's capacity by setting it to max - low
.
See the modified example (the only difference is that we create x
like this: x = a[:2:2]
:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground)
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]
As you can see, we get the same x
result but the backing array a
did not change, because capacity of x
was "only" 2
(thanks to the full slice expression a[:2:2]
). So to do the append, a new backing array is allocated that can store the elements of both x
and y
, which is distinct from a
.
/**
* Get a diff between two dates
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
And then can you call:
getDateDiff(date1,date2,TimeUnit.MINUTES);
to get the diff of the 2 dates in minutes unit.
TimeUnit
is java.util.concurrent.TimeUnit
, a standard Java enum going from nanos to days.
public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {
long diffInMillies = date2.getTime() - date1.getTime();
//create the list
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
//create the result map of TimeUnit and difference
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = diffInMillies;
for ( TimeUnit unit : units ) {
//calculate difference in millisecond
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
//put the result in the map
result.put(unit,diff);
}
return result;
}
The output is something like Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
, with the units ordered.
You just have to convert that map to an user-friendly string.
The above code snippets compute a simple diff between 2 instants. It can cause problems during a daylight saving switch, like explained in this post. This means if you compute the diff between dates with no time you may have a missing day/hour.
In my opinion the date diff is kind of subjective, especially on days. You may:
count the number of 24h elapsed time: day+1 - day = 1 day = 24h
count the number of elapsed time, taking care of daylight savings: day+1 - day = 1 = 24h (but using midnight time and daylight savings it could be 0 day and 23h)
count the number of day switches
, which means day+1 1pm - day 11am = 1 day, even if the elapsed time is just 2h (or 1h if there is a daylight saving :p)
My answer is valid if your definition of date diff on days match the 1st case
If you are using JodaTime you can get the diff for 2 instants (millies backed ReadableInstant) dates with:
Interval interval = new Interval(oldInstant, new Instant());
But you can also get the diff for Local dates/times:
// returns 4 because of the leap year of 366 days
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5), PeriodType.years()).getYears()
// this time it returns 5
new Period(LocalDate.now(), LocalDate.now().plusDays(365*5+1), PeriodType.years()).getYears()
// And you can also use these static methods
Years.yearsBetween(LocalDate.now(), LocalDate.now().plusDays(365*5)).getYears()
I like some of the answers here, but there is a sed command that should do the trick on any platform:
sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.
This is how it worked for me:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
You can try with regular expression
string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);
Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.
WebAsyncManagerIntegrationFilter
Provides integration between the SecurityContext and Spring Web's WebAsyncManager.
SecurityContextPersistenceFilter
This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.
HeaderWriterFilter
Filter implementation to add headers to the current response.
LogoutFilter
If request url is /logout
(for default configuration) or if request url mathces RequestMatcher
configured in LogoutConfigurer
then
LogoutConfigurer
/
or logout success url configured or invokes logoutSuccessHandler configured.UsernamePasswordAuthenticationFilter
HTTP POST
) default /login
or matches .loginProcessingUrl()
configured in FormLoginConfigurer
then UsernamePasswordAuthenticationFilter
attempts authentication.usernameParameter(String)
, passwordParameter(String)
..loginPage()
overrides defaults Authentication
object(UsernamePasswordAuthenticationToken
or any implementation of Authentication
in case of your custom auth filter) is created. authenticationManager.authenticate(authToken)
will be invokedAuthenticationProvider
authenticate method tries all auth providers and checks any of the auth provider supports
authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException
.authenticationSuccessHandler
will be invoked which redirects to the target url configured(default is /
)SecurityContextHolderAwareRequestFilter
, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
AnonymousAuthenticationFilter
Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication
object (AnonymousAuthenticationToken
) with granted authority ROLE_ANONYMOUS
. Here AnonymousAuthenticationToken
facilitates identifying un-authenticated users subsequent requests.
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
ExceptionTranslationFilter
, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor
There will be FilterSecurityInterceptor
which comes almost last in the filter chain which gets Authentication object from SecurityContext
and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers
configured in HttpSecurityConfiguration
.
Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain
Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter
,RequestCacheAwareFilter
,SessionManagementFilter
...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter
.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter
it will become entirely different case.
From Documentation ordering of filters is given as
- ChannelProcessingFilter
- ConcurrentSessionFilter
- SecurityContextPersistenceFilter
- LogoutFilter
- X509AuthenticationFilter
- AbstractPreAuthenticatedProcessingFilter
- CasAuthenticationFilter
- UsernamePasswordAuthenticationFilter
- ConcurrentSessionFilter
- OpenIDAuthenticationFilter
- DefaultLoginPageGeneratingFilter
- DefaultLogoutPageGeneratingFilter
- ConcurrentSessionFilter
- DigestAuthenticationFilter
- BearerTokenAuthenticationFilter
- BasicAuthenticationFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
- SwitchUserFilter
You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?
Do not forget zope.testbrowser which is wrapper around mechanize .
zope.testbrowser provides an easy-to-use programmable web browser with special focus on testing.
Google uses this code in the device-info plugin from Flutter to determine if the device is an emulator:
private boolean isEmulator() {
return (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.HARDWARE.contains("goldfish")
|| Build.HARDWARE.contains("ranchu")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.PRODUCT.contains("sdk_google")
|| Build.PRODUCT.contains("google_sdk")
|| Build.PRODUCT.contains("sdk")
|| Build.PRODUCT.contains("sdk_x86")
|| Build.PRODUCT.contains("vbox86p")
|| Build.PRODUCT.contains("emulator")
|| Build.PRODUCT.contains("simulator");
}
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -
my expected:
http://localhost/api/v1/admin/logs/testLog.log
would be encoded to:
http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log
If you need to do a comparison, transforming the url using:
addcslashes($url, '/')
allowed for the proper output during my comparisons.
Using Sourcetree | The easiest way.
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
Try to use android:scaleType="fitXY"
in i-Imagebutton xml
Simply try to run mysqld
.
This was what was not working for me on mac.
If it doesn't work try go to /usr/local/var/mysql/<your_name>.err
to see detailed error logs.
2018 Update
Font Awesome 5 now features light, regular and solid variants. The icon featured in this question has the following style under the different variants:
A modern answer to this question would be that different variants of the icon can be used to make the icon appear bolder or lighter. The only downside is that if you're already using solid you will have to fall back to the original answers here to make those bolder, and likewise if you're using light you'd have to do the same to make those lighter.
Font Awesome's How To Use documentation walks through how to use these variants.
Original Answer
Font Awesome makes use of the Private Use region of Unicode. For example, this .icon-remove
you're using is added in using the ::before
pseudo-selector, setting its content to \f00d (
):
.icon-remove:before {
content: "\f00d";
}
Font Awesome does only come with one font-weight variant, however browsers will render this as they would render any font with only one variant. If you look closely, the normal
font-weight isn't as bold as the bold
font-weight. Unfortunately a normal font weight isn't what you're after.
What you can do however is change its colour to something less dark and reduce its font size to make it stand out a bit less. From your image, the "tags" text appears much lighter than the icon, so I'd suggest using something like:
.tag .icon-remove {
color:#888;
font-size:14px;
}
Here's a JSFiddle example, and here is further proof that this is definitely a font.
success
is the callback that is invoked when the request is successful and is part of the $.ajax
call. done
is actually part of the jqXHR
object returned by $.ajax()
, and replaces success
in jQuery 1.8.
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
Since every example here is just using walk
(with join
), i'd like to show a nice example and comparison with listdir
:
import os, time
def listFiles1(root): # listdir
allFiles = []; walk = [root]
while walk:
folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
return allFiles
def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
allFiles = []; walk = [root]
while walk:
folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
return allFiles
def listFiles3(root): # walk (takes ~1.5x as long)
allFiles = []
for folder, folders, files in os.walk(root):
for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
return allFiles
def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
allFiles = []
for folder, folders, files in os.walk(root):
for file in files: allFiles+=[os.path.join(folder,file)]
return allFiles
for i in range(100): files = listFiles1("src") # warm up
start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s
start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s
start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s
start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s
So as you can see for yourself, the listdir
version is much more efficient. (and that join
is slow)
since you only want the files, you don't need to treat it as a git repo.
rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .
and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
The CSS :first-child
selector allows you to target an element that is the first child element within its parent.
element:first-child { style_properties }
table:first-child { style_properties }
Even simplier solution (still with [one line inline] javascript):
Use this as the body tag:
Note that body.
or this.
did not work for me. Only the long ; querySelector
allow the use of classList.remove
(Linux Chromium)
<body class="onload" onload="document.querySelector('body').classList.remove('onload')">
and add this line on top of your other css rules.
body.onload *{ transform: none !important; }
Take note that this can apply to opacity (as requested by OP [other posters] ) simply by using opacity as a transition trigger instead. (might even work on any other css ruling in the same fashion and you can use multiple class for explicity delay between triggering)
The logic is the same. Enforce no transform (with :none !important
on all child element of body.onload
and once the document is loaded remove the class to trigger all transition on all elements as specified in your css.
FIRST ANSWER BELOW (SEE EDIT ABOVE FOR SHORTER ANSWER)
Here is a reverse solution:
Works with multiple transition on multiple elements. Did not try cross-browser compatibility.
#rotated{
transform : rotate(90deg) /* any other transformation */;
transition 3s;
}
#translated{
transform : translate(90px) /* any other transformation */;
transition 3s;
}
.waitload{
transform: none !important;
}
<div id='rotated' class='waitload'>
rotate after load
</div>
<div id='translated' class='waitload'>
trasnlate after load
</div>
<script type="text/javascript">
// or body onload ?
[...document.querySelectorAll('.waitload')]
.map(e => e.classList.remove('waitload'));
</script>
To remove need for ToString()
call use
string actionName = ControllerContext.RouteData.GetRequiredString("action");
string controllerName = ControllerContext.RouteData.GetRequiredString("controller");
>>> import django
>>> print(django.get_version())
1.6.1
I am using the IDLE (Python GUI).
function call() {
var x = document.getElementById("mySelect");
var optionVal = new Array();
for (i = 0; i < x.length; i++) {
optionVal.push(x.options[i].text);
}
for (i = x.length; i >= 0; i--) {
x.remove(i);
}
optionVal.sort();
for (var i = 0; i < optionVal.length; i++) {
var opt = optionVal[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
x.appendChild(el);
}
}
The idea is to pullout all the elements of the selectbox into an array , delete the selectbox values to avoid overriding, sort the array and then push back the sorted array into the select box
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
With the Pendulum very complete library, we have the subtract
method (and not "subStract"):
import pendulum
today = pendulum.datetime.today() # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'
We see that it handles jumping years.
The reverse equivalent is add
.
From http://readableweb.com/mo-bulletproofer-font-face-css-syntax/
Now that web fonts are supported in Firefox 3.5 and 3.6, Internet Explorer, Safari, Opera 10.5, and Chrome, web authors face new questions: How do these implementations differ? What CSS techniques will accommodate all? Firefox developer John Daggett recently posted a little roundup about these issues and the workarounds that are being explored. In response to that post, and in response to, particularly, Paul Irish’s work, I came up with the following @font-face CSS syntax. It’s been tested in all of the above named browsers including IE 8, 7, and 6. So far, so good. The following is a test page that declares the free Droid font as a complete font-family with Regular, Italic, Bold, and Bold Italic. View source for details. Alert: Be aware that Readable Web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. It has it’s own web site and, in addition to the utility itself, the download package contains helpful documentation, a test font, and an EOT test page. It’s called EOTFAST If you’re working with @font-face, it’s a must-have.
Here’s The Mo’ Bulletproofer Code:
@font-face{ /* for IE */
font-family:FishyFont;
src:url(fishy.eot);
}
@font-face { /* for non-IE */
font-family:FishyFont;
src:url(http://:/) format("No-IE-404"),url(fishy.ttf) format("truetype");
}
The NSLocalizedString
exists also in the Swift's world.
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value: String = default,
#comment: String) -> String
The tableName
, bundle
, and value
parameters are marked with a default
keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.
This leads to a conclusion that the method call can be simplified to:
NSLocalizedString("key", comment: "comment")
Swift 5 - no change, still works like that.
i think this will help you
content of .htaccess
ErrorDocument 404 /error.php
ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 405 /error.php
ErrorDocument 406 /error.php
ErrorDocument 409 /error.php
ErrorDocument 413 /error.php
ErrorDocument 414 /error.php
ErrorDocument 500 /error.php
ErrorDocument 501 /error.php
error.php and .htaccess should be put in the same directory [in this case]
width
and height
are used when going the css route.
<!DOCTYPE html>
<html>
<head>
<title>Setting Width and Height on Textareas</title>
<style>
.comments { width: 300px; height: 75px }
</style>
</head>
<body>
<textarea class="comments"></textarea>
</body>
</html>
errno 111 is ECONNREFUSED, I suppose something is wrong with the router's DNAT.
It is also possible that your ISP is filtering that port.
If you are not looking for Excel formula, Its easy from the Menu
Data Menu --> Remove Duplicates would alert, if there are no duplicates
Also, if you see the count and reduced after removing duplicates...
@sz3, funny enough today I had to do exactly what you were trying to achieve: 'load a specific CSS file only when a user access' a specific page. So I used the solution above.
But I am here to answer your last question: 'where exactly should I put the code. Any ideas?'
You were right including the code into the resolve, but you need to change a bit the format.
Take a look at the code below:
.when('/home', {
title:'Home - ' + siteName,
bodyClass: 'home',
templateUrl: function(params) {
return 'views/home.html';
},
controler: 'homeCtrl',
resolve: {
style : function(){
/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#mobile').length){
angular.element('head').append('<link id="home" href="home.css" rel="stylesheet">');
}
}
}
})
I've just tested and it's working fine, it injects the html and it loads my 'home.css' only when I hit the '/home' route.
Full explanation can be found here, but basically resolve: should get an object in the format
{
'key' : string or function()
}
You can name the 'key' anything you like - in my case I called 'style'.
Then for the value you have two options:
If it's a string, then it is an alias for a service.
If it's function, then it is injected and the return value is treated as the dependency.
The main point here is that the code inside the function is going to be executed before before the controller is instantiated and the $routeChangeSuccess event is fired.
Hope that helps.
text/javascript
is obsolete, and application/x-javascript
was experimental (hence the x-
prefix) for a transitional period until application/javascript
could be standardised.
You should use application/javascript
. This is documented in the RFC.
As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/*
and application/*
MIME type groups had a consistent meaning where possible. (text/*
MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).
Note that using application/javascript
in the type
attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript
there or omit the attribute entirely (which is permitted in HTML 5).
This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript
.
python enumerate
function will be satisfied your requirements
result = list(enumerate([1,3,7,12]))
print result
output
[(0, 1), (1, 3), (2, 7),(3,12)]
You use this style code
.heighttext{
float:right;
height:30px;
width:70px;
}
There is no version 1.3.0
for rope
. 1.3.0
refers to the package cached-property
. The highest available version of rope
is 0.9.4
.
You can install different versions with conda install package=version
. But in this case there is only one version of rope
so you don't need that.
The reason you see the cached-property
in this listing is because it contains the string "rope"
: "cached-p rope erty"
py35_0
means that you need python version 3.5
for this specific version. If you only have python3.4
and the package is only for version 3.5
you cannot install it with conda.
I am not quite sure on the defaults
either. It should be an indication that this package is inside the default conda channel.
As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.
I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:
unzip zip_name.zip && chmod +x script_name.sh
If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh
as follows:
#!/bin/bash
# file: grant_perms.sh
chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh
(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)
And now your unzip one-liner becomes:
unzip zip_name.zip && source grant_perms.sh
Note that since you are using source
to run grant_perms.sh
, it doesn't need execute permission
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
len(self.table)
checks for the length of the array, so you can use if-statements to find out if the length of the list is greater than 0 (not empty):
Python 2:
if len(self.table) > 0:
#Do code here
Python 3:
if(len(self.table) > 0):
#Do code here
It's also possible to use
if self.table:
#Execute if self.table is not empty
else:
#Execute if self.table is empty
to see if the list is not empty.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
I've found the following "cheat" to work very neatly and error-free
> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary
Et voila!
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
Just to add my solution to the list..
I wanted a semi transparent bottom border that extends past the original shape (So the semi-transparent border was outside the parent rectangle).
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#33000000" /> <!-- Border colour -->
</shape>
</item>
<item android:bottom="2dp" >
<shape android:shape="rectangle" >
<solid android:color="#164586" />
</shape>
</item>
</layer-list>
Which gives me;
Here's a bit of C code that should properly calculate perceived luminance.
// reverses the rgb gamma
#define inverseGamma(t) (((t) <= 0.0404482362771076) ? ((t)/12.92) : pow(((t) + 0.055)/1.055, 2.4))
//CIE L*a*b* f function (used to convert XYZ to L*a*b*) http://en.wikipedia.org/wiki/Lab_color_space
#define LABF(t) ((t >= 8.85645167903563082e-3) ? powf(t,0.333333333333333) : (841.0/108.0)*(t) + (4.0/29.0))
float
rgbToCIEL(PIXEL p)
{
float y;
float r=p.r/255.0;
float g=p.g/255.0;
float b=p.b/255.0;
r=inverseGamma(r);
g=inverseGamma(g);
b=inverseGamma(b);
//Observer = 2°, Illuminant = D65
y = 0.2125862307855955516*r + 0.7151703037034108499*g + 0.07220049864333622685*b;
// At this point we've done RGBtoXYZ now do XYZ to Lab
// y /= WHITEPOINT_Y; The white point for y in D65 is 1.0
y = LABF(y);
/* This is the "normal conversion which produces values scaled to 100
Lab.L = 116.0*y - 16.0;
*/
return(1.16*y - 0.16); // return values for 0.0 >=L <=1.0
}
Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.
#!/usr/bin/env python2
import sys
import socket
if __name__ == "__main__":
string = sys.argv[1]
buf_get = "x" * int(string)
buf_size = 1024
request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
print "===>", request
sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_http.connect(("localhost", 80))
sock_http.send(request)
while True:
print "==>", sock_http.recv(buf_size)
if not sock_http.recv(buf_size):
break
sock_http.close()
On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large
for Z score, we can stick to documentation instead of using 'apply' function
from scipy.stats import zscore
df_zscore = zscore(cols as array, axis=1)
Enable mod_ssl in httpd.conf and restart the apache. You will see the openssl information in error.log as below
[Fri Mar 23 15:13:38.448268 2018] [mpm_worker:notice] [pid 8891:tid 1] AH00292: Apache/2.4.29 (Unix) OpenSSL/1.0.2n configured -- resuming normal operations_x000D_
[Fri Mar 23 15:13:38.448502 2018] [core:notice] [pid 8891:tid 1] AH00094: Command line: '/opt/apps/apache64/2.4.29/bin/httpd'
_x000D_
Use:
git remote prune <remote>
Where <remote>
is a remote source name like origin or upstream.
Example: git remote prune origin
Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.
This worked for me:
location / {
# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
-- borrowed from: https://github.com/nicokaiser/nginx-websocket-proxy/blob/df67cd92f71bfcb513b343beaa89cb33ab09fb05/simple-wss.conf
To get left/right centering, then applying text-align: center
to the div
and margin: auto
to the p
.
For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div
A pure solution without jQuery:
function chbg(color) {
document.getElementById('b').style.backgroundColor = color;
}
<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>
JSFiddle: http://jsfiddle.net/YShs2/
The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.
There are three major differences between static and dynamic binding while designing the compilers and how variables and procedures are transferred to the runtime environment. These differences are as follows:
Static Binding: In static binding three following problems are discussed:
Definition of a procedure
Declaration of a name(variable, etc.)
Scope of the declaration
Dynamic Binding: Three problems that come across in the dynamic binding are as following:
Activation of a procedure
Binding of a name
Lifetime of a binding
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
If you use docker there is a chance you get error because of OpenSSL default security level.
You need lower seclevel in /etc/ssl/openssl.cnf
from DEFAULT@SECLEVEL=2
to DEFAULT@SECLEVEL=1
Or just add into Dockerfile
RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf
Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876
After that change I can run SoapClient without any additional options
You can verify it by run on container
curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl
I think the reason that this is happening could be because TextBox1
is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".
EDIT
It looks like you may be able to use the GetObject function to pull the textbox from the workbook.
Stack(
children: [
Container(color:Colors.red, height:200.0, width:200.0),
Positioned.fill(
child: Container(color: Colors. yellow),
)
]
),
Give your inner div a width.
EXAMPLE
Change your CSS:
<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>
To this:
<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; width:500px }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>
You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduser
home = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())
Update : In angular 7, they are the same as 6
In angular 6
the complete answer found in live example
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
it's because of pipeable/lettable operators
which now angular is able to use tree-shakable
and remove unused imports and optimize the app
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
more in MIGRATION
and Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
and for backward compatability you can use rxjs-compat
The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:
Reference the CSS files in the web folder (after: console assets:install --symlink web
)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Recently,I also encountered this problem. That's because I used qt(x64
) in vs win32
. If you want to use qt application x64
, you could choose vs x64
--as the above. If you want to use win32
and perhaps you haven't,you need to download qt(32bit
),then correctly set your enviroment, such as the lib
directory, etc.(note: maybe you are is old set in x64(other version)
, if you convert your win32 or x64 into another, Additional Dependencies
includes the old directory!)
As for me, I realized there was another web project in the solution that my VS2017 was loading fine, so I copied over the ProjectTypeGuids
element of it over to the project that wasn't loading. Its diff was:
- <ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
+ <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
After this, it loads. Don't ask me why.
HTML 4.x & HTML5 disallow nested forms, but HTML5 will allow a workaround with "form" attribute ("form owner").
As for HTML 4.x you can:
This works well from within Eclipse, until GitHub adds the feature:
PHP was not designed to explicitly give you a pure REST (GET, POST, PUT, PATCH, DELETE) like interface for handling HTTP requests.
However, the $_SERVER
, $_COOKIE
, $_POST
, $_GET
, and $_FILES
superglobals, and the function filter_input_array()
are very useful for the average person's / layman's needs.
The number one hidden advantage of $_POST
(and $_GET
) is that your input data is url-decoded automatically by PHP. You never even think about having to do it, especially for query string parameters within a standard GET
request, or HTTP body data submitted with a POST
request.
Those studying the underlying HTTP protocol and its various request methods come to understand that there are many HTTP request methods, including the often referenced PUT
, PATCH
(not used in Google's Apigee), and DELETE
.
In PHP, there are no superglobals or input filter functions for getting HTTP request body data when POST
is not used. What are disciples of Roy Fielding to do? ;-)
That being said, as you advance in your PHP programming knowledge and want to use JavaScript's XmlHttpRequest
object (jQuery for some), you come to see the limitation of this scheme.
$_POST
limits you to the use of two media types in the HTTP Content-Type
header:
application/x-www-form-urlencoded
, andmultipart/form-data
Thus, if you want to send data values to PHP on the server, and have it show up in the $_POST
superglobal, then you must urlencode it on the client-side and send said data as key/value pairs--an inconvenient step for novices (especially when trying to figure out if different parts of the URL require different forms of urlencoding: normal, raw, etc..).
For all you jQuery users, the $.ajax()
method is converting your JSON to URL encoded key/value pairs before transmitting them to the server. You can override this behavior by setting processData: false
. Just read the $.ajax() documentation, and don't forget to send the correct media type in the Content-Type header.
Even if you use php://input
instead of $_POST
for your HTTP POST
request body data, it will not work with an HTTP Content-Type
of multipart/form-data
This is the content type that you use on an HTML form when you want to allow file uploads!
<form enctype="multipart/form-data" accept-charset="utf-8" action="post">
<input type="file" name="resume">
</form>
Therefore, in traditional PHP, to deal with a diversity of content types from an HTTP POST
request, you will learn to use $_POST
or filter_input_array(POST)
, $_FILES
, and php://input
. There is no way to just use one, universal input source for HTTP POST
requests in PHP.
You cannot get files through $_POST
, filter_input_array(POST), or php://input
, and you cannot get JSON/XML/YAML in either filter_input_array(POST)
or $_POST
.
php://input is a read-only stream that allows you to read raw data from the request body...php://input is not available with enctype="multipart/form-data".
PHP frameworks like Codeigniter 4 and Laravel use a facade to provide a cleaner interface (IncomingRequest
or Request
objects) to the above. This is why professional PHP developers use frameworks instead of raw PHP.
Of course, if you like to program, you can devise your own facade object to provide what frameworks do. It is because I have taken time to investigate this issue that I am able to write this answer.
Typically, if you are doing a normal, synchronous (when the entire page redraws) HTTP requests with an HTML form, the user-agent (web browser) will urlencode your form data for you. If you want to do an asynchronous HTTP requests using the XmlHttpRequest
object, then you must fashion a urlencoded string and send it, if you want that data to show up in the $_POST
superglobal.
Converting from a JavaScript array or object to a urlencoded string bothers many developers (even with new APIs like Form Data). They would much rather just be able to send JSON, and it would be more efficient for the client code to do so.
Remember (wink, wink), the average web developer does not learn to use the XmlHttpRequest
object directly, global functions, string functions, array functions, and regular expressions like you and I ;-). Urlencoding for them is a nightmare. ;-)
PHP's lack of intuitive XML and JSON handling turns many people off. You would think it would be part of PHP by now (sigh).
XML, JSON, and YAML all have media types that can be put into an HTTP Content-Type
header.
Look how many media-types (formerly, MIME types) are defined by IANA.
Look how many HTTP headers there are.
Using the php://input
stream allows you to circumvent the baby-sitting / hand holding level of abstraction that PHP has forced on the world. :-) With great power comes great responsibility!
Now, before you deal with data values streamed through php://input
, you should / must do a few things.
AH, HA! Yes, you might want the data stream being sent into your application to be UTF-8 encoded, but how can you know if it is or not?
php://input
.Are you going to attempt to handle stream data without knowing how much is there first? That is a terrible idea. You cannot rely exclusively on the HTTP Content-Length
header for guidance on the size of streamed input because it can be spoofed.
You are going to need a:
Are you going to attempt to convert stream data to UTF-8 without knowing the current encoding of the stream? How? The iconv stream filter (iconv stream filter example) seems to want a starting and ending encoding, like this.
'convert.iconv.ISO-8859-1/UTF-8'
Thus, if you are conscientious, you will need:
(Update: 'convert.iconv.UTF-8/UTF-8'
will force everything to UTF-8, but you still have to account for characters that the iconv library might not know how to translate. In other words, you have to some how define what action to take when a character cannot be translated: 1) Insert a dummy character, 2) Fail / throw and exception).
You cannot rely exclusively on the HTTP Content-Encoding
header, as this might indicate something like compression as in the following. This is not what you want to make a decision off of in regards to iconv.
Content-Encoding: gzip
Part I: HTTP Request Related
Part II: Stream Data Related
Part III: Data Type Related
(Remember, the data can still be a URL encoded string which you must then parse and URL decode).
Part IV: Data Value Related
Filter input data.
Validate input data.
The $_POST
superglobal, along with php.ini settings for limits on input, are simpler for the layman. However, dealing with character encoding is much more intuitive and efficient when using streams because there is no need to loop through superglobals (or arrays, generally) to check input values for the proper encoding.
Swift 3
self.paddingView.layer.masksToBounds = false
self.paddingView.layer.shadowOffset = CGSize(width: -15, height: 10)
self.paddingView.layer.shadowRadius = 5
self.paddingView.layer.shadowOpacity = 0.5
<Directory /uploads>
Options +Indexes
</Directory>
This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!
randomFill()
to the current location of the array.Note: Your array is double
, but you are returning int
s from randomFill
. So there's something you need to fix there.
As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.
Perform followings steps to do the needful.
exec sp_helpconstraint '<your table name>'
alter table <your_table_name>
drop constraint <constraint_name_that_you_copied_in_1>
(It'll be something like this only or similar format)Alter table <YourTableName> Drop column column1, column2
etcIf you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Another alternative that uses an external library is _.has() from Lodash.
E.g.
_.has(a, 'b.c')
is equal to
(a && a.b && a.b.c)
EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.
is
will compare the memory location. It is used for object-level comparison.
==
will compare the variables in the program. It is used for checking at a value level.
is
checks for address level equivalence
==
checks for value level equivalence
I don't think such a thing is possible. You can use SUBSTRING
function to extract the part you want.
According to the php manual, the finfo-file function is best way to do this. However, you will need to install the FileInfo PECL extension.
If the extension is not an option, you can use the outdated mime_content_type function.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href
attribute of the anchor like so:
<a href="javascript:alert('I am your script.'); alert('So am I.');">Click me</a>
As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.
In my case:
antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip pip2 pip2.7 pip3 pip3.5
And then just uninstall with the specific pip version.
I dont have access to a Solaris machine, but grep "\-X"
works for me on linux.
Schedule provides various ajax behavior events to respond user actions.
there is more in here https://www.primefaces.org/docs/guide/primefaces_user_guide_5_0.pdf
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
A similar option in Sublime Text is the built in Edit->Line->Reindent
. You can put this code in Preferences -> Key Bindings User
:
{ "keys": ["alt+shift+f"], "command": "reindent"}
I use alt+shift+f because I'm a Netbeans user.
To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.
Or if you don't want to select all before formatting, add an argument to the command instead:
{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }
(as per comment by @Supr below)
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Go to Run type services.msc
. Check whether MySQL services is running or not. If not, start it manually. Once it started, type mysqlshow
to test the service.
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
Try this:
$(".use-address").click(function() {
$(this).closest('tr').find('td').each(function() {
var textval = $(this).text(); // this will be the text of each <td>
});
});
This will find the closest tr
(going up through the DOM) of the currently clicked button and then loop each td
- you might want to create a string / array with the values.
You can also set DirectoryIndex in apache's httpd.conf file.
CentOS keeps this file in /etc/httpd/conf/httpd.conf
Debian: /etc/apache2/apache2.conf
Open the file in your text editor and find the line starting with DirectoryIndex
To load landing.html as a default (but index.html if that's not found) change this line to read:
DirectoryIndex landing.html index.html
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
I think you are trying to toggle the disabled state, in witch case you should use this (from this question):
$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });
If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS
doesn't include 'n'.
Turning off line numbers by default (for example, setting LESS=n
) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.
I typically run with LESS=RSXin
(escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less
as needed.
Performance-wise it's the same as a named method. The big problem is when you do the following:
MyButton.Click -= (o, i) =>
{
//snip
}
It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.
The best practice is to compare it using constructor
, something like this
if(some_variable.constructor === Array){
// do something
}
You can use other methods too like typeOf
, converting it to a string and then comparing but comparing it with dataType is always a better approach.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Here is simple steps add this gradle:
dependencies {
compile "com.google.firebase:firebase-messaging:9.0.0"
}
No extra permission are needed in manifest like GCM.
No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver
is added automatically.
Migrate your listener service
A service extending InstanceIDListenerService
is now required only if you want to access the FCM token.
This is needed if you want to
Add Service in manifest
<service
android:name=".MyInstanceIDListenerService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Change MyInstanceIDListenerService
to extend FirebaseInstanceIdService
, and update code to listen for token updates and get the token whenever a new token is generated.
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
...
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is also called
* when the InstanceID token is initially generated, so this is where
* you retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
}
For more information visit
Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.
The Set statement is only used for object variables (like Range
, Cell
or Worksheet
in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer
. You can find a good explanation for when to use set here.
The other problem is, that your variable g1val
isn't actually declared as Integer
, but has the type Variant
. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant
. You can only shorten your Dim statement this way:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.
Try this example to understand the difference:
Sub Dimming()
Dim thisBecomesVariant, thisIsAnInteger As Integer
Dim integerOne As Integer, integerTwo As Integer
MsgBox TypeName(thisBecomesVariant) 'Will display "Empty"
MsgBox TypeName(thisIsAnInteger ) 'Will display "Integer"
MsgBox TypeName(integerOne ) 'Will display "Integer"
MsgBox TypeName(integerTwo ) 'Will display "Integer"
'By assigning an Integer value to a Variant it becomes Integer, too
thisBecomesVariant = 0
MsgBox TypeName(thisBecomesVariant) 'Will display "Integer"
End Sub
Two further notices on your code:
First remark: Instead of writing
'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
g1val = g1val 'Don't change g1val
Else
g1val = Cells(33, i).Value 'Otherwise set g1val to the cell's value
End If
you could simply write
'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
g1val = Cells(33, i).Value 'Set g1val to the cell's value
End If
Since you don't want to change g1val
in the other case.
Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.
Opera 12 (not the latest Chrome Webkit engine based) Dragonfly has had this for a while and is obviously displayed in the DOM structure. In my opinion it is a superior debugger and is the only reason remaining why I still use the Opera 12 based version (there is no v13, v14 version and the v15 Webkit based lacks Dragonfly still)
<html>
<title>Practice Session</title>
<body>
<form name="RegForm" onsubmit="return validate()" method="post">
<p>Name: <input type="text" name="Name"> </p><br>
<p>Contact: <input type="text" name="Telephone"> </p><br>
<p><input type="submit" value="send" name="Submit"></p>
</form>
</body>
<script>
function validate()
{
var name = document.forms["RegForm"]["Name"];
var phone = document.forms["RegForm"]["Telephone"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{
window.alert("please enter character");
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}
}
</script>
</html>
What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.
Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.
Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.
Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.
Full disclosure: I'm a co-founder :)
Using bash regular expressions:
re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi
Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.
re="http://([^/]+)/"
This is the regular expression stored in a bash variable, re
- i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:
http://
is just a string - the input string must contain this substring for the regular expression to match[]
Normally square brackets are used say "match any character within the brackets". So c[ao]t
would match both "cat" and "cot". The ^
character within the []
modifies this to say "match any character except those within the square brackets. So in this case [^/]
will match any character apart from "/".+
to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+
matches 1 or more of the set of all characters, excluding "/".()
parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:
if [[ $name =~ $re ]]; then
echo ${BASH_REMATCH[1]}
fi
In bash, the [[ ]]
specify an extended conditional test, and may contain the =~
bash regular expression operator. In this case we test whether the input string $name
matches the regular expression $re
. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()
), and we can access it using the BASH_REMATCH array:
${BASH_REMATCH[0]}
will be the entire string matched by the regular expression, i.e. "http://www.google.com/".()
within a regular expression - The BASH_REMATCH
elements will correspond to these in order. So in this case ${BASH_REMATCH[1]}
will contain "www.google.com", which I think is the string you want.Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~
operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.
This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.
Note that instead of setting the $re
variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~
match operator.
Not sure it will help people but this one worked for me :
So the issue I had was that I was getting the following message:
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "My.Resources.Resources.resources" was correctly embedded or linked into assembly "X" at compile time, or that all the satellite assemblies required are loadable and fully signed"
I was trying to get the resources that were embedded in my project from another class library.
What I did to fix the problem was to set the Access Modifier in the tab Project->Properties->Resources from "Internal" (accessible only within the same class library) to "Public" (accessible from another class library)
Then run and voilà, no more error for me...
If you log in a web application using tomcat add:
-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
On VM arguments
You may also used foreach loop for display category image and etc from parent category given by parent id.
for example, i am giving 74 id of parent category, then i will display the image from child category and its slug also.
**<?php
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'child_of'=>'74'));
foreach($catTerms as $catTerm) : ?>
<?php $thumbnail_id = get_woocommerce_term_meta( $catTerm->term_id, 'thumbnail_id', true );
// get the image URL
$image = wp_get_attachment_url( $thumbnail_id ); ?>
<li><img src="<?php echo $image; ?>" width="152" height="245"/><span><?php echo $catTerm->name; ?></span></li>
<?php endforeach; ?>**
I kept having this problem because windows was setting my node_modules
folder to Readonly. Make sure you uncheck this.
Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.
@Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer
will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
A one-liner using the or
operator:
($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
Step 1:
Go to a fiddle page like jsfiddle.net/oskar/v5893p61
Step 2:
Add '/show' at the end of the URL, like jsfiddle.net/oskar/v5893p61/show
Step 3:
Right click on the page and click on the View frame source. You will get the HTML code including CSS in tag and Javascript (js) in tag. [Also source link of all library will be added].
See screenshot
Step 4:
Now you can save the source code in a .html file.
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
In the example you shared you are loading the existing file into book
and setting the writer.book
value to be book
. In the line writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
you are accessing each sheet in the workbook as ws
. The sheet title is then ws
so you are creating a dictionary of {sheet_titles: sheet}
key, value pairs. This dictionary is then set to writer.sheets. Essentially these steps are just loading the existing data from 'Masterfile.xlsx'
and populating your writer with them.
Now let's say you already have a file with x1
and x2
as sheets. You can use the example code to load the file and then could do something like this to add x3
and x4
.
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
writer = pd.ExcelWriter(path, engine='openpyxl')
df3.to_excel(writer, 'x3', index=False)
df4.to_excel(writer, 'x4', index=False)
writer.save()
That should do what you are looking for.
The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
And then back again:
textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
A much simpler solution, without all the inside form-group
elements
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<input type="text" class="form-control" placeholder="year" style="width:70px;"/>
<input type="text" class="form-control" placeholder="month" style="width:80px;"/>
<input type="text" class="form-control" placeholder="day" style="width:100px;"/>
</div>
</div>
</div>
... and it will look like this,
Cheers!
There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:
If you need the code source:
with curl:
curl $url
with wget:
wget -O - $url
but if you want to get what you can see with a browser, lynx can be useful:
lynx -dump $url
I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url
by your URL :)
Good luck :)
To modify the column in mysql we use alter and modify keywords. Suppose we have created a table like:
create table emp(
id varchar(20),
ename varchar(20),
salary float
);
Now we want to modify type of the column id to integer with auto increment. You could do this with a command like:
alter table emp modify column id int(10) auto_increment;
An easy way is :
wstring your_wchar_in_ws(<your wchar>);
string your_wchar_in_str(your_wchar_in_ws.begin(), your_wchar_in_ws.end());
char* your_wchar_in_char = your_wchar_in_str.c_str();
I'm using this method for years :)
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
There is an article available in which explains how to perform multiple deletion paths using triggers. Maybe this is useful for complex scenarios.
Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.
There is a comprehensive list of tools on the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/PostgreSQL_Clients
And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.
Also you can
use it lowercase
under below
let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)
Output
68b696d7-320b-4402-a412-d9cee10fc6a3
Thank you !
For me I had to go a different route. Instead of trying to fix the JSON.Net serializer I had to go after the Lazy Loading on my datacontext.
I just added this to my base repository:
context.Configuration.ProxyCreationEnabled = false;
The "context" object is a constructor parameter I use in my base repository because I use dependency injection. You could change the ProxyCreationEnabled property anywhere you instantiate your datacontext instead.
http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html
Sweet and simple:
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
you need to add this tags to your pom.xml
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
I asked recently about something similar.
If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)
This allows you to do:
[Flags]
public enum PossibleOptions : byte
{
None = 0,
OptionOne = 1,
OptionTwo = 2,
OptionThree = 4,
OptionFour = 8,
//combinations can be in the enum too
OptionOneAndTwo = OptionOne | OptionTwo,
OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,
...
}
Then you can do:
PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree
if( opt.IsSet( PossibleOptions.OptionOne ) ) {
//optionOne is one of those set
}
I find this easier to read than the most ways of checking the included flags.
Fitting a moving average to your data would smooth out the noise, see this this answer for how to do that.
If you'd like to use LOWESS to fit your data (it's similar to a moving average but more sophisticated), you can do that using the statsmodels library:
import numpy as np
import pylab as plt
import statsmodels.api as sm
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
lowess = sm.nonparametric.lowess(y, x, frac=0.1)
plt.plot(x, y, '+')
plt.plot(lowess[:, 0], lowess[:, 1])
plt.show()
Finally, if you know the functional form of your signal, you could fit a curve to your data, which would probably be the best thing to do.
This thread is old but I wanted to do same things with the https://github.com/mikeal/request package.
Here a working example
var fs = require('fs');
var request = require('request');
// Or with cookies
// var request = require('request').defaults({jar: true});
request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
});
});
I had the same problem when I wrote two upstreams in NGINX conf
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
server 127.0.0.1:9000;
}
...
fastcgi_pass php_upstream;
but in /etc/php/7.3/fpm/pool.d/www.conf
I listened the socket only
listen = /var/run/php/my.site.sock
So I need just socket, no any 127.0.0.1:9000
, and I just removed IP+port upstream
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
}
This could be rewritten without an upstream
fastcgi_pass unix:/var/run/php/my.site.sock;
With the YouTube video updated as of June 2020 it's very straight forward
You will get and .sbv file
From django docs:
render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.
direct_to_template
is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
For now I just switched registry URL from https to http. Like this:
npm config set registry="http://registry.npmjs.org/"
Change %
to %%
for use in batch file, for %~ta
syntax enter call /?
for %a in (MyFile.txt) do set FileDate=%~ta
Sample output:
for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM
for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=
My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.
To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list
or an object
as root. So I considered that my JSON file always has a list of objects
and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w
):
def saveJson(url,sc): # This function writes the two values to the file
newdata = {'url':url,'sc':sc}
json_path = "db/file.json"
old_list= []
with open(json_path) as myfile: # Read the contents first
old_list = json.load(myfile)
old_list.append(newdata)
with open(json_path,"w") as myfile: # Overwrite the whole content
json.dump(old_list, myfile, sort_keys=True, indent=4)
return "success"
The new JSON file will look something like this:
[
{
"sc": "a11",
"url": "www.google.com"
},
{
"sc": "a12",
"url": "www.google.com"
},
{
"sc": "a13",
"url": "www.google.com"
}
]
NOTE: It is essential to have a file named file.json
with []
as initial data for this approach to work
PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.
Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.
import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Capturing",frame)
# 6.for playing
key = cv2.waitKey(1)
if key == ord('q'):
break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows
You can see my github code here
For swift 2.0 and above do this
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.userInteractionEnabled = true
}
func tappedMe()
{
print("Tapped on Image")
}
% Assuming that the dataset is ";"-delimited and each line ends with ";"
fid = fopen('sampledata.csv');
tline = fgetl(fid);
u=sprintf('%c',tline); c=length(u);
id=findstr(u,';'); n=length(id);
data=cell(1,n);
for I=1:n
if I==1
data{1,I}=u(1:id(I)-1);
else
data{1,I}=u(id(I-1)+1:id(I)-1);
end
end
ct=1;
while ischar(tline)
ct=ct+1;
tline = fgetl(fid);
u=sprintf('%c',tline);
id=findstr(u,';');
if~isempty(id)
for I=1:n
if I==1
data{ct,I}=u(1:id(I)-1);
else
data{ct,I}=u(id(I-1)+1:id(I)-1);
end
end
end
end
fclose(fid);
This answer
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
}
is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:
for (var i = someArray.length - 1; i>= 0; i--)
...
instead .
I have recently written a plugin that does exactly that - jquery.initialize
You use it the same way as .each
function
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
The difference from .each
is - it takes your selector, in this case .some-element
and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.
In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .detach()
it from body and then add it again, it will not be initialized again.
$("<div/>").addClass('some-element').appendTo("body").detach()
.appendTo(".some-container");
//initialized only once
Plugin is based on MutationObserver
- it will work on IE9 and 10 with dependencies as detailed on the readme page.
Ensure these two and it should work:-
Fixes this issue on windows like a charm.
try this:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
What is a smart pointer.
Long version, In principle:
https://web.stanford.edu/class/archive/cs/cs106l/cs106l.1192/lectures/lecture15/15_RAII.pdf
A modern C++ idiom:
RAII: Resource Acquisition Is Initialization.
? When you initialize an object, it should already have
acquired any resources it needs (in the constructor).
? When an object goes out of scope, it should release every
resource it is using (using the destructor).
key point:
? There should never be a half-ready or half-dead object.
? When an object is created, it should be in a ready state.
? When an object goes out of scope, it should release its resources.
? The user shouldn’t have to do anything more.
Raw Pointers violate RAII: It need user to delete manually when the pointers go out of scope.
RAII solution is:
Have a smart pointer class:
? Allocates the memory when initialized
? Frees the memory when destructor is called
? Allows access to underlying pointer
For smart pointer need copy and share, use shared_ptr:
? use another memory to store Reference counting and shared.
? increment when copy, decrement when destructor.
? delete memory when Reference counting is 0.
also delete memory that store Reference counting.
for smart pointer not own the raw pointer, use weak_ptr:
? not change Reference counting.
shared_ptr usage:
correct way:
std::shared_ptr<T> t1 = std::make_shared<T>(TArgs);
std::shared_ptr<T> t2 = std::shared_ptr<T>(new T(Targs));
wrong way:
T* pt = new T(TArgs); // never exposure the raw pointer
shared_ptr<T> t1 = shared_ptr<T>(pt);
shared_ptr<T> t2 = shared_ptr<T>(pt);
Always avoid using raw pointer.
For scenario that have to use raw pointer:
https://stackoverflow.com/a/19432062/2482283
For raw pointer that not nullptr, use reference instead.
not use T*
use T&
For optional reference which maybe nullptr, use raw pointer, and which means:
T* pt; is optional reference and maybe nullptr.
Not own the raw pointer,
Raw pointer is managed by some one else.
I only know that the caller is sure it is not released now.
I may be arising by aoColumns field. As stated HERE
aoColumns: If specified, then the length of this array must be equal to the number of columns in the original HTML table. Use 'null' where you wish to use only the default values and automatically detected options.
Then you have to add fields as in table Columns
...
aoColumnDefs: [
null,
null,
null,
{ "bSortable": false },
null,
],
...
MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.
The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.
Thus, (4,2)
can be anything from -99.99
to 99.99
.
As for why you're getting 99.99
instead of the desired 3.80
, the value you're inserting must be interpreted as larger than 99.99
, so the max value is used. Maybe you could post the code that you are using to insert or update the table.
Edit
Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.
Writing JSON Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject
and looping through each json item. Below i am creating an instance of JSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
Stream version, filters spaces and tabs.
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
Look for GSpread.NET. You can work with Google Spreadsheets by using API from Microsoft Excel. You don't need to rewrite old code with the new Google API usage. Just add a few row:
Set objExcel = CreateObject("GSpreadCOM.Application");
app.MailLogon(Name, ClientIdAndSecret, ScriptId);
It's an OpenSource project and it doesn't require Office to be installed.
The documentation available over here http://scand.com/products/gspread/index.html
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesthis is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.