Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.
lines = (line.rstrip('\n') for line in open(filename))
However, you'll most likely want to use this to get rid of trailing whitespaces too.
lines = (line.rstrip() for line in open(filename))
ip addr show | grep -E '^\s*inet' | grep -m1 global | awk '{ print $2 }' | sed 's|/.*||'
Using jQuery, the following are identical in effect:
$('a').click(function(){ doSomething(); });
$('a').on('click', function(){ doSomething(); });
With the input
event, however, only the second pattern seems to work in the browsers I've tested.
Thus, you'd expect this to work, but it DOES NOT (at least currently):
$(':text').input(function(){ doSomething(); });
Again, if you wanted to leverage event delegation (e.g. to set up the event on the #container
before your input.text
is added to the DOM), this should come to mind:
$('#container').on('input', ':text', function(){ doSomething(); });
Sadly, again, it DOES NOT work currently!
Only this pattern works:
$(':text').on('input', function(){ doSomething(); });
EDITED WITH MORE CURRENT INFORMATION
I can certainly confirm that this pattern:
$('#container').on('input', ':text', function(){ doSomething(); });
NOW WORKS also, in all 'standard' browsers.
I found "npm config edit" to be more useful to update the entries for https-proxy, proxy, registry
I did something like this
This is old question but still my answer may help someone
For checking Java version in android studio version , simply open Terminal of Android Studio and type
java -version
This will display java version installed in android studio
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH
environment variable (or other language equivalent, like PYTHONPATH
, LD_LIBRARY_PATH
) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
As for today, answers of @knowbody (https://stackoverflow.com/a/42418963/6778546) and @Rocket Hazmat (https://stackoverflow.com/a/8837511/6778546) can be combined to provide for ES2015 support and correct date handling:
arr.sort((a, b) => {
const dateA = new Date(a.updated_at);
const dateB = new Date(b.updated_at);
return dateA - dateB;
});
The issue is due to incompatibility of unity with latest Android build tools. For MacOS here's a one liner that will get it working for you:
cd $ANDROID_HOME; rm -rf tools; wget http://dl-ssl.google.com/android/repository/tools_r25.2.5-ma??cosx.zip; unzip tools_r25.2.5-macosx.zip
As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here
Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.
I had this problem. For posterity, my exception was:
org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 117;
schema_reference.4: Failed to read schema document
'http://www.springframework.org/schema/beans/spring-beans-4.2.xsd'
I solved it when I realised the the version of spring-beans
specified in my Maven pom.xml
was 4.1.x
, thus meaning the specific .xsd
could not be found on the classpath.
This was masked for a long time because I normally am online, so I thought being offline had "broken" the build. But it really had nothing to do with it. Updating my pom.xml
to specify the correct version of spring-beans
, namely 4.2.x
, fixed it.
This process preserve history, but is little workarround:
# make branchs to new files
$: git mv arquivos && git commit
# in original branch, remove original files
$: git rm arquivos && git commit
# do merge and fix conflicts
$: git merge branch-copia-arquivos
# back to original branch and revert commit removing files
$: git revert commit
More or less this page has answers but all are not at one place. I was dealing with the same issue and spent quite a good time on it. Now i have a better understanding and i would like to share it here:
I Enabling Swagger ui with Spring websecurity:
If you have enabled Spring Websecurity by default it will block all the requests to your application and returns 401. However for the swagger ui to load in the browser swagger-ui.html makes several calls to collect data. The best way to debug is open swagger-ui.html in a browser(like google chrome) and use developer options('F12' key ). You can see several calls made when the page loads and if the swagger-ui is not loading completely probably some of them are failing.
you may need to tell Spring websecurity to ignore authentication for several swagger path patterns. I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:
However if you are using a different version your's might change. you may have to figure out yours with developer option in your browser as i said before.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
}
II Enabling swagger ui with interceptor
Generally you may not want to intercept requests that are made by swagger-ui.html. To exclude several patterns of swagger below is the code:
Most of the cases pattern for web security and interceptor will be same.
@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {
@Autowired
RetrieveInterceptor validationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
.excludePathPatterns("/v2/api-docs", "/configuration/ui",
"/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
, "/webjars/**", "/csrf", "/");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
Below code will hide your text with fixed width you decide. but not quite right for responsive designs.
.CropLongTexts {
width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Update
I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:
.CropLongTexts {
max-width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.
> C:\java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
The -X
options are non-standard and subject to change without notice.
(copy-paste)
render: ->
<a className="upvotes" onClick={(e) => {this.upvote(e); }}>upvote</a>
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
For a bit of facts here is the relevant text from the specifications
Pointers to objects of the same type can be compared for equality with the 'intuitive' expected results:
From § 5.10 of the C++11 standard:
Pointers of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address (3.9.2).
(leaving out details on comparison of pointers to member and or the null pointer constants - they continue down the same line of 'Do What I Mean':)
- [...] If both operands are null, they compare equal. Otherwise if only one is null, they compare unequal.[...]
The most 'conspicuous' caveat has to do with virtuals, and it does seem to be the logical thing to expect too:
- [...] if either is a pointer to a virtual member function, the result is unspecified. Otherwise they compare equal if and only if they would refer to the same member of the same most derived object (1.8) or the same subobject if they were dereferenced with a hypothetical object of the associated class type. [...]
From § 5.9 of the C++11 standard:
Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows:
- If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then
p<=q
andp>=q
both yield true andp<q
andp>q
both yield false.- If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of
p<q,
p>q,
p<=q,
andp>=q
are unspecified.- If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.
- If two pointers point to non-static data members of the same object with different access control (Clause 11) the result is unspecified.
- If two pointers point to non-static data members of the same union object, they compare equal (after conversion to
void*
, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.- Other pointer comparisons are unspecified.
So, if you had:
int arr[3];
int *a = arr;
int *b = a + 1;
assert(a != b); // OK! well defined
Also OK:
struct X { int x,y; } s;
int *a = &s.x;
int *b = &s.y;
assert(b > a); // OK! well defined
But it depends on the something
in your question:
int g;
int main()
{
int h;
int i;
int *a = &g;
int *b = &h; // can't compare a <=> b
int *c = &i; // can't compare b <=> c, or a <=> c etc.
// but a==b, b!=c, a!=c etc. are supported just fine
}
§ 20.8.5/8: "For templates greater
, less
, greater_equal
, and less_equal
, the specializations for any pointer type yield a total order, even if the built-in operators <
, >
, <=
, >=
do not."
So, you can globally order any odd void*
as long as you use std::less<>
and friends, not bare operator<
.
I'm assuming you've got a nice fat USB HD and a good connection to the net. You can use apt-mirror to essentially create your own debian mirror.
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
You should use the following:
$('#gentab').on('click', 'a.tabclick', function(event) {
event.preventDefault();
var liId = $(this).closest("li").attr("id");
alert(liId);
});
This will attach your event to any anchors within the #gentab
element,
reducing the scope of having to check the whole document
element tree and increasing efficiency.
If you've upgraded to Mac OS X 10.8 Mountain Lion, and previously had a working system, all you should need to do is re-enable PHP as in Step 1 of the above chosen answer.
You may also find the following Preference Pane useful for managing "web sharing" (Apache web server), which replaces system functionality removed in OS X 10.8: http://clickontyler.com/blog/2012/02/web-sharing-mountain-lion/
I also had to re-add my virtual hosts include line to the httpd.conf
First, to answer "why doesn't VOLUME
work?" When you define a VOLUME
in the Dockerfile, you can only define the target, not the source of the volume. During the build, you will only get an anonymous volume from this. That anonymous volume will be mounted at every RUN
command, prepopulated with the contents of the image, and then discarded at the end of the RUN
command. Only changes to the container are saved, not changes to the volume.
Since this question has been asked, a few features have been released that may help. First is multistage builds allowing you to build a disk space inefficient first stage, and copy just the needed output to the final stage that you ship. And the second feature is Buildkit which is dramatically changing how images are built and new capabilities are being added to the build.
For a multi-stage build, you would have multiple FROM
lines, each one starting the creation of a separate image. Only the last image is tagged by default, but you can copy files from previous stages. The standard use is to have a compiler environment to build a binary or other application artifact, and a runtime environment as the second stage that copies over that artifact. You could have:
FROM debian:sid as builder
COPY export /export
RUN compile command here >/result.bin
FROM debian:sid
COPY --from=builder /result.bin /result.bin
CMD ["/result.bin"]
That would result in a build that only contains the resulting binary, and not the full /export directory.
Buildkit is coming out of experimental in 18.09. It's a complete redesign of the build process, including the ability to change the frontend parser. One of those parser changes has has implemented the RUN --mount
option which lets you mount a cache directory for your run commands. E.g. here's one that mounts some of the debian directories (with a reconfigure of the debian image, this could speed up reinstalls of packages):
# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/var/lib/apt/lists,type=cache \
--mount=target=/var/cache/apt,type=cache \
apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
git
You would adjust the cache directory for whatever application cache you have, e.g. $HOME/.m2 for maven, or /root/.cache for golang.
TL;DR: Answer is here: With that RUN --mount
syntax, you can also bind mount read-only directories from the build-context. The folder must exist in the build context, and it is not mapped back to the host or the build client:
# syntax = docker/dockerfile:experimental
FROM debian:latest
RUN --mount=target=/export,type=bind,source=export \
process export directory here...
Note that because the directory is mounted from the context, it's also mounted read-only, and you cannot push changes back to the host or client. When you build, you'll want an 18.09 or newer install and enable buildkit with export DOCKER_BUILDKIT=1
.
If you get an error that the mount flag isn't supported, that indicates that you either didn't enable buildkit with the above variable, or that you didn't enable the experimental syntax with the syntax line at the top of the Dockerfile before any other lines, including comments. Note that the variable to toggle buildkit will only work if your docker install has buildkit support built in, which requires version 18.09 or newer from Docker, both on the client and server.
It's impossible, and for a good reason (for one, think about all those catch(Exception){} around).
If you want to continue execution after stack overflow, run dangerous code in a different AppDomain. CLR policies can be set to terminate current AppDomain on overflow without affecting original domain.
Since the original question also involves a desktop and laptop and example involving music files (hence he's probably using a GUI), I'd also mention one of the best bi-directional, multi-platform, free and open source programs to date: FreeFileSync.
It's GUI based, very fast and intuitive, comes with filtering and many other options, including the ability to remote connect, to view and interactively manage "collisions" (in example, files with similar timestamps) and to switch between bidirectional transfer, mirroring and so on.
You can do it by javascript on client side or using some regex validator on the textbox.
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
Try this (in the psql
command-line tool):
\d+ tablename
See the manual for more info.
Here is my simple code FormData with react-native to post request with string and image.
I have used react-native-image-picker to capture/select photo react-native-image-picker
let photo = { uri: source.uri}
let formdata = new FormData();
formdata.append("product[name]", 'test')
formdata.append("product[price]", 10)
formdata.append("product[category_ids][]", 2)
formdata.append("product[description]", '12dsadadsa')
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
NOTE you can change image/jpeg
to other content type. You can get content type from image picker response.
fetch('http://192.168.1.101:3000/products',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
console.log("image uploaded")
}).catch(err => {
console.log(err)
})
});
while read -r num; do ((sum += num)); done < inputfile; echo $sum
I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
Using answer from @nathanielperales i've added hover function cause for me it works better when user loses focus on map to stop scrolling again :)
$(function(){
$('.mapa').hover(function(){
stopScroll();},
function () {
$('.mapa iframe').css("pointer-events", "none");
});
});
function stopScroll(){
$('.mapa').click(function () {
$('.mapa iframe').css("pointer-events", "auto");
});
}
Or if You are little less on the evangelist's side You can do a little ugly way I'm using. In deploy_template there are commits I want to copy on my master as branch deploy
git branch deploy deploy_template
git checkout deploy
git rebase master
This will create new branch deploy (I use -f to overwrite existing deploy branch) on deploy_template, then rebase this new branch onto master, leaving deploy_template untouched.
Just to add, in django, if you have a query like:
MyModel.objects.all()
do:
MyModel.objects.all().query.sql_with_params()
or:
str(MyModel.objects.all().query)
to get the sql string
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
In maven, folder resources, create the same package structure where the configuration files are located and copy them there
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
The top 2 answers (from Adam Robinson and Andrejs Cainikovs) are kinda, sorta correct, in that they do technically work, but their explanations are wrong and so could be misleading in many cases. For example, while the SQL_Latin1_General_CP1_CI_AS
collation will work in many cases, it should not be assumed to be the appropriate case-insensitive collation. In fact, given that the O.P. is working in a database with a case-sensitive (or possibly binary) collation, we know that the O.P. isn't using the collation that is the default for so many installations (especially any installed on an OS using US English as the language): SQL_Latin1_General_CP1_CI_AS
. Sure, the O.P. could be using SQL_Latin1_General_CP1_CS_AS
, but when working with VARCHAR
data, it is important to not change the code page as it could lead to data loss, and that is controlled by the locale / culture of the collation (i.e. Latin1_General vs French vs Hebrew etc). Please see point # 9 below.
The other four answers are wrong to varying degrees.
I will clarify all of the misunderstandings here so that readers can hopefully make the most appropriate / efficient choices.
Do not use UPPER()
. That is completely unnecessary extra work. Use a COLLATE
clause. A string comparison needs to be done in either case, but using UPPER()
also has to check, character by character, to see if there is an upper-case mapping, and then change it. And you need to do this on both sides. Adding COLLATE
simply directs the processing to generate the sort keys using a different set of rules than it was going to by default. Using COLLATE
is definitely more efficient (or "performant", if you like that word :) than using UPPER()
, as proven in this test script (on PasteBin).
There is also the issue noted by @Ceisc on @Danny's answer:
In some languages case conversions do not round-trip. i.e. LOWER(x) != LOWER(UPPER(x)).
The Turkish upper-case "I" is the common example.
No, collation is not a database-wide setting, at least not in this context. There is a database-level default collation, and it is used as the default for altered and newly created columns that do not specify the COLLATE
clause (which is likely where this common misconception comes from), but it does not impact queries directly unless you are comparing string literals and variables to other string literals and variables, or you are referencing database-level meta-data.
No, collation is not per query.
Collations are per predicate (i.e. something operand something) or expression, not per query. And this is true for the entire query, not just the WHERE
clause. This covers JOINs, GROUP BY, ORDER BY, PARTITION BY, etc.
No, do not convert to VARBINARY
(e.g.convert(varbinary, myField) = convert(varbinary, 'sOmeVal')
) for the following reasons:
_BIN2
if you are using SQL Server 2008 or newer, else you have no choice but to use one that ends with _BIN
. If the data is NVARCHAR
then it doesn't matter which locale you use as they are all the same in that case, hence Latin1_General_100_BIN2
always works. If the data is VARCHAR
, you must use the same locale that the data is currently in (e.g. Latin1_General
, French
, Japanese_XJIS
, etc) because the locale determines the code page that is used, and changing code pages can alter the data (i.e. data loss).CONVERT()
it will use the 30 default value. The danger is, if the string can be over 30 bytes, it will get silently truncated and you will likely get incorrect results from this predicate.No, LIKE
is not always case-sensitive. It uses the collation of the column being referenced, or the collation of the database if a variable is compared to a string literal, or the collation specified via the optional COLLATE
clause.
LCASE
is not a SQL Server function. It appears to be either Oracle or MySQL. Or possibly Visual Basic?
Since the context of the question is comparing a column to a string literal, neither the collation of the instance (often referred to as "server") nor the collation of the database have any direct impact here. Collations are stored per each column, and each column can have a different collation, and those collations don't need to be the same as the database's default collation or the instance's collation. Sure, the instance collation is the default for what a newly created database will use as its default collation if the COLLATE
clause wasn't specified when creating the database. And likewise, the database's default collation is what an altered or newly created column will use if the COLLATE
clause wasn't specified.
You should use the case-insensitive collation that is otherwise the same as the collation of the column. Use the following query to find the column's collation (change the table's name and schema name):
SELECT col.*
FROM sys.columns col
WHERE col.[object_id] = OBJECT_ID(N'dbo.TableName')
AND col.[collation_name] IS NOT NULL;
Then just change the _CS
to be _CI
. So, Latin1_General_100_CS_AS
would become Latin1_General_100_CI_AS
.
If the column is using a binary collation (ending in _BIN
or _BIN2
), then find a similar collation using the following query:
SELECT *
FROM sys.fn_helpcollations() col
WHERE col.[name] LIKE N'{CurrentCollationMinus"_BIN"}[_]CI[_]%';
For example, assuming the column is using Japanese_XJIS_100_BIN2
, do this:
SELECT *
FROM sys.fn_helpcollations() col
WHERE col.[name] LIKE N'Japanese_XJIS_100[_]CI[_]%';
For more info on collations, encodings, etc, please visit: Collations Info
You can use third party libraries for Clean Code like Apache Commons Lang and use it like:
byte[] bytes = ArrayUtils.addAll(a, b);
It is fast. Try it:
DELETE FROM YourTABLE
FROM (SELECT TOP XX PK FROM YourTABLE) tbl
WHERE YourTABLE.PK = tbl.PK
Replace YourTABLE
by table name,
XX
by a number, for example 1000,
pk
is the name of the primary key field of your table.
Here is a link with 100 useful queries, these are tested in Oracle database but remember SQL is a standard, what differ between Oracle, MS SQL Server, MySQL and other databases are the SQL dialect:
If you have mysqladmin
available, you may get the list of queries with:
> mysqladmin -uUSERNAME -pPASSWORD pr
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query | 292 | Sending data | DELETE FROM |
| 145 | root | localhost:55745 | | Query | 0 | | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
Then you may stop the mysql process that is hosting the long running query:
> mysqladmin -uUSERNAME -pPASSWORD kill 137
Its really helpful. The only problem i had was the size of sound file created after recording. I needed to reduce the file size so i did some changes in settings.
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
File size reduced from 360kb to just 25kb (2 seconds recording).
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
I think you are trying to check whether the array is empty or not.You can do like this :
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
Reference isEmpty()
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
A simple for
loop can also be handy:
> df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
> df
V1 V2 V3
1 2 7 9
2 8 3 6
3 1 5 4
> df2<-data.frame()
> for (i in 1:nrow(df)){
+ df2[i,1]<-colnames(df[which.max(df[i,])])
+ }
> df2
V1
1 V3
2 V1
3 V2
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\wsdl.exe
(via this question: Where can I find WSDL.exe?)
I had the same problems.
I solved it verifying that IE8 was not configured correctly to reach the SRC URL.
I changed this, it works right.
You can define instance method for js class, via prototype of the constructor.
Following is the sample code:
// BaseClass
var BaseClass = function(name) {
// instance property
this.name = name;
};
// instance method
BaseClass.prototype.getName = function() {
return this.name;
};
BaseClass.prototype.setName = function(name) {
return this.name = name;
};
// test - start
function test() {
var b1 = new BaseClass("b1");
var b2 = new BaseClass("b2");
console.log(b1.getName());
console.log(b2.getName());
b1.setName("b1_new");
console.log(b1.getName());
console.log(b2.getName());
}
test();
// test - end
And, this should work for any browser, you can also simply use nodejs to run this code.
If you want to test private methods, have a look at PrivateObject
and PrivateType
in the Microsoft.VisualStudio.TestTools.UnitTesting
namespace. They offer easy to use wrappers around the necessary reflection code.
Docs: PrivateType, PrivateObject
For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget
Note that the variables @fname
or @ext
can be simply concatenated. This:
forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"
renames all PDF files to "filename_old.pdf"
I have resolved it by deleting android-support-v4.jar
from my Project. Because appcompat_v7
already have a copy of it.
If you have already import appcompat_v7 but still the problem doesn't solve. then try it.
I found a post suggesting a solution for that. It's about to run:
svn resolve --accept working <YourPath>
which will claim the local version files as OK.
You can run it for single file or entire project catalogues.
JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.
You can use exec.java
.
The simulator puts the file in ~/Library/Developer/CoreSimulator/Devices/... but the path after /Devices is different for everyone.
Use this handy method. It returns the path of the temporary directory for the current user and takes no argument.
NSString * NSTemporaryDirectory ( void );
So in my ViewController class I usually put this line in my viewDidLoad just for a reference when I need to grab my CoreData stored file. Hope this helps.
NSLog(@"FILE PATH :%@", NSTemporaryDirectory());
(Note: to go to the path, from the finder menu click on Go and type ~/Library to open hidden directory then in the Finder Window you can click on the path shown on your console.)
sudo apt-get install python3-pip
sudo pip3 install MODULE_NAME
Source: Shashank Bharadwaj's comment
The short answer applies only on newer systems. On some versions of Ubuntu the command is pip-3.2
:
sudo pip-3.2 install MODULE_NAME
If it doesn't work, this method should work for any Linux distro and supported version:
sudo apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py | sudo python3
sudo pip3 install MODULE_NAME
If you don't have curl
, use wget
. If you don't have sudo
, switch to root
. If pip3
symlink does not exists, check for something like pip-3.X
Much python packages require also the dev package, so install it too:
sudo apt-get install python3-dev
Sources:
python installing packages with pip
Pip latest install
Check also Tobu's answer if you want an even more upgraded version of Python.
I want to add that using a virtual environment is usually the preferred way to develop a python application, so @felixyan answer is probably the best in an ideal world. But if you really want to install that package globally, or if need to test / use it frequently without activating a virtual environment, I suppose installing it as a global package is the way to go.
Of course, if you want something as close to TortoiseSVN as possible, you could just use TortoiseGit.
you can get List value without using Type object.
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
I have tested it and it is working.
The following code should be useful to you.
String email;
check.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
checkEmail(email);
if (checkMail) {
System.out.println("Valid mail Id");
}
}
});
}
}
public static boolean checkEmail(String email) {
Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile("[a-zA-Z0-9+._%-+]{1,256}" + "@"
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
jQuery doesnt have a method to provide the md5 of a string. So you need to use some external script. There is a plugin called jQuery MD5. and it gives you number of methods to achieve md5. Few of those are
Create (hex-encoded) MD5 hash of a given string value:
var md5 = $.md5('value');
Create (hex-encoded) HMAC-MD5 hash of a given string value and key:
var md5 = $.md5('value', 'key');
Create raw MD5 hash of a given string value:
var md5 = $.md5('value', null, true);
Create raw HMAC-MD5 hash of a given string value and key:
var md5 = $.md5('value', 'key', true);
This might do what you want... Check the snippet here. jQuery MD5
$('#example').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../admin/ajax/loadtransajax.php",
"fnServerParams": function (aoData) {
// Initialize your variables here
// I have assign the textbox value for "text_min_val"
var min_val = $("#min").val(); //push to the aoData
aoData.push({name: "text_min_val", value:min_val});
},
"fnCreatedRow": function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'tr_' + aData[0]);
$(nRow).attr('name', 'tr_' + aData[0]);
$(nRow).attr('min', 'tr_' + aData[0]);
$(nRow).attr('max', 'tr_' + aData[0]);
}
});
In loadtransajax.php
you may receive the get value:
if ($_GET['text_min_val']){
$sWhere = "WHERE (";
$sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
$sWhere .= ')';
}
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
To augment Benjamin's answer with an example:
Find Carrots(With)Dip(Are)Yummy
Replace Bananas$1Mustard$2Gross
Result BananasWithMustardAreGross
Anything in the parentheses can be a regular expression.
Have no idea about gd2, but I have done a similar thing with gd and it was not that hard.
Go to http://www.php.net/ and search for things like
It's not as flashy as some of those other solution out there, but since you generate a picture it will work in all browsers. (except lynx... :-) )
/Johan
Update: I nearly forgot, don't use jpeg for this type of pictures. The jpeg artefacts will be really annoying, png is a better solution.
The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.
The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.
Maybe SP2012 release will adrress this...
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
You can negate a time.Duration
:
then := now.Add(- dur)
You can even compare a time.Duration
against 0
:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
You can see a working example at http://play.golang.org/p/ml7svlL4eW
If you are on windows, you can use PeekConsoleInput to detect if there's any input,
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput( handle, &buffer, 1, &events );
then use ReadConsoleInput to "consume" the input character ..
PeekConsoleInput(handle, &buffer, 1, &events);
if(events > 0)
{
ReadConsoleInput(handle, &buffer, 1, &events);
return buffer.Event.KeyEvent.wVirtualKeyCode;
}
else return 0
to be honest this is from some old code I have, so you have to fiddle a bit with it.
The cool thing though is that it reads input without prompting for anything, so the characters are not displayed at all.
Abusive one-liner!
Array.from(fd).reduce((obj, [k, v]) => ({...obj, [k]: v}), {});
Today I learned firefox has object spread support and array destructuring!
exp(x) = e^x where e= 2.718281(approx)
import numpy as np
ar=np.array([1,2,3])
ar=np.exp(ar)
print ar
outputs:
[ 2.71828183 7.3890561 20.08553692]
I'd say the minimum would be to
In Angular 5.12 and latest Angular CLI, do
ng generate service my-service -m app.module
outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
outfile.write( str(key) + '\t' + str(value) + '\n' )
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
ReverseString.java
public class ReverseString {
public static void main(String[] args) {
String str = "Ranga Reddy";
String revStr = reverseStr(str);
System.out.println(revStr);
}
// Way1 - Recursive
public static String reverseStr(String str) {
char arrStr[] = reverseString(0, str.toCharArray());
return new String(arrStr);
}
private static char[] reverseString(int charIndex, char[] arr) {
if (charIndex > arr.length - (charIndex+1)) {
return arr;
}
int startIndex = charIndex;
int endIndex = arr.length - (charIndex+1);
char temp = arr[startIndex];
arr[startIndex] = arr[endIndex];
arr[endIndex] = temp;
charIndex++;
return reverseString(charIndex++, arr);
}
// Way2
private static String strReverse(String str) {
char ch[] = new char[str.length()];
for (int i = str.length() - 1, j = 0; i >= 0; i--) {
ch[j++] = str.charAt(i);
}
return new String(ch);
}
}
The practical solution ...
Be aware that results are the integers one through seven.
(Not zero through six.)
let trivialDayStringsORDINAL = ["", "SUN","MON","TUE","WED","THU","FRI","SAT"]
// note that zero is not used
and then ...
let dow = Calendar.current.component(.weekday, from: someDate)
print( trivialDayStringsORDINAL[dow] )
In C# 7.1 you will be able to do a proper async Main. The appropriate signatures for Main
method has been extended to:
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
For e.g. you could be doing:
static async Task Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
At compile time, the async entry point method will be translated to call GetAwaitor().GetResult()
.
Details: https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main
EDIT:
To enable C# 7.1 language features, you need to right-click on the project and click "Properties" then go to the "Build" tab. There, click the advanced button at the bottom:
From the language version drop-down menu, select "7.1" (or any higher value):
The default is "latest major version" which would evaluate (at the time of this writing) to C# 7.0, which does not support async main in console apps.
You are encountering a problem because you cannot construct the ArrayList
and populate it at the same time. You either need to create it and then manually populate it as such:
ArrayList list = new ArrayList<Double>();
list.add(1.38);
...
Or, alternatively if it is more convenient for you, you can populate the ArrayList
from a primitive array containing your values. For example:
Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
Here, resource means the 'id' of the Layout you are using while instantiating the view.
Now, this layout has many child views with their own ids. So, textViewResourceId
tells which child view we need to populate with the data.
I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.
sudo apt-get install openjfx
To do this using numpy, ie, if you have an array, a
, instead of list_a
:
a = np.array([1, 2, 4, 6])
my_filter = np.array([True, False, True, False], dtype=bool)
a[my_filter]
> array([1, 4])
I would suggest using following
req.param('<param_name>')
req.param("") works as following
Lookup is performed in the following order:
req.params
req.body
req.query
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like
Dim copyRange2 As Range
Dim copyRange3 As Range
Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)
copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")
put these near the other codings that are the same you can easily change the Ranges as you need.
I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.
I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.
In my case it was stupid missing of @OneToOne annotation, i set @MapsId without it
The read
method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct
module: http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Note that unpack
always returns a tuple, so struct.unpack('i', fin.read(4))[0]
gives the integer value that you are after.
You should probably use the format string '<i'
(< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.
There isn't any built-in way to handle this (although actionpack might have a helper for that). I would advise something like this
def to_boolean(s)
s and !!s.match(/^(true|t|yes|y|1)$/i)
end
# or (as Pavling pointed out)
def to_boolean(s)
!!(s =~ /^(true|t|yes|y|1)$/i)
end
What works as well is to use 0 and non-0 instead of false/true literals:
def to_boolean(s)
!s.to_i.zero?
end
I had this error with VS 2015, in my case going to the project properties page, Web tab, and clicking on Create Virtual Directory
button in Servers section solved it
Just by one line-
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text);
Output: ["text1", "text2"]
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.value);
Output: ["value1", "value2"]
If you use .join()
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text).join();
Output: text1,text2,text3
I would recommend that you use the following code in CSS:
text-transform:uppercase;
Make sure you put it in your class.
os.Mkdir
is used to create a single directory. To create a folder path, instead try using:
os.MkdirAll(folderPath, os.ModePerm)
func MkdirAll(path string, perm FileMode) error
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
Edit:
Updated to correctly use os.ModePerm
instead.
For concatenation of file paths, use package path/filepath
as described in @Chris' answer.
Yep, you'll want to do something like this:
echo -n "Enter Fullname: "
read fullname
Another option would be to have them supply this information on the command line. Getopts is your best bet there.
Using getopts in bash shell script to get long and short command line options
as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir
Use the Office FileDialog
object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library
and look in the help. This is much better than having people enter full paths.
Here is an example using msoFileDialogFilePicker
to allow the user to choose multiple files. You could also use msoFileDialogOpen
.
'Note: this is Excel VBA code
Public Sub LogReader()
Dim Pos As Long
Dim Dialog As Office.FileDialog
Set Dialog = Application.FileDialog(msoFileDialogFilePicker)
With Dialog
.AllowMultiSelect = True
.ButtonName = "C&onvert"
.Filters.Clear
.Filters.Add "Log Files", "*.log", 1
.Title = "Convert Logs to Excel Files"
.InitialFileName = "C:\InitialPath\"
.InitialView = msoFileDialogViewList
If .Show Then
For Pos = 1 To .SelectedItems.Count
LogRead .SelectedItems.Item(Pos) ' process each file
Next
End If
End With
End Sub
There are lots of options, so you'll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you'll need to find the correct help for the version you're using).
I use following templates for Android development:
Verbose (Logv)
Log.v(TAG, ${word_selection}${});${cursor}
Debug (Logd)
Log.d(TAG, ${word_selection}${});${cursor}
Info (Logi)
Log.i(TAG, ${word_selection}${});${cursor}
Warn (Logw)
Log.w(TAG, ${word_selection}${});${cursor}
Error (Loge)
Log.e(TAG, ${word_selection}${});${cursor}
Assert (Loga)
Log.a(TAG, ${word_selection}${});${cursor}
TAG is a Constant I define in every activity.
strip()
is a method for strings, you are calling it on a list
, hence the error.
>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False
To do what you want, just do
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
Since, you want the elements to be in a single list (and not a list of lists), you have two options.
To do the first, follow the code:
>>> l1 = []
>>> for elem in l:
l1.extend(elem.strip().split(';'))
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
To do the second, use itertools.chain
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
pad
In order to move the colorbar relative to the subplot, one may use the pad
argument to fig.colorbar
.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()
One can use an instance of make_axes_locatable
to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad
argument would allow to set the space between the two axes.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios
as gridspec_kw={"height_ratios":[1, 0.05]}
in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4),
gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
Based on my tests (Win7 64bit, 6GB RAM, Java6), NIO transferFrom is fast only with small files and becomes very slow on larger files. NIO databuffer flip always outperforms standard IO.
Copying 1000x2MB
Copying 100x20mb
Copying 1x1000mb
The transferTo() method works on chunks of a file; wasn't intended as a high-level file copy method: How to copy a large file in Windows XP?
The answer probably depends on what format your date is in, but here is an example using the Date
class:
dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")
You can even play with different units like weeks.
I think he wants to replace a class name.
Something like this would work:
$(document).ready(function(){
$('.blue').removeClass('blue').addClass('green');
});
from http://monstertut.com/2012/06/use-jquery-to-change-css-class/
This is not exactly showing you which rows are locked, but this may helpful to you.
You can check which statements are blocked by running this:
select cmd,* from sys.sysprocesses
where blocked > 0
It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.
Edit to add comment from @MikeBlandford:
The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.
You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.
An alternate solution is to use the keyword continue
in combination with break
, i.e.:
for (;;) {
switch(msg->state) {
case MSGTYPE:
// code
continue; // continue with loop
case DONE:
break;
}
break;
}
Use the continue
statement to finish each case label where you want the loop to continue and use the break
statement to finish case labels that should terminate the loop.
Of course this solution only works if there is no additional code to execute after the switch statement.
You could also build out a new Gemfile and run bundle clean --force
. This will remove all other gems that aren't included in the new Gemfile.
Use npm run[-script] <script name>
After using npm to install the bin package to your local ./node_modules
directory, modify package.json
to add <script name>
like this:
$ npm install --save learnyounode
$ edit packages.json
>>> in packages.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"learnyounode": "learnyounode"
},
...
$ npm run learnyounode
It would be nice if npm install had a --add-script option or something or if npm run would work without adding to the scripts block.
Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake
You could use PIL to create (and display) an image:
from PIL import Image
import numpy as np
w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()
Use the built-in VBA function Val, if the numbers are at the front end of the string:
Dim str as String
Dim lng as Long
str = "1 149 xyz"
lng = Val(str)
lng = 1149
#include <cstdio>
#include <cstdlib>
#include <string>
void strrev(char *str)
{
if( str == NULL )
return;
char *end_ptr = &str[strlen(str) - 1];
char temp;
while( end_ptr > str )
{
temp = *str;
*str++ = *end_ptr;
*end_ptr-- = temp;
}
}
int main(int argc, char *argv[])
{
char buffer[32];
strcpy(buffer, "testing");
strrev(buffer);
printf("%s\n", buffer);
strcpy(buffer, "a");
strrev(buffer);
printf("%s\n", buffer);
strcpy(buffer, "abc");
strrev(buffer);
printf("%s\n", buffer);
strcpy(buffer, "");
strrev(buffer);
printf("%s\n", buffer);
strrev(NULL);
return 0;
}
This code produces this output:
gnitset
a
cba
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())
Suppose you have a which is an array. to get the dimensions of an array you should use shape.
import numpy as np
a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape
The output of this will be (4,3)
Swift 4, 4.2 and 5
Remove space from front and end only
let str = " Akbar Code "
let trimmedString = str.trimmingCharacters(in: .whitespacesAndNewlines)
Remove spaces from every where in the string
let stringWithSpaces = " The Akbar khan code "
let stringWithoutSpaces = stringWithSpaces.replacingOccurrences(of: " ", with: "")
The default/updated configuration/data of the widgets is set to automatically bind to an associated DataSource.
$('#GridId').data('kendoGrid').dataSource.read();
$('#GridId').data('kendoGrid').refresh();
The easiest and quickest way I can think of would be to use sp_help
sp_help 'TableName'
As other users explained here about the usage of allowoveride directive, which is used to give permission to .htaccess usage. one thing I want to point out that never use allowoverride all if other users have access to write .htaccess instead use allowoveride as to permit certain modules.
Such as AllowOverride AuthConfig mod_rewrite
Instead of
AllowOverride All
Because module like mod_mime can render your server side files as plain text.
If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.
Replace:
stdin.read(1)
with
stdin.readline().strip()[:1]
This will read a line, remove spaces and newlines and just keep the first character.
Replace the username and password with Integrated Security=SSPI;
So the connection string should be
<connectionStrings>
<add name="NorthwindContex"
connectionString="data source=localhost;
initial catalog=northwind;persist security info=True;
Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.
Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement
namespace, you could also do it programmatically:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.
Or:
UserPrincipal myself = UserPrincipal.Current;
This will give you a UserPrincipal
object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!
Button click event only.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnext").click(function () {
window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
});
</script>
Can an interface extend multiple interfaces in java?
Answer is: Yes.
According to JLS
An interface may be declared to be a direct extension of one or more other interfaces, meaning that it implicitly specifies all the member types, abstract methods, and constants of the interfaces it extends, except for any member types and constants that it may hide.
Get the current URL including the query string.
echo url()->full();
You could use the following style with opacity
input[disabled="disabled"], select[disabled="disabled"], textarea[disabled="disabled"] {
opacity: 0.85 !important;
}
or a specific CSS class
.ui-state-disabled{
opacity: 0.85 !important;
}
My guess is that part of your problem is the parameter lists not matching.
int (* length)();
and
int length(PString * self)
are not the same. It should be int (* length)(PString *);
.
...woah, it's Jon!
Edit: and, as mentioned below, your struct pointer is never set to point to anything. The way you're doing it would only work if you were declaring a plain struct, not a pointer.
str = (PString *)malloc(sizeof(PString));
If you don't remember the password you set for root and need to reset it, follow these steps:
sudo mysqld_safe --skip-grant-tables;
mysql -u root
For MySQL older than MySQL 5.7 use:
UPDATE mysql.user SET Password=PASSWORD('your-password') WHERE User='root';
For MySQL 5.7+ use:
USE mysql;
UPDATE mysql.user SET authentication_string=PASSWORD("your-password") WHERE User='root';
Refresh and quit:
FLUSH PRIVILEGES;
\q
you can use Realm or Sqlite if you want to manage complex data type.
Otherwise go with inbuilt react native asynstorage
Try this:
reverse = 0;
remainder = 0;
count = 0;
while (number > reverse)
{
remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number / 10;
count++;
}
Console.WriteLine(count);
if (reverse == number)
{
Console.WriteLine("Your number is a palindrome");
}
else
{
number = number * 10 + remainder;
if (reverse == number)
Console.WriteLine("your number is a palindrome");
else
Console.WriteLine("your number is not a palindrome");
}
Console.ReadLine();
}
}
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
%lld
is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d
So try this:
if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);
and
scanf("%I64d", &n);
The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>
.
In your case, it would look like this:
scanf("%"SCNd64"", &n);
//...
if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);
It really is very ugly... but at least it is portable.
It is only possible if you are able to send custom server-side response headers with the static content.
For a more detailed explanation see my answer here: Set P3P code in HTML
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
On Mac:
Install easy_install
curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python
Install pip
sudo easy_install pip
Now, you could install external modules. For example
pip install regex # This is only an example for installing other modules
Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.
OK then. These two are the ones I used:
and then there is always Eclipse.
*UPDATE 20 March 2013 *
Well, Sublime Text 2 is the one to heavily consider. Heavily.
Or just simply add a span
tag with the height of the fixed header set as its height then insert it next to the sticky header:
$(function() {
var $span_height = $('.fixed-header').height;
var $span_tag = '<span style="display:block; height:' + $span_height + 'px"></span>';
$('.fixed-header').after($span_tag);
});
If you are specifically looking for getting the difference between two files, then this might help:
with open('first_file', 'r') as file1:
with open('second_file', 'r') as file2:
difference = set(file1).difference(file2)
difference.discard('\n')
with open('diff.txt', 'w') as file_out:
for line in difference:
file_out.write(line)
I managed to copy text to the clipboard (without showing any text boxes) by adding a hidden input
element to body
, i.e.:
function copy(txt){_x000D_
var cb = document.getElementById("cb");_x000D_
cb.value = txt;_x000D_
cb.style.display='block';_x000D_
cb.select();_x000D_
document.execCommand('copy');_x000D_
cb.style.display='none';_x000D_
}
_x000D_
<button onclick="copy('Hello Clipboard!')"> copy </button>_x000D_
<input id="cb" type="text" hidden>
_x000D_
It indicates that you are using a decorator. Here is Bruce Eckel's example from 2008.
phpMyAdmin can handle CSV import. Here are the steps:
Prepare the CSV file to have the fields in the same order as the MySQL table fields.
Remove the header row from the CSV (if any), so that only the data is in the file.
Go to the phpMyAdmin interface.
Select the table in the left menu.
Click the import button at the top.
Browse to the CSV file.
Select the option "CSV using LOAD DATA".
Enter "," in the "fields terminated by".
Enter the column names in the same order as they are in the database table.
Click the go button and you are done.
This is a note that I prepared for my future use, and sharing here if someone else can benefit.
From Apple documentation:
Guard Statement
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
Synatx:
guard condition else {
statements
}
Advantage:
1. By using guard
statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.
2. It was designed specifically for exiting a method or function early.
if you use if let below is the code how it looks.
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error == nil {
if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
if let data = data {
//Process Data Here.
print("Data: \(data)")
} else {
print("No data was returned by the request!")
}
} else {
print("Your request returned a status code other than 2XX!")
}
} else {
print("Error Info: \(error.debugDescription)")
}
}
task.resume()
Using guard you can transfer control out of a scope if one or more conditions aren't met.
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
/* GUARD: was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
print("Your request returned a status code other than 2XX!")
return
}
/* GUARD: was there any data returned? */
guard let data = data else {
print("No data was returned by the request!")
return
}
//Process Data Here.
print("Data: \(data)")
}
task.resume()
Reference:
1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement
@foreach (var m in Model)
{
<img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
}
All of these answers are wrong! Do not use InsecureSkipVerify
to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName
on tls.Config
. If tls.Config.ServerName
== remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify
means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.
There is one legitimate use for InsecureSkipVerify
: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify
, it's generally because you didn't set ServerName
properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).
In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify
, or you will learn what is wrong with it the hard way!
For Expose.class Error i.e
java.util.zip.ZipException: duplicate entry: com/google/gson/annotations/Expose.class
use the below code
configurations {
all*.exclude module: 'gson'
}
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
If you already have a JavaScript function called showImage
defined to show the image, you can link as such:
<a href="javascript:showImage()">show image</a>
If you need help defining the function, I would try:
function showImage() {
var img = document.getElementById('myImageId');
img.style.visibility = 'visible';
}
Or, better yet,
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
Then, your links would be:
<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>
If you want to tag the branch you are in, then type:
git tag <tag>
and push the branch with:
git push origin --tags
As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)
We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that
HTTP/1.1 implementations MAY ignore ranges specified using other units.
Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.
This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)
Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:
If all of the preconditions are true, the server supports the Range
header field for the target resource, and the specified range(s) are
valid and satisfiable (as defined in Section 2.1), the server SHOULD
send a 206 (Partial Content) response with a payload containing one
or more partial representations that correspond to the satisfiable
ranges requested, as defined in Section 4.
So, as a result, we would have the following HTTP header fields:
For Partial Content:
206 Partial Content
Accept-Ranges: members
Content-Range: members 0-20/100
For full Content:
200 OK
Accept-Ranges: members
Content-Range: members 0-20/20
function test(a) {_x000D_
var x = (a.value || a.options[a.selectedIndex].value); //crossbrowser solution =)_x000D_
alert(x);_x000D_
}
_x000D_
<select onchange="test(this)" id="select_id">_x000D_
<option value="0">-Select-</option>_x000D_
<option value="1">Communication</option>_x000D_
<option value="2">Communication</option>_x000D_
<option value="3">Communication</option>_x000D_
</select>
_x000D_
Another vote for if/else. I'm not a huge fan of case or switch statements because there are some people that don't use them. The code is less readable if you use case or switch. Maybe not less readable to you, but to those that have never needed to use the command.
The same goes for object factories.
If/else blocks are a simple construct that everyone gets. There's a few things you can do to make sure that you don't cause problems.
Firstly - Don't try and indent if statements more than a couple of times. If you're finding yourself indenting, then you're doing it wrong.
if a = 1 then
do something else
if a = 2 then
do something else
else
if a = 3 then
do the last thing
endif
endif
endif
Is really bad - do this instead.
if a = 1 then
do something
endif
if a = 2 then
do something else
endif
if a = 3 then
do something more
endif
Optimisation be damned. It doesn't make that much of a difference to the speed of your code.
Secondly, I'm not averse to breaking out of an If Block as long as there are enough breaks statements scattered through the particular code block to make it obvious
procedure processA(a:int)
if a = 1 then
do something
procedure_return
endif
if a = 2 then
do something else
procedure_return
endif
if a = 3 then
do something more
procedure_return
endif
end_procedure
EDIT: On Switch and why I think it's hard to grok:
Here's an example of a switch statement...
private void doLog(LogLevel logLevel, String msg) {
String prefix;
switch (logLevel) {
case INFO:
prefix = "INFO";
break;
case WARN:
prefix = "WARN";
break;
case ERROR:
prefix = "ERROR";
break;
default:
throw new RuntimeException("Oops, forgot to add stuff on new enum constant");
}
System.out.println(String.format("%s: %s", prefix, msg));
}
For me the issue here is that the normal control structures which apply in C like languages have been completely broken. There's a general rule that if you want to place more than one line of code inside a control structure, you use braces or a begin/end statement.
e.g.
for i from 1 to 1000 {statement1; statement2}
if something=false then {statement1; statement2}
while isOKtoLoop {statement1; statement2}
For me (and you can correct me if I'm wrong), the Case statement throws this rule out of the window. A conditionally executed block of code is not placed inside a begin/end structure. Because of this, I believe that Case is conceptually different enough to not be used.
Hope that answers your questions.
Here is a new one (Note: in Tech Preview stage): http://www.dot42.com
It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.
Disclosure: I work for this company
UPDATE: all sources are now on https://github.com/dot42
List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;
The implicit conversion failes because List<>
implements IList
, not viceversa. So you can say IList<T> foo = new List<T>()
, but not List<T> foo = (some IList-returning method or property)
.
in header
using System.Configuration;
in code
SqlConnection conn = new SqlConnection(*ConfigurationManager.ConnectionStrings["connstrname"].ConnectionString*);
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
Here is a way to do it in the shell:
FIELD=2
cut -f $FIELD * | sort| uniq -c |sort -nr
This is the sort of thing bash is great at.
At the VS code
press Ctrl+Shift+P
then type Format Document With...
At the end of the list click on Configure Default Formatter...
Now you can choose your favorite beautifier from the list.
Update 2021
if "Format Document With..."
didn't exist any more, go to file
=> preferences
=> settings
then navigate to Extensions
=> Vetur
scroll a little bit then you will see format > defaultFormatter:css
, now you can pick any document formatter that you installed bofer for different file type extensions.
You can jump through hoops and convert your solution to a lapply
, sapply
or apply
call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.
If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo
package as it handles ordered data like this very well indeed.
require(zoo)
set.seed(1)
## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it
plot(datz)
Which gives:
Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.
Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.
To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.
It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.
I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.
It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!
This is suggested by the github help page:
clip < filename
this copies the contents of filename to the clipboard and is useful for doing things like copying your id_rsa.pub to a web form.
This is because of using integer indices (ix
selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).
*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:
df.iloc[-3:]
see the docs.
As Wes points out, in this specific case you should just use tail!
I've simply used this javascript code (using jquery but it's not strictly necessary) :
$( "#button" ).on( "click", function(event) {
$(this).attr('href', 'mailto:[email protected]?subject=hello');
});
When users click on the link, we replace the href attribute of the clicked element.
Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go
I think robots can't see it, the address is protected from spams.
For my first post/comment: We all know that 'touchstart' is triggered before click. We also know that when user open your page he or she will: 1) move the mouse 2) click 3) touch the screen (for scrolling, or ... :) )
Let's try something :
//--> Start: jQuery
var hasTouchCapabilities = 'ontouchstart' in window && (navigator.maxTouchPoints || navigator.msMaxTouchPoints);
var isTouchDevice = hasTouchCapabilities ? 'maybe':'nope';
//attach a once called event handler to window
$(window).one('touchstart mousemove click',function(e){
if ( isTouchDevice === 'maybe' && e.type === 'touchstart' )
isTouchDevice = 'yes';
});
//<-- End: jQuery
Have a nice day!
Here's the final code I [OP] used. Probably not best practice, but it worked.
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var breaks = text.split('\n');
var newLines = "";
for(var i = 0; i < breaks.length; i ++){
newLines = newLines + breaks[i] + ' breakLine ';
}
var words = newLines.split(' ');
var line = '';
console.log(words);
for(var n = 0; n < words.length; n++) {
if(words[n] != 'breakLine'){
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}else{
context.fillText(line, x, y);
line = '';
y += lineHeight;
}
}
context.fillText(line, x, y);
}
Maybe you can write a function as follows:
var addParams = function(key, val, url) {
var arr = url.split('?');
if(arr.length == 1) {
return url + '?' + key + '=' + val;
}
else if(arr.length == 2) {
var params = arr[1].split('&');
var p = {};
var a = [];
var strarr = [];
$.each(params, function(index, element) {
a = element.split('=');
p[a[0]] = a[1];
})
p[key] = val;
for(var o in p) {
strarr.push(o + '=' + p[o]);
}
var str = strarr.join('&');
return(arr[0] + '?' + str);
}
}
Probably one of the indexes is wrong, either the inner one or the outer one.
I suspect you mean to say [0]
where you say [1]
and [1]
where you say [2]
. Indexes are 0-based in Python.
If you want to select last numbers of rows from a table.
Syntax will be like
select * from table_name except select top
(numbers of rows - how many rows you want)* from table_name
These statements work but differrent ways. thank you guys.
select * from Products except select top (77-10) * from Products
in this way you can get last 10 rows but order will show descnding way
select top 10 * from products
order by productId desc
select * from products
where productid in (select top 10 productID from products)
order by productID desc
select * from products where productID not in
(select top((select COUNT(*) from products ) -10 )productID from products)
The UserManager did not work, and As @Kevin Junghans wrote,
UpdateAsync just commits the update to the context, you still need to save the context for it to commit to the database
Here is quick solution (prior to new features in ASP.net identity v2) I used in a web forms projetc. The
class AspNetUser :IdentityUser
Was migrated from SqlServerMembership aspnet_Users. And the context is defined:
public partial class MyContext : IdentityDbContext<AspNetUser>
I apologize for the reflection and synchronous code--if you put this in an async method, use await
for the async calls and remove the Tasks and Wait()s. The arg, props, contains the names of properties to update.
public static void UpdateAspNetUser(AspNetUser user, string[] props)
{
MyContext context = new MyContext();
UserStore<AspNetUser> store = new UserStore<AspNetUser>(context);
Task<AspNetUser> cUser = store.FindByIdAsync(user.Id);
cUser.Wait();
AspNetUser oldUser = cUser.Result;
foreach (var prop in props)
{
PropertyInfo pi = typeof(AspNetUser).GetProperty(prop);
var val = pi.GetValue(user);
pi.SetValue(oldUser, val);
}
Task task = store.UpdateAsync(oldUser);
task.Wait();
context.SaveChanges();
}
if ( $('#whatever')[0] ) {...}
The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Try to use:
mvn jacoco:report -debug
to see the details about your reporting process.
I configured my jacoco like this:
<configuration>
<dataFile>~/jacoco.exec</dataFile>
<outputDirectory>~/jacoco</outputDirectory>
</configuration>
Then mvn jacoco:report -debug
shows it using the default configuration, which means jacoco.exec
is not in ~/jacoco.exec
. The error says missing execution data file
.
So just use the default configuration:
<execution>
<id>default-report</id>
<goals>
</goals>
<configuration>
<dataFile>${project.build.directory}/jacoco.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
And everything works fine.
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
@Daniel's suggestion worked perfectly for me. To install
make, open Xcode, go to Preferences -> Downloads -> Components -> Command Line Tools.You can then test with
gcc -v
if you are using docker you have to do the following steps:
copy the file from hdfs to namenode (hadoop fs -get output/part-r-00000 /out_text). "/out_text" will be stored on the namenode.
copy the file from namenode to local disk by (docker cp namenode:/out_text output.txt)
output.txt will be there on your current working directory
try
var lst= (from char c in source select c.ToString()).ToList();
For a box that appears in the center - horizontal & vertical - I got this to work with just one LinearLayout. The answer from Viswanath L was very helpful
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/layout_bg"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:id="@+id/dialog_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="Error"
android:textColor="#000" />
<TextView
android:id="@+id/message_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="Error-Message"
android:textColor="#000" />
<Button
android:id="@+id/dialogButtonOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/message_text"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:text="Ok" />
</LinearLayout>
Why not just INNER JOIN the table with itself?
SELECT a.firstname, a.lastname, a.address
FROM list a
INNER JOIN list b ON a.address = b.address
WHERE a.id <> b.id
A DISTINCT is needed if the address could exist more than two times.
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
git clone ssh://[email protected]:[port]/gitolite-admin
Note that the port number should be there without the square brackets: []
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
If you want the entire package name with it, call:
String name = MyClass.class.getCanonicalName();
If you only want the last element, call:
String name = MyClass.class.getSimpleName();
You want to restrict to input fields that are of type text so use the selector input[type=text]
rather than input
(which will apply to all input fields (e.g. those of type submit as well)).
Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.
I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.
Instant.now()
.toString()
2016-05-06T23:24:25.694Z
ZonedDateTime
.now
(
ZoneId.of( "America/Montreal" )
)
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19:24:25.694
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z
at the end is short for Zulu
, and means UTC.
An Instant
represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T
in the middle with a space, and the Z
with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
Main Class:
public class AndroidLocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(
AndroidLocationActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AndroidLocationActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog.setMessage(provider
+ " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AndroidLocationActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Next Class:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Don't forget to add in your manifest.
<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />
If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.
scp user@host:/path/file /localpath/file
Wild card characters are supported, so
scp user@host:/path/folder/* /localpath/folder
will copy all of the remote files in that folder.If copying more then one directory.
note -r will copy all sub-folders and content too.
class Solve:
def __init__(self,w,d):
self.value=w
self.unit=d
def __str__(self):
return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)
output: my speed is 21 kmh
Found this on a different forum
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
What you are doing is passing 664
which in octal is 1230
In your case you would need
os.chmod("/tmp/test_file", 436)
[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666
You can use the setspace package which gives you spacing environments, e.g.:
\documentclass{article}
\usepackage{setspace}
\begin{document}
\doublespace
my line of text blah blah blah
new line of text with blank line between
\end{document}
Or use a verbatim
environment to control the layout of your code precisely.
Here's my code Example for if..else..if
which do the following
Prompt user for Process Name
If the process name is invalid
Then it's write to user
Error : The Processor above doesn't seem to be exist
if the process name is services
Then it's write to user
Error : You can't kill the Processor above
if the process name is valid and not services
Then it's write to user
the process has been killed via taskill
so i called it Process killer.bat
Here's my Code:
@echo off
:Start
Rem preparing the batch
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%
:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid
Cls
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist
) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls
Color 0c
Title Permission denied
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above
) else (
REM if the process name is valid and not services
Cls
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)
pause>nul
REM If else if Template
REM if thing1 (
REM Command here 2 !
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )
I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: color 0.3s linear;
-webkit-transition: color 0.3s linear;
-moz-transition: color 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the above code!
Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: all 0.3s linear;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
padding-left: 10px;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the "all" example!
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"
I would suggest the following code, you can use this <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
to get the latitude and longitude of a location, although it may not be so accurate however it worked for me;
code snippet below
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript's Geolocation API</title>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
var lat = geoip_latitude();
var long = geoip_longitude();
document.write("Latitude: "+lat+"</br>Longitude: "+long);
</script>
</body>
</html>
Select the block of code that you want indented.
Right-click (or, on Mac, Ctrl-click).
Structure → Re-indent
For users coming back to this post long after the initial answer was accepted, it may pay off to note that now you can use
data-fancybox-href="#"
on any element (since data is an HTML-5 accepted attribute) to have the fancybox work on say an input form if for some reason you can't use the options to initiate for some reason (like say you have multiple elements on the page that use fancybox and they all share a similar class you call fancybox on).
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25