The Version 56.0.2924.87 which I am in now, Undocks the DevTools automatically if you are NOT in a desktop. Otherwise Open a NEW new Chrome tab and Inspect to Dock the DevTools back into the window.
Another great solution to debug the Network calls before redirecting to other pages is to select the beforeunload
event break point
This way you assure to break the flow right before it redirecting it to another page, this way all network calls, network data and console logs are still there.
This solution is best when you want to check what is the response of the calls
P.S: You can also use XHR break points if you want to stop right before a specific call or any call (see image example)
Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.
You can always clear a specific file by doing the following:
If not:
This is very handy if you have resources that are in frames and CTRL+F5
is not force refreshing them.
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
New versions of Chrome have a feature called workspaces which addresses this issue. You can define which paths on your webserver correspond to which paths on your system, then edit and save with just ctrl-s.
See: http://www.html5rocks.com/en/tutorials/developertools/revolutions2013/
Try to see if it works in Incognito Mode. If it does, then it's a bug in recent Chrome. On my computer the following fix worked:
I know that what I do is quite the workaround, however it works perfectly and that is the way I do it everytime.
Then, proceed like this:
Cheers!
In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.
I haven't tried it, but iOS WebKit debug proxy (ios_webkit_debug_proxy / iwdp) supposedly lets you remotely debug UIWebView. From the README.md
The ios_webkit_debug_proxy (aka iwdp) allows developers to inspect MobileSafari and UIWebViews on real and simulated iOS devices via the Chrome DevTools UI and Chrome Remote Debugging Protocol. DevTools requests are translated into Apple's Remote Web Inspector service calls.
Just adding this here for reference, I was trying to connect an LG G5 Android phone and Chrome dev tools did not recognize it until I downloaded the LG usb driver here.
Good luck, all!
For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:
While the browser is open, press F12 to access Web Developer tools
When opened, click the "Network" option
Initially, it is possible the page data is not present/up to date. Refresh the page if necessary
Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)
Step over the next function(F10)
button beside Resume(F8)
in the upper top center of the chrome until you freeze the popup you want to see. There is some cases when you copy and paste the CSS code in somewhere and it breaks the format so Chrome show the yellow warning. You should try to reformat the CSS code again and it should be fine.
Yep,there is a way you could do it
Right click->Inspect->sources(tab)
Towards Your right there will be a "pause script execution button"
I hope it helps!Peace
I ran this issue when I tried to load main.js for require js for the second time after I made changes as a result from error . I just turned on in Developer Tools Settings "Disable Cache (When DevTools is Open)" . and that did the charm.
To chain CSS3 styles which spans across multiple lines, you can do like this,
var styles = [
'background: linear-gradient(#D33106, #571402)'
, 'border: 1px solid #3E0E02'
, 'color: white'
, 'display: block'
, 'text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3)'
, 'box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4) inset, 0 5px 3px -5px rgba(0, 0, 0, 0.5), 0 -13px 5px -10px rgba(255, 255, 255, 0.4) inset'
, 'line-height: 40px'
, 'text-align: center'
, 'font-weight: bold'
].join(';');
console.log('%c a spicy log message ?', styles);
Result
Find more :- https://coderwall.com/p/fskzdw/colorful-console-log
Cheers.
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
I located the Facebook's console buster script using Chrome developer tools. Here is the script with minor changes for readability. I have removed the bits that I could not understand:
Object.defineProperty(window, "console", {
value: console,
writable: false,
configurable: false
});
var i = 0;
function showWarningAndThrow() {
if (!i) {
setTimeout(function () {
console.log("%cWarning message", "font: 2em sans-serif; color: yellow; background-color: red;");
}, 1);
i = 1;
}
throw "Console is disabled";
}
var l, n = {
set: function (o) {
l = o;
},
get: function () {
showWarningAndThrow();
return l;
}
};
Object.defineProperty(console, "_commandLineAPI", n);
Object.defineProperty(console, "__commandLineAPI", n);
With this, the console auto-complete fails silently while statements typed in console will fail to execute (the exception will be logged).
References:
You can remove the 404 by removing the line
//@ sourceMappingURL=jquery-1.10.2.min.map
from the top part of your jQuery file.
The top part of the jQuery file will look like this.
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/
Just change that to
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license */
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files. (Read more on this here)
Under Chrome v51 on a Mac, I found the rendering settings by clicking in the upper right corner, choosing More tools > Rendering settings and checking the Emulate media button in the options offered at the bottom of the window.
Thank you to all the other posters that led me to this, and credit to those that provided the answer without the images.
Since the Fetch API is supported by Chrome (and most other browsers), it is now quite easy to make HTTP requests from the devtools console.
To GET a JSON file for instance:
fetch('https://jsonplaceholder.typicode.com/posts/1')_x000D_
.then(res => res.json())_x000D_
.then(console.log)
_x000D_
Or to POST a new resource:
fetch('https://jsonplaceholder.typicode.com/posts', {_x000D_
method: 'POST',_x000D_
body: JSON.stringify({_x000D_
title: 'foo',_x000D_
body: 'bar',_x000D_
userId: 1_x000D_
}),_x000D_
headers: {_x000D_
'Content-type': 'application/json; charset=UTF-8'_x000D_
}_x000D_
})_x000D_
.then(res => res.json())_x000D_
.then(console.log)
_x000D_
Chrome Devtools actually also support new async/await syntax (even though await normally only can be used within an async function):
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
console.log(await response.json())
Notice that your requests will be subject to the same-origin policy, just like any other HTTP-request in the browser, so either avoid cross-origin requests, or make sure the server sets CORS-headers that allow your request.
Using a plugin (old answer)
As an addition to previously posted suggestions I've found the Postman plugin for Chrome to work very well. It allow you to set headers and URL parameters, use HTTP authentication, save request you execute frequently and so on.
Use dataType: "jsonp"
. I had the same error before. It fixed for me.
This comes from the official site of Chome-devtools and it helps. Here i quote:
- Queuing If a request is queued it indicated that:
- The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
- The request was put on hold to wait for an unavailable TCP socket that's about to free up.
- The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
- Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.
Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.
Consider a more pragmatic approach to the question of "doing it correctly".
console.log("about to bind scroll fx");
$(window).scroll(function() {
console.log("scroll bound, loop through div's");
$('div').each(function(){
If both of those log
s output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:
var id='#'+$(this).attr('id');
console.log(id);
var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());
By doing this, at least during debugging, you may find that the var id
is undefined, causing errors throughout the rest of the code. Is it possible some of your div
tags do not have id's?
Right-click, then "Open link in new tab"
edit : you can also double-click, it has the same effect
For jQuery (at least version 1.11.2) the following procedure worked for me.
$._data(($0), 'events');
in the 'Console'handler:
value.And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)
...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...
For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:
When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.
More info:
Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
Try adding this to your source:
debugger;
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.
David Walsh has a nice solution for this. Here is my take on this, combining his solution with what has been discovered on this thread as well.
https://davidwalsh.name/global-variables-javascript
x = {};
var iframe = document.createElement('iframe');
iframe.onload = function() {
var standardGlobals = Object.keys(iframe.contentWindow);
for(var b in window) {
const prop = window[b];
if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) {
x[b] = prop;
}
}
console.log(x)
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
x
now has only the globals.
Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)
A tool with a single solution for this I'm unaware of, but you can use Firebug and Web Developer extension at the same time.
Use Firebug to copy the html section you need (Inspect Element) and Web Developer to see which css is associated with an element (Calling Web Developer "View Style Information" - it works like Firebug's "Inspect Element", but instead of showing the html markup it shows the associated CSS with that markup).
It's not exactly what you want (one click for everything), but it's pretty close, and at least intuitive.
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
Alexander Pavlov's answer gets the closest to what you want.
Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.
You were close on this one.
Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:
Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.
I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.
Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:
// ...snip...
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// ...snip...
The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.
Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.
If you want to temporarily get rid of these console errors (like I did) you can install the extension here: https://chrome.google.com/webstore/detail/google-cast/boadgeojelhgndaghljhdicfkmllpafd/reviews?hl=en
I left a review asking for a fix. You can also do a bug report via the extension (after you install it) here. Instructions for doing so are here: https://support.google.com/chromecast/answer/3187017?hl=en
I hope Google gets on this. I need my console to show my errors, etc. Not theirs.
Search All Files with Control+Shift+F or Console->[Search tab]
NOTE: Global Search shows up next to the CONSOLE menu
node-debug -p 8888 scriptFileName.js
You have to click and hold until the other icon shows up, then slide the mouse down to the icon.
Let tell you a simple formula to find xpath of any element:
1- Open site in browser
2- Select element and right click on it
3- Click inspect element option
4- Right click on selected html
5- choose option to copy xpath Use it where ever you need it
This video link will be helpful for you. http://screencast.com/t/afXsaQXru
Note: For advance options of xpath you must know regex or pattern of your html.
One workaround is to use Postman with same request url, headers and payload.
It will give response for sure.
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
Click on the Settings icon and then click on the Restore defaults and reload button. This worked for me whereas the accepted answer didn't.
Yes, just open the "Source" Tab in the dev-tools and navigate to the script you want to change . Make your adjustments directly in the dev tools window and then hit ctrl+s to save the script - know the new js will be used until you refresh the whole page.
<html>
tag in Elements.<!DOCTYPE html>
before the <html>
.You can also run Chrome with JavaScript disabled by default by using the flag:
-disable-javascript
You would use this for example by running Chrome like this:
C:\Documents and Settings\%username%\Local Settings\Application Data\Google\Chrome" -disable-javascript
Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.
See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
There are many appropiate solution to this problem as mentioned above in this post, but i have found a small hack that can be inserrted in the script or pasted in the Chromes console (debugger) to achieve it:
jQuery(window).keydown(function(e) { if (e.keyCode == 123) debugger; });
This will cause execution to be paused when you hit F12
.
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
I found a solution that works, but it's ugly.
Click the three-dot menu and select "Remote devices" under the "More tools" menu:
In the panel that opens, select your device and then the "Inspect" button next to the name of the tab on your phone that needs to be refreshed:
In the window that opens, click the "Network" tab and check the "Disable cache" checkbox:
Reload the page on your phone or using the reload button in the DevTools window.
Note: if your phone doesn't appear in the device list:
- make sure the USB connection is using File Transfer mode and isn't simply charging
- try restarting ADB or run
adb devices
to see if the device is being detected
I suggest using JavaScript's Array method filter()
to identify an element by value. It filters data by using a "function to test each element of the array. Return true to keep the element, false otherwise.."
The following function filters the data, returning data for which the callback returns true
, i.e. where data.code
equals the requested country code.
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
See the demonstration below:
var data = [{_x000D_
"name": "Afghanistan",_x000D_
"code": "AF"_x000D_
}, {_x000D_
"name": "Åland Islands",_x000D_
"code": "AX"_x000D_
}, {_x000D_
"name": "Albania",_x000D_
"code": "AL"_x000D_
}, {_x000D_
"name": "Algeria",_x000D_
"code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
return data.filter(_x000D_
function(data) {_x000D_
return data.code == code_x000D_
}_x000D_
);_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
Use the powershell pipeline to get packages and remove in single statement like this
Get-Package | Uninstall-Package
if you want to uninstall selected packages follow these steps
GetPackages
to get the list of packages GetPackages
in NimbleText(For each row in the list window)(
if requiredUninstall-Package $0
(Substitute using pattern window)That be all folks.
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
You need to Enable security and set the security realm on the Configure Global Security page (see: Standard Security Setup) and choose the appropriate Authorization method (Security Realm).
Depending on your selection, create the user using appropriate method. Recommended method is to select Jenkins’ own user database and tick Allow users to sign up, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).
See also: Creating user in Jenkins via API
This is what worked for me:
In your build.gradle (project) write mavenCentral() in the buildscript{} and allprojects {}. It should look like this:
buildscript {
repositories {
jcenter()
**mavenCentral()**
}
//more code ...
}
allprojects {
repositories {
jcenter()
**mavenCentral()**
}
}
Then, in build.gradle(module) add in dependencies{} this snippet:
compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'
it should look like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
testCompile 'junit:junit:4.12'
**compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'**
}
Put your .gif image in your drawable folder. Now go to app > res > layout > activity_main.xml and add this snipped for your .gif:
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/YOUR_GIF_IMAGE"
android:background="#000000" //for black background
/>
And you're done :)
Helpful links: https://github.com/koral--/android-gif-drawable
https://www.youtube.com/watch?v=EOFY0cwNjuk
Hope this helps.
If you want to set image as background for whole page, use this:
body
{
background-image: url('Image URL');
}
You could use Synonyms part in the database.
Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply.
Make sure upload
plugin implements this.each
in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });
Check your folder's permission where the image is saved Right cLick on folder then go :
Properties > Security > Edit > Add-- select "everyone" and check Allow "Full Control"
Try This
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%your table name%'
This is a great spot for a reduce
var uniqueArray = o.DATA.reduce(function (a, d) {
if (a.indexOf(d.name) === -1) {
a.push(d.name);
}
return a;
}, []);
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
One thing that confused me a little bit with this command is that if redis-cli
fails to connect using the passed connection string it will still put you in the redis-cli
shell, i.e:
redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected>
You'll then need to exit
to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli
commands wondering why the command wasn't using my passed connection string.
I'm not familiar with resolve, but I've used the others:
Recursive is the default for non-fast-forward merges. We're all familiar with that one.
I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.
An octopus branch merges multiple heads in one commit as long as it can do it cleanly.
For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).
A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):
However, a single octopus merge would look like this:
commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
Ours == I want to pull in another head, but throw away all of the changes that head introduces.
This keeps the history of a branch without any of the effects of the branch.
(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours
)
Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.
The or
operator returns the first operand if it is true, otherwise the second operand. So in your case your test is equivalent to if name == "Jesse"
.
The correct application of or
would be:
if (name == "Jesse") or (name == "jesse"):
While Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?
.
hash.key?(some_key)
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.
To answer your question:
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
You can use jQuery's $.getScript()
method to do it but if you want a more full feature one, yepnope.js is your choice. It supports conditional loading of scripts and stylesheets and it's easy to use.
Add the following CSS:
For the parent div:
style="display: flex;"
For child div:
style="align-items: stretch;"
You can try with:
route -n get default
It is not the same as GNU/Linux's route -n
(or even ip route show
) but is useful for checking the default route information.
Also, you can check the route that packages will take to a particular host. E.g.
route -n get www.yahoo.com
The output would be similar to:
route to: 98.137.149.56
destination: default
mask: 128.0.0.0
gateway: 5.5.0.1
interface: tun0
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1500 0
IMHO netstat -nr
is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information.
I hope this helps :)
(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app
I think the solution from medopal is what you are looking for.
But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.
This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.
Browser jumps to <element id="abc" />
if there are http://site.com/#abc hash in the address and the element with id="abc" is visible. So, you just should hide the element by default: <element id="anchor" style="display: none" />
.
If there is no visible element with id=hash at the page, the browser would not jump.
Create a script that checks the hash in url, and then finds and shows the prrpopriate element (that is hidden by default).
Disable default "hash-like link" behaviour by binding an onclick event to a link and specify return false;
as a result of onclick event.
When I implemented tabs, I wrote something like that:
<script>
$(function () {
if (location.hash != "") {
selectPersonalTab(location.hash);
}
else {
selectPersonalTab("#cards");
}
});
function selectPersonalTab(hash) {
$("#personal li").removeClass("active");
$("a[href$=" + hash + "]").closest("li").addClass("active");
$("#personaldata > div").hide();
location.hash = hash;
$(hash).show();
}
$("#personal li a").click(function (e) {
var t = e.target;
if (t.href.indexOf("#") != -1) {
var hash = t.href.substr(t.href.indexOf("#"));
selectPersonalTab(hash);
return false;
}
});
</script>
Actually what you are searching is: Optional.map. Your code would then look like:
object.map(o -> "result" /* or your function */)
.orElseThrow(MyCustomException::new);
I would rather omit passing the Optional
if you can. In the end you gain nothing using an Optional
here. A slightly other variant:
public String getString(Object yourObject) {
if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
throw new MyCustomException();
}
String result = ...
// your string mapping function
return result;
}
If you already have the Optional
-object due to another call, I would still recommend you to use the map
-method, instead of isPresent
, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).
I have struggled on this same issue for several days. It can be solved by modifying the security user access properties of the file system folder on which your site is mapped. But IIS_IUSRS is not the only account you must authorize.
OR
Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.
function CallbackFunction(event) {
if(window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
if (event.currentTarget.performance.navigation.type == 2) {
alert("back button is clicked");
}
if (event.currentTarget.performance.navigation.type == 1) {
alert("refresh button is clicked");
}
}
}
How about the ole goto statement (i know, i know, but it works just fine here ;)
DECLARE
v_attr char(88);
CURSOR SELECT_USERS IS
SELECT id FROM USER_TABLE
WHERE USERTYPE = 'X';
BEGIN
FOR user_rec IN SELECT_USERS LOOP
BEGIN
SELECT attr INTO v_attr
FROM ATTRIBUTE_TABLE
WHERE user_id = user_rec.id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- user does not have attribute, continue loop to next record.
goto end_loop;
END;
<<end_loop>>
null;
END LOOP;
END;
Just put end_loop at very end of loop of course. The null can be substituted with a commit maybe or a counter increment maybe, up to you.
From JavaScript, since the Github API is CORS enabled:
fetch('https://api.github.com/repos/webdev23/source_control_sentry')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
_x000D_
An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.
You can use ALTER TABLE command with 'LOCATION' option. Here is below required command
ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'
The only condition here is, the location should be a directory instead of file.
Hope this will solve the problem.
def nans(df): return df[df.isnull().any(axis=1)]
then when ever you need it you can type:
nans(your_dataframe)
As others have said, defeating caching completely for dev purposes can be done easily without changing code: use a browser setting or a plugin. Outside of dev, to defeat Angular template caching of route-based templates, remove the template URL from the cache during $routeChangeStart (or $stateChangeStart, for UI Router) as Shayan showed. However, that does NOT affect the caching of templates loaded by ng-include, because those templates are not loaded through the router.
I wanted to be able to hotfix any template, including those loaded by ng-include, in production and have users receive the hotfix in their browser quickly, without having to reload the entire page. I'm also not concerned about defeating HTTP caching for templates. The solution is to intercept every HTTP request that the app makes, ignore those that are not for my app's .html templates, then add a param to the template's URL that changes every minute. Note that the path-checking is specific to the path of your app's templates. To get a different interval, change the math for the param, or remove the % completely to get no caching.
// this defeats Angular's $templateCache on a 1-minute interval
// as a side-effect it also defeats HTTP (browser) caching
angular.module('myApp').config(function($httpProvider, ...) {
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
config.url = getTimeVersionedUrl(config.url);
return config;
}
};
});
function getTimeVersionedUrl(url) {
// only do for html templates of this app
// NOTE: the path to test for is app dependent!
if (!url || url.indexOf('a/app/') < 0 || url.indexOf('.html') < 0) return url;
// create a URL param that changes every minute
// and add it intelligently to the template's previous url
var param = 'v=' + ~~(Date.now() / 60000) % 10000; // 4 unique digits every minute
if (url.indexOf('?') > 0) {
if (url.indexOf('v=') > 0) return url.replace(/v=[0-9](4)/, param);
return url + '&' + param;
}
return url + '?' + param;
}
Your first usage of Map
is inside a function in the combat
class. That happens before Map
is defined, hence the error.
A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map
is fully declared.
The solution is to follow the C++ pattern of the class declaration in a .h
file and the function bodies in a .cpp
. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.
Regarding:
var button = document.getElementById(/* Button client id */);
button.click();
It should be like:
var button = document.getElementById('<%=formID.ClientID%>');
Where formID is the ASP.NET control ID in the .aspx file.
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
I would like to add for the beginners that the difference between the 2 most upvoted answers here is given by the different use of a fragment.
If you use the fragment within the java class where you have the data you want to pass, you can apply the first answer to pass data:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
If however you use for example the default code given by Android Studio for tabbed fragments, this code will not work.
It will not work even if you replace the default PlaceholderFragment with your FragmentClasses, and even if you correct the FragmentPagerAdapter to the new situation adding a switch for getItem() and another switch for getPageTitle() (as shown here)
Warning: the clip mentioned above has code errors, which I explain later here, but is useful to see how you go from default code to editable code for tabbed fragments)! The rest of my answer makes much more sense if you consider the java classes and xml files from that clip (representative for a first use of tabbed fragments by a beginner scenario).
The main reason the most upvoted answer from this page will not work is that in that default code for tabbed fragments, the fragments are used in another java class: FragmentPagerAdapter!
So, in order to send the data, you are tempted to create a bundle in the MotherActivity and pass it in the FragmentPagerAdapter, using answer no.2.
Only that is wrong again. (Probably you could do it like that, but it is just a complication which is not really needed).
The correct/easier way to do it, I think, is to pass the data directly to the fragment in question, using answer no.2. Yes, there will be tight coupling between the Activity and the Fragment, BUT, for tabbed fragments, that is kind of expected. I would even advice you to create the tabbed fragments inside the MotherActivity java class (as subclasses, as they will never be used outside the MotherActivity) - it is easy, just add inside the MotherActivity java class as many Fragments as you need like this:
public static class Tab1 extends Fragment {
public Tab1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
return rootView;
}
}.
So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).
public class MotherActivity extends Activity {
private String out;
private Bundle results;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother_activity);
// for example get a value from the previous activity
Intent intent = getIntent();
out = intent.getExtras().getString("Key");
}
public Bundle getMyData() {
Bundle hm = new Bundle();
hm.putString("val1",out);
return hm;
}
}
And then in the fragment class, you use getMyData:
public static class Tab1 extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public Tab1() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout_name_for_fragment_1, container, false);
TextView output = (TextView)rootView.findViewById(R.id.your_id_for_a_text_view_within_the_layout);
MotherActivity activity = (MotherActivity)getActivity();
Bundle results = activity.getMyData();
String value1 = results.getString("val1");
output.setText(value1);
return rootView;
}
}
If you have database queries I advice you to do them in the MotherActivity (and pass their results as Strings/Integers attached to keys inside a bundle as shown above), as inside the tabbed fragments, your syntax will become more complex (this becomes getActivity() for example, and getIntent becomes getActivity().getIntent), but you have also the option to do as you wish.
My advice for beginners is to focus on small steps. First, get your intent to open a very simple tabbed activity, without passing ANY data. Does it work? Does it open the tabs you expect? If not, why?
Start from that, and by applying solutions such as those presented in this clip, see what is missing. For that particular clip, the mainactivity.xml is never shown. That will surely confuse you. But if you pay attention, you will see that for example the context (tools:context) is wrong in the xml fragment files. Each fragment XML needs to point to the correct fragment class (or subclass using the separator $).
You will also see that in the main activity java class you need to add tabLayout.setupWithViewPager(mViewPager) - right after the line TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); without this line, your view is actually not linked to the XML files of the fragments, but it shows ONLY the xml file of the main activity.
In addition to the line in the main activity java class, in the main activity XML file you need to change the tabs to fit your situation (e.g. add or remove TabItems). If you do not have tabs in the main activity XML, then possibly you did not choose the correct activity type when you created it in the first place (new activity - tabbed activity).
Please note that in the last 3 paragraphs I talk about the video! So when I say main activity XML, it is the main activity XML in the video, which in your situation is the MotherActivity XML file.
Using PHP version 4.4.9 & MySQL 5.0, this worked for me:
$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate
PubDate
is the column in MySQL.
I am just curious why the official docs are so ignored which elaborate the details meticulously already.
But if you'd like to understand the cases, please refer to duffymo's answer.
The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories--new, emerging, and already deployed--can be accessed in a common way.
And its architecture
And normally how you use it.
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Code = (Label)e.Row.FindControl("lblCode");
if (lbl_Code.Text == "1")
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#f2d9d9");
}
}
}
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
I was in a similar problem than you. I need to lock device orientation for some screens (like Login) and allow rotation in others.
After a few changes and following some answers below I did it by:
shouldAutorotate
method in this VC:-(BOOL)shouldAutorotate{
return NO;
}
Hope this will work for you.
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
Direct get a count of row
Using Eloquent
//Useing Eloquent
$count = Model::count();
//example
$count1 = Wordlist::count();
Using query builder
//Using query builder
$count = \DB::table('table_name')->count();
//example
$count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:
ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
Regex to the rescue!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
Example:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
You can do:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, style='.-')
plt.show()
This will return a graph with the data points marked with a dot
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
Try changing your Content Type (media type) to application/x-download
and your Content-Disposition to: attachment;filename=" + fileName;
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
To further work with array of maps, the followings could help:
@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {
List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
maps.addAll(payload);
}
You want to use the isspace()
method
str.isspace()
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
That's defined on every string object. Here it is an usage example for your specific use case:
if aStr and (not aStr.isspace()):
print aStr
This usually appears when you want to use UIActivityViewController
in iPad.
Add below, before you present the controller to mark the arrow.
activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC
I assume you already have below, if not, add together:
activityViewController.popoverPresentationController?.sourceView = self.view
function converter()
{
var number = $(.number).text();
var number = 'Rp. '+number;
s(.number).val(number);
}
You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.
You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m
as
Unfortunately, np.polynomial.polynomial.polyfit
returns the coefficients in the opposite order of that for np.polyfit
and np.polyval
(or, as you used np.poly1d
). To illustrate:
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
0.65459882])
In [41]: np.polyfit(x, y, 4)
Out[41]:
array([ 0.65459882, -8.859311 , 44.83281407, -100.53595375,
84.29340846])
In general: np.polynomial.polynomial.polyfit
returns coefficients [A, B, C]
to A + Bx + Cx^2 + ...
, while np.polyfit
returns: ... + Ax^2 + Bx + C
.
So if you want to use this combination of functions, you must reverse the order of coefficients, as in:
ffit = np.polyval(coefs[::-1], x_new)
However, the documentation states clearly to avoid np.polyfit
, np.polyval
, and np.poly1d
, and instead to use only the new(er) package.
You're safest to use only the polynomial package:
import numpy.polynomial.polynomial as poly
coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)
Or, to create the polynomial function:
ffit = poly.Polynomial(coefs) # instead of np.poly1d
plt.plot(x_new, ffit(x_new))
If its in a landscape then you will be needing more width and less height! That's just what all websites have.
Lets go with a basic first then the rest!
The basic CSS:
By CSS you can do this,
#body {
width: 100%;
height: 100%;
}
Here you are using a div with id
body, as:
<body>
<div id="body>
all the text would go here!
</div>
</body>
Then you can have a web page with 100%
height and width.
What if he tries to resize the window?
The issues pops up, what if he tries to resize the window? Then all the elements inside #body
would try to mess up the UI. For that you can write this:
#body {
height: 100%;
width: 100%;
}
And just add min-height
max-height
min-width
and max-width
.
This way, the page element would stay at the place they were at the page load.
Using JavaScript:
Using JavaScript, you can control the UI, use jQuery as:
$('#body').css('min-height', '100%');
And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.
How to not add scroll to the web page:
If you are not trying to add a scroll, then you can use this JS
$('#body').css('min-height', screen.height); // or anyother like window.height
This way, the document will get a new height whenever the user would load the page.
Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!
Tip: So try using JS to find current Screen size and edit the page! :)
After you clone repository repo
, you can edit repo/.git/config
and add some configuration like below:
[user]
name = you_name
password = you_password
[credential]
helper = store
Then you won't be asked for username
and password
again.
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
Code:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
Explanation:
The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z
%TIME% is in the format H:MM:SS,CS after midnight and hence conversion to centiseconds >doesn't work. Seeing Patrick Cuff's post with 6:46am it seems that it is not only me.
But with this lines bevor you should will fix that problem easy:
if " "=="%StartZeit:~0,1%" set StartZeit=0%StartZeit:~-10%
if " "=="%EndZeit:~0,1%" set EndZeit=0%EndZeit:~-10%
Thanks for your nice inspiration! I like to use it in my mplayer, ffmpeg, sox Scripts to pimp my mediafiles for old PocketPlayers just for fun.
I have a folder /fields full of files with a single class each, ex:
fields/Text.js -> Test class
fields/Checkbox.js -> Checkbox class
Drop this in fields/index.js to export each class:
var collectExports, fs, path,
__hasProp = {}.hasOwnProperty;
fs = require('fs');
path = require('path');
collectExports = function(file) {
var func, include, _results;
if (path.extname(file) === '.js' && file !== 'index.js') {
include = require('./' + file);
_results = [];
for (func in include) {
if (!__hasProp.call(include, func)) continue;
_results.push(exports[func] = include[func]);
}
return _results;
}
};
fs.readdirSync('./fields/').forEach(collectExports);
This makes the modules act more like they would in Python:
var text = new Fields.Text()
var checkbox = new Fields.Checkbox()
Assuming that temp
is a char
and textFile
is a std::fstream
derivative...
The syntax you're looking for is
textFile.get( temp );
Nowadays you can also use lazy_eval
function from lazyeval
package.
> lazyeval::lazy_eval("5+5")
[1] 10
Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.
PHP Page: session.php
if (!isset($_SESSION))
{
session_start();
}
$_SESSION['variable'] = "hello world";
$sessions = array();
$sessions['variable'] = $_SESSION['variable'];
header('Content-Type: application/json');
echo json_encode($sessions);
Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.
JS All Together
var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {
Session.then(function(response){
$rootScope.session = response;
});
}]);
app.factory('Session', function($http) {
return $http.get('/session.php').then(function(result) {
return result.data;
});
});
HTML
Inside your html you can reference your session
<html ng-app="StarterApp">
<body ng-controller="AppCtrl">
{{ session.variable }}
</body>
On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.
I think this is wrong: "65536" ==> 0.0.255.255" Should be: "65535" ==> 0.0.255.255" or "65536" ==> 0.1.0.0"
You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.
Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.
Using TextWatcher in Android
Here is a sample code. Try using addTextChangedListener
method of TextView
addTextChangedListener(new TextWatcher() {
BigDecimal previousValue;
BigDecimal currentValue;
@Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
if (isFirstTimeChange) {
return;
}
if (s.toString().length() > 0) {
try {
currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
} catch (Exception e) {
currentValue = new BigDecimal(0);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if (isFirstTimeChange) {
return;
}
if (s.toString().length() > 0) {
try {
previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
} catch (Exception e) {
previousValue = new BigDecimal(0);
}
}
}
@Override
public void afterTextChanged(Editable editable) {
if (isFirstTimeChange) {
isFirstTimeChange = false;
return;
}
if (currentValue != null && previousValue != null) {
if ((currentValue.compareTo(previousValue) > 0)) {
//setBackgroundResource(R.color.devises_overview_color_green);
setBackgroundColor(flashOnColor);
} else if ((currentValue.compareTo(previousValue) < 0)) {
//setBackgroundResource(R.color.devises_overview_color_red);
setBackgroundColor(flashOffColor);
} else {
//setBackgroundColor(textColor);
}
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 1000);
}
}
});
There are several ways to use gitignore git
just create a .gitignore file and write in whatever you want to ignore a sample gitignore file would be:
# NPM packages folder.
node_modules
# Build files
dist/
# lock files
yarn.lock
package-lock.json
# Logs
logs
*.log
npm-debug.log*
# node-waf configuration
.lock-wscript
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Jest Coverage
coverage
.history/
You can find more on git documentation gitignore
If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.
var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;
Above query will be converted to this:
Select Top (1) UserId, Name from MyTable where UserId = 1;
For multiple items you can simply chain Select after Where:
var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);
Use anonymous object inside Select if you need more than one properties.
Here's what I do... CoffeeScript:
ready = ->
...your coffeescript goes here...
$(document).ready(ready)
$(document).on('page:load', ready)
last line listens for page load which is what turbo links will trigger.
Edit...adding Javascript version (per request):
var ready;
ready = function() {
...your javascript goes here...
};
$(document).ready(ready);
$(document).on('page:load', ready);
Edit 2...For Rails 5 (Turbolinks 5) page:load
becomes turbolinks:load
and will be even fired on initial load. So we can just do the following:
$(document).on('turbolinks:load', function() {
...your javascript goes here...
});
use http://www.php.net/manual/en/datetime.add.php like
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d');
output
2000-01-2
I got tired of every solution in here either being outdated or requiring root, so I made an LD_PRELOAD-based solution (Linux only).
It hooks into Git's internals, overriding the 'is this a symlink?' function, allowing symlinks to be treated as their contents. By default, all links to outside the repo are inlined; see the link for details.
Library called Darvin
can be used.
import Darwin
exit(0) // Here you go
NB: This is not recomanded in iOS applications.
Doing this will get you crash log.
Quick and dirty:
#!/usr/bin/perl -w
use strict;
open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);
foreach(@lines) {
$_ =~ s/<PREF>/ABCD/g;
}
open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.
In the interest of coverage. I put forward an implementation using lambda expressions.
C++11
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const MyStruct& lhs, const MyStruct& rhs )
{
return lhs.key < rhs.key;
});
C++14
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const auto& lhs, const auto& rhs )
{
return lhs.key < rhs.key;
});
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
Ex:
CREATE TABLE 'test'.'pic' (
'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'caption' VARCHAR(45) NOT NULL,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('idpic')
)
As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.
You can use Lodash merge:
var object = {
'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
'a': [{ 'c': 3 }, { 'e': 5 }]
};
_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
rake tmp:cache:clear
might be what you're looking for.
Simply restarting Visual Studio works for me.. try restarting Visual Studio.
Another example
public IEnumerable<string> Tokenize(params string[] words)
{
...
}
var items = Tokenize(product.Name, product.FullName, product.Xyz)
Assuming that winrar.exe
is in the PATH
, then Runtime.exec
is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe
is installed in C:/Program Files/WinRAR
you would need to use something like...
p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");
Personally, I would recommend that you use ProcessBuilder
as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String
elements, it deals with things like spaces much better then a single String
variable, for example...
ProcessBuilder pb = new ProcessBuilder(
"C:/Program Files/WinRAR/winrar",
"x",
"myjar.jar",
"*.*",
"new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
Don't forget to read the contents of the InputStream
from the process, as failing to do so may stall the process
List node process:
$ ps -e|grep node
Kill the process using
$kill -9 XXXX
Here XXXX is the process number
Try this,
this.props.router.push('/foo')
warning works for versions prior to v4
and
this.props.history.push('/foo')
for v4 and above
Short Answer: value >= 0 means that the servlet is loaded when the web-app is deployed or when the server starts. value < 0 : servlet is loaded whenever the container feels like.
Long answer (from the spec):
The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive 128 integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.
The issue is it is missing Dynamic Web Module facet definition. Run the following at command line
mvn eclipse:eclipse -Dwtpversion=2.0
After build is success, refresh the project and you will be add the web project to server.
The problem is you can't template a typedef, also there is no need to typedef structs in C++.
The following will do what you need
template <typename T>
struct array {
size_t x;
T *ary;
};
I think programmers should be competent in the language they are using; use it clearly; and use it well. I don't think they should artificially cripple the language they are using. I speak from experience. I once worked literally next door to a Cobol shop where they didn't use ELSE 'because it was too complicated'. Reductio ad absurdam.
Solution it's quite simple
Just enable Builds for iOS 8 and Later
Try
rows = tabDelimitedTable.split("[" + newLine + "]");
This should solve the regex problem.
Also not that important but return type of
System.getProperty("line.separator")
is String so no need to call toString().
The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.
This simply means when you override an existing method, the exception that this overloaded method throws should be either the same exception which the original method throws or any of its subclasses.
Note that checking whether all checked exceptions are handled is done at compile time and not at runtime. So at compile time itself, the Java compiler checks the type of exception the overridden method is throwing. Since which overridden method will be executed can be decided only at runtime, we cannot know what kind of Exception we have to catch.
Example
Let's say we have class A
and its subclass B
. A
has method m1
and class B
has overridden this method (lets call it m2
to avoid confusion..). Now let's say m1
throws E1
, and m2
throws E2
, which is E1
's superclass. Now we write the following piece of code:
A myAObj = new B();
myAObj.m1();
Note that m1
is nothing but a call to m2
(again, method signatures are same in overloaded methods so do not get confuse with m1
and m2
.. they are just to differentiate in this example... they both have same signature).
But at compile time, all java compiler does is goes to the reference type (Class A
in this case) checks the method if it is present and expects the programmer to handle it. So obviously, you will throw or catch E1
. Now, at runtime, if the overloaded method throws E2
, which is E1
's superclass, then ... well, it's very wrong (for the same reason we cannot say B myBObj = new A()
). Hence, Java does not allow it. Unchecked exceptions thrown by the overloaded method must be same, subclasses, or non-existent.
I solved the same issue 10 minutes ago, so I will give you a short effective fix: Place this inside the application tag or your manifest:
android:theme="@android:style/Theme.Holo"
Also set the Theme of your XML layout to Holo, in the layout's graphical view.
Libraries will be useful if you need to change more complicated theme stuff, but this little fix will work, so you can move on with your app.
I have some documents where …
was showing as …
and ê
was showing as ê
. This is how it got there (python code):
# Adam edits original file using windows-1252
windows = '\x85\xea'
# that is HORIZONTAL ELLIPSIS, LATIN SMALL LETTER E WITH CIRCUMFLEX
# Beth reads it correctly as windows-1252 and writes it as utf-8
utf8 = windows.decode("windows-1252").encode("utf-8")
print(utf8)
# Charlie reads it *incorrectly* as windows-1252 writes a twingled utf-8 version
twingled = utf8.decode("windows-1252").encode("utf-8")
print(twingled)
# detwingle by reading as utf-8 and writing as windows-1252 (it's really utf-8)
detwingled = twingled.decode("utf-8").encode("windows-1252")
assert utf8==detwingled
To fix the problem, I used python code like this:
with open("dirty.html","rb") as f:
dt = f.read()
ct = dt.decode("utf8").encode("windows-1252")
with open("clean.html","wb") as g:
g.write(ct)
(Because someone had inserted the twingled version into a correct UTF-8 document, I actually had to extract only the twingled part, detwingle it and insert it back in. I used BeautifulSoup for this.)
It is far more likely that you have a Charlie in content creation than that the web server configuration is wrong. You can also force your web browser to twingle the page by selecting windows-1252 encoding for a utf-8 document. Your web browser cannot detwingle the document that Charlie saved.
Note: the same problem can happen with any other single-byte code page (e.g. latin-1) instead of windows-1252.
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
you can use WMI in .net too but you're then dependent on the wmi service running etc. Sometimes it works locally, but then fail when the same code is run on servers. I believe that's a namespace issue, related to the "names" whose values you're reading.
Summary from answers and links below:
NULL
), whereas a reference always refers to an object.&obj + 5
).To clarify a misconception:
The C++ standard is very careful to avoid dictating how a compiler may implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:
int &ri = i;
if it's not optimized away entirely, allocates the same amount of storage as a pointer, and places the address of
i
into that storage.
So, a pointer and a reference both use the same amount of memory.
As a general rule,
Interesting read:
You can use this code, it can return true
or false
:
$(document).ready(function(){_x000D_
_x000D_
//add selector of your checkbox_x000D_
_x000D_
var status=$('#IdSelector')[0].checked;_x000D_
_x000D_
console.log(status);_x000D_
_x000D_
});
_x000D_
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
Just use the insert query and put the NULL keyword without quotes. That will work-
INSERT INTO `myDatabase`.`myTable` (`myColumn`) VALUES (NULL);
For emulating Ruby syntax (and convey the semantics) of opening and reading a file, consider this implicit class (Scala 2.10 and upper),
import java.io.File
def open(filename: String) = new File(filename)
implicit class RichFile(val file: File) extends AnyVal {
def read = io.Source.fromFile(file).getLines.mkString("\n")
}
In this way,
open("file.txt").read
There is another point must be noted before regenerating keys that resolve 90% issue.
for example your xampp directory is C:\xampp
and htdocs folder is C:\xampp\htdocs
we want to open page called: example-cap.html and page is showing error "invalid domain for site key"
USE YOUR LOCALHOST ADDRESS in browser address like:
localhost/example-cap.html
this will resolve your issue
DONOT USE ADDRESS c:\xampp\htdocs\example-cap.html this will generate error
Internet Explorer, Chrome, Firefox...
Cross Browser function "isVisible()"
//check if exist and is visible
function isVisible(id) {
var element = $('#' + id);
if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
return true;
} else {
return false;
}
}
Full example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
//check if exist and is visible
function isVisible(id) {
var element = $('#' + id);
if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
return true;
} else {
return false;
}
}
function check(id) {
if (isVisible(id)) {
alert('visible: true');
} else {
alert('visible: false');
}
return false;
}
</script>
<style type="text/css">
#fullname{
display: none;
}
#vote{
visibility: hidden;
}
</style>
<title>Full example: isVisible function</title>
</head>
<body>
<div id="hello-world">
Hello World!
</div>
<div id="fullname">
Fernando Mosquera Catarecha
</div>
<div id="vote">
rate it!
</div>
<a href="#" onclick="check('hello-world');">Check isVisible('hello-world')</a><br /><br />
<a href="#" onclick="check('fullname');">Check isVisible('fullname')</a><br /><br />
<a href="#" onclick="check('vote');">Check isVisible('vote')</a>
</body>
</html>
Regards,
Fernando
I wanted to make a version of this that uses $.getJSON() from a separate JSON file.
Demo: here
JavaScript:
$(document).ready(function () {
"use strict";
var selectData, $states;
function updateSelects() {
var cities = $.map(selectData[this.value], function (city) {
return $("<option />").text(city);
});
$("#city_names").empty().append(cities);
}
$.getJSON("updateSelect.json", function (data) {
var state;
selectData = data;
$states = $("#us_states").on("change", updateSelects);
for (state in selectData) {
$("<option />").text(state).appendTo($states);
}
$states.change();
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<select id="us_states"></select>
<select id="city_names"></select>
<script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>
JSON:
{
"NE": [
"Smallville",
"Bigville"
],
"CA": [
"Sunnyvale",
"Druryburg",
"Vickslake"
],
"MI": [
"Lakeside",
"Fireside",
"Chatsville"
]
}
An alternative solution, which is portable and with higher precision, available since C++11, is to use std::chrono
.
Here is an example:
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
int main()
{
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
}
Running this on ideone.com gave me:
Delta t2-t1: 282 nanoseconds
It's my code: Work for me
var jsonData = request.body;
var jsonParsed = JSON.parse(JSON.stringify(jsonData));
// message_body = {
// "phone": "5511995001920",
// "body": "WhatsApp API on chat-api.com works good"
// }
axios.post(whatsapp_url, jsonParsed,validateStatus = true)
.then((res) => {
// console.log(`statusCode: ${res.statusCode}`)
console.log(res.data)
console.log(res.status);
// var jsonData = res.body;
// var jsonParsed = JSON.parse(JSON.stringify(jsonData));
response.json("ok")
})
.catch((error) => {
console.error(error)
response.json("error")
})
This is the solution for MS Access.
The example table is called tab
, with fields id
and val
.
SELECT (SELECT last(val)
FROM tab AS temp
WHERE tab.id >= temp.id AND temp.val IS NOT NULL) AS val2, *
FROM tab;
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
for just debugging purpose, use one line code -
msg.writeTo(System.out);
Look at the MSDN blog which details out this error:
Removing Connections
The connection pooler removes a connection from the pool after it has been idle for a long time, or if the pooler detects that the connection with the server has been severed.
Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid.
Invalid connections are removed from the connection pool only when they are closed or reclaimed.
If a connection exists to a server that has disappeared, this connection can be drawn from the pool even if the connection pooler has not detected the severed connection and marked it as invalid.
This is the case because the overhead of checking that the connection is still valid would eliminate the benefits of having a pooler by causing another round trip to the server to occur.
When this occurs, the first attempt to use the connection will detect that the connection has been severed, and an exception is thrown.
Basically what you are seeing is that exception in the last sentence.
A connection is taken from the connection pool, the application does not know that the physical connection is gone, an attempt to use it is done under the assumption that the physical connection is still there.
And you get your exception.
There are a few common reasons for this.
- The server has been restarted, this will close the existing connections.
In this case, have a look at the SQL Server log, usually found at: C:\Program Files\Microsoft SQL Server\\MSSQL\LOG
If the timestamp for startup is very recent, then we can suspect that this is what caused the error. Try to correlate this timestamp with the time of exception.
2009-04-16 11:32:15.62 Server Logging SQL Server messages in file ‘C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG’.
- Someone or something has killed the SPID that is being used.
Again, take a look in the SQL Server log. If you find a kill, try to correlate this timestamp with the time of exception.
2009-04-16 11:34:09.57 spidXX Process ID XX was killed by hostname xxxxx, host process ID XXXX.
- There is a failover (in a mirror setup for example) again, take a look in the SQL Server log.
If there is a failover, try to correlate this timestamp with the time of exception.
2009-04-16 11:35:12.93 spidXX The mirrored database “” is changing roles from “PRINCIPAL” to “MIRROR” due to Failover.
Additionally to the great answer of Erti-Chris Eelmaa - there's annoying window.navigator.webdriver
and it is read-only. Event if you change the value of it to false
it will still have true
. That's why the browser driven by automated software can still be detected.
The variable is managed by the flag --enable-automation
in chrome. The chromedriver launches Chrome with that flag and Chrome sets the window.navigator.webdriver
to true
. You can find it here. You need to add to "exclude switches" the flag. For instance (Go):
package main
import (
"github.com/tebeka/selenium"
"github.com/tebeka/selenium/chrome"
)
func main() {
caps := selenium.Capabilities{
"browserName": "chrome",
}
chromeCaps := chrome.Capabilities{
Path: "/path/to/chrome-binary",
ExcludeSwitches: []string{"enable-automation"},
}
caps.AddChrome(chromeCaps)
wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", 4444))
}
As of the time of this writing, Swift natively supports comparing Dates with all comparison operators (i.e. <
, <=
, ==
, >=
, and >
). You can also compare optional Dates but are limited to <
, ==
, and >
. If you need to compare two optional dates using <=
or >=
, i.e.
let date1: Date? = ...
let date2: Date? = ...
if date1 >= date2 { ... }
You can overload the <=
and >=
operators to support optionals:
func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs < rhs
}
func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs > rhs
}
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById()
, and the actual exception is thrown when you try to call a function setText()
on null
. You should post your XML for R.layout.activity_main
, as it's hard to tell where things went wrong just by looking at your code.
More reading on null pointers: What is a NullPointerException, and how do I fix it?
fwuensche "answer" is corret to set up a CDN; doing this, i removed MaxAgeSeconds.
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
Taking as a given you have a "large" number of data.frames with similar names (here d# where # is some positive integer), the following is a slight improvement of @mark-miller's method. It is more terse and returns a named list of data.frames, where each name in the list is the name of the corresponding original data.frame.
The key is using mget
together with ls
. If the data frames d1 and d2 provided in the question were the only objects with names d# in the environment, then
my.list <- mget(ls(pattern="^d[0-9]+"))
which would return
my.list
$d1
y1 y2
1 1 4
2 2 5
3 3 6
$d2
y1 y2
1 3 6
2 2 5
3 1 4
This method takes advantage of the pattern argument in ls
, which allows us to use regular expressions to do a finer parsing of the names of objects in the environment. An alternative to the regex "^d[0-9]+$"
is "^d\\d+$"
.
As @gregor points out, it is a better overall to set up your data construction process so that the data.frames are put into named lists at the start.
data
d1 <- data.frame(y1 = c(1,2,3),y2 = c(4,5,6))
d2 <- data.frame(y1 = c(3,2,1),y2 = c(6,5,4))
Here is a simple and elegant way of getting filtered files
var allowedFileExtensions = ".csv,.txt";
var files = Directory.EnumerateFiles(@"C:\MyFolder", "*.*", SearchOption.TopDirectoryOnly)
.Where(s => allowedFileExtensions.IndexOf(Path.GetExtension(s)) > -1).ToArray();
I was looking for a solution to remove strings' masks, specifically from Brazilian phones numbers, this post not answered but inspired me. This is my solution:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
IF you are using Android Studio 3+ This will work: android:theme="@style/Theme.AppCompat.NoActionBar"
@android:style/Theme.NoTitleBar will not support in new API and force you app close.
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
In my case, which none of the answers above stated. If your device is using the miniUsb connector, make sure you are using a cable that is not charge-only. I became accustom to using developing with a newer Usb-C device and could not fathom a charge-only cable got mixed with my pack especially since there is no visible way to tell the difference.
Before you uninstall and go through a nightmare of driver reinstall and android menu options. Try a different cable first.
Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN
. If you are using the Java Configs (Spring Boot
) and would like to allow the X-Frame-Options: SAMEORIGIN
, then you would need to use the following.
For older Spring Security versions:
http
.headers()
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
For newer versions like Spring Security 4.0.2:
http
.headers()
.frameOptions()
.sameOrigin();
You can also use BigInteger for variable length bytes. You can convert it to long, int or short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
To get bytes back just:
new BigInteger(bytes).toByteArray()
In your application context declare a AnnotationMethodHandlerAdapter and registerByteArrayHttpMessageConverter:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean id="byteArrayMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
</util:list>
</property>
</bean>
also in the handler method set appropriate content type for your response.
Do NOT do this:
git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch
As the next time you run git rebase
(or git pull --rebase
) those 3 commits would be silently discarded from newbranch
! (see explanation below)
Instead do this:
git reset --keep HEAD~3
git checkout -t -b newbranch
git cherry-pick ..HEAD@{2}
--keep
is like --hard
, but safer, as fails rather than throw away uncommitted changes).newbranch
.newbranch
. Since they're no longer referenced by a branch, it does that by using git's reflog: HEAD@{2}
is the commit that HEAD
used to refer to 2 operations ago, i.e. before we 1. checked out newbranch
and 2. used git reset
to discard the 3 commits.Warning: the reflog is enabled by default, but if you've manually disabled it (e.g. by using a "bare" git repository), you won't be able to get the 3 commits back after running git reset --keep HEAD~3
.
An alternative that doesn't rely on the reflog is:
# newbranch will omit the 3 most recent commits.
git checkout -b newbranch HEAD~3
git branch --set-upstream-to=oldbranch
# Cherry-picks the extra commits from oldbranch.
git cherry-pick ..oldbranch
# Discards the 3 most recent commits from oldbranch.
git branch --force oldbranch oldbranch~3
(if you prefer you can write @{-1}
- the previously checked out branch - instead of oldbranch
).
Why would git rebase
discard the 3 commits after the first example? It's because git rebase
with no arguments enables the --fork-point
option by default, which uses the local reflog to try to be robust against the upstream branch being force-pushed.
Suppose you branched off origin/master when it contained commits M1, M2, M3, then made three commits yourself:
M1--M2--M3 <-- origin/master
\
T1--T2--T3 <-- topic
but then someone rewrites history by force-pushing origin/master to remove M2:
M1--M3' <-- origin/master
\
M2--M3--T1--T2--T3 <-- topic
Using your local reflog, git rebase
can see that you forked from an earlier incarnation of the origin/master branch, and hence that the M2 and M3 commits are not really part of your topic branch. Hence it reasonably assumes that since M2 was removed from the upstream branch, you no longer want it in your topic branch either once the topic branch is rebased:
M1--M3' <-- origin/master
\
T1'--T2'--T3' <-- topic (rebased)
This behavior makes sense, and is generally the right thing to do when rebasing.
So the reason that the following commands fail:
git branch -t newbranch
git reset --hard HEAD~3
git checkout newbranch
is because they leave the reflog in the wrong state. Git sees newbranch
as having forked off the upstream branch at a revision that includes the 3 commits, then the reset --hard
rewrites the upstream's history to remove the commits, and so next time you run git rebase
it discards them like any other commit that has been removed from the upstream.
But in this particular case we want those 3 commits to be considered as part of the topic branch. To achieve that, we need to fork off the upstream at the earlier revision that doesn't include the 3 commits. That's what my suggested solutions do, hence they both leave the reflog in the correct state.
For more details, see the definition of --fork-point
in the git rebase and git merge-base docs.
You must include jQuery in the project.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php
Hope this helps someone else.
If you need a convenient command line interface or python API, look at repositorytools
Using it, you can upload artifact to nexus with command
artifact upload foo-1.2.3.ext releases com.fooware
To make it work, you will also need to set some environment variables
export REPOSITORY_URL=https://repo.example.com
export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword
SELECT prosrc FROM pg_proc WHERE proname = 'function_name';
This tells the function handler how to invoke the function. It might be the actual source code of the function for interpreted languages, a link symbol, a file name, or just about anything else, depending on the implementation language/call convention
Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.
I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.
If you don't need to display exact result "running" / "not runnuning", you could simply:
ps notepad -ErrorAction SilentlyContinue | kill -PassThru
If the process was not running, you'll get no results. If it was running, you'll receive get-process
output, and the process will be stopped.
Apart from standard Heap parameters -Xms
and -Xmx
it's also good to know -XX:PermSize
and -XX:MaxPermSize
, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.
>>> a.argmax(axis=0)
array([1, 1, 0])
The top answer didn´t work for me. After some investigation I found the required information on "Android Developer": https://developer.android.com/training/articles/security-ssl.html#SelfSigned
Creating an empty implementation of X509TrustManager did the trick:
private static class MyTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
...
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
try
{
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] tmlist = {new MyTrustManager()};
context.init(null, tmlist, null);
conn.setSSLSocketFactory(context.getSocketFactory());
}
catch (NoSuchAlgorithmException e)
{
throw new IOException(e);
} catch (KeyManagementException e)
{
throw new IOException(e);
}
conn.setRequestMethod("GET");
int rcode = conn.getResponseCode();
Please be aware that this empty implementation of TustManager is just an example and using it in a productive environment would cause a severe security threat!
This MSDN thread explains how to fix it.
To summarize:
Either disable incremental linking, by going to
Project Properties
-> Configuration Properties
-> Linker (General)
-> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"
or install VS2010 SP1.
Edits (@CraigRinger): Note that installing VS 2010 SP1 will remove the 64-bit compilers. You need to install the VS 2010 SP1 compiler pack to get them back.
This affects Microsoft Windows SDK 7.1 for Windows 7 and .NET 4.0 as well as Visual Studio 2010.
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
What do you mean exactly? Do you want to reuse the result of your query for an other query?
In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)
#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).
If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.
For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).
#2 Pros and cons for all methods are almost the same and the lesson should be:
Use what ever is most appropriate or feels most intuitive to you.
If you have to assign the same OnClickListener
to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Take action.
}
});
I tend to not implement the OnClickListener
in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this
is all doing).
You can also run a down migration like so:
rake db:migrate:down VERSION=versionnumber
Refer to the Ruby on Rails guide on migrations for more info.
You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:
resultArrGame.add(txt.Game.getText().toString());
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
One straight forward way to ensure the object is initialized without any error is to test the object's type instance.
Here is an example :
p = SomeClass(param1=_param1_value)
self.assertTrue(isinstance(p, SomeClass))
Into Preferences > Settings - Users
File : Preferences.sublime-settings
Write this :
"show_encoding" : true,
It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3
Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value
returns a desired DateTime
object.
public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
object cellValue = cell.Value;
if (cellValue is DateTime result)
{
return result;
}
return null;
}
I used awk for this
a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
Select a Random sample from a tibble type in R:
library("tibble")
a <- your_tibble[sample(1:nrow(your_tibble), 150),]
nrow takes a tibble and returns the number of rows. The first parameter passed to sample
is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.
I find that adb shell pm uninstall <package>
works consistently, where adb uninstall <package>
does not.
Remove the '#' and do
Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
System.Globalization.NumberStyles.AllowHexSpecifier));
You need to use cv.LoadImageM instead of cv.LoadImage:
In [1]: import cv
In [2]: import numpy as np
In [3]: x = cv.LoadImageM('im.tif')
In [4]: im = np.asarray(x)
In [5]: im.shape
Out[5]: (487, 650, 3)
You can override the onBackPressed()
method in your activity and remove the call to super class.
@Override
public void onBackPressed() {
//remove call to the super class
//super.onBackPressed();
}
You can take advantage of the fact that span
is an inline element
span{
word-spacing:10px;
}
However, this solution will break if you have more than one word of text in your span
Yes, the first one is a static method
also called class method
, while the second one is an instance method
.
Consider the following examples, to understand it in more detail.
In ES5
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.isPerson = function(obj) {
return obj.constructor === Person;
}
Person.prototype.sayHi = function() {
return "Hi " + this.firstName;
}
In the above code, isPerson
is a static method, while sayHi
is an instance method of Person
.
Below, is how to create an object from Person
constructor.
var aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
In ES6
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
static isPerson(obj) {
return obj.constructor === Person;
}
sayHi() {
return `Hi ${this.firstName}`;
}
}
Look at how static
keyword was used to declare the static method isPerson
.
To create an object of Person
class.
const aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class
introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.
Annotations are a form of metadata (data about data) added to a Java source file. They are largely used by frameworks to simplify the integration of client code. A couple of real world examples off the top of my head:
JUnit 4 - you add the @Test
annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like @Before
and @BeforeClass
). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the @Test
annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can.
Terracotta - uses both annotations and XML configuration files. For example, the @Root
annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument.
Google Guice - an example would be the @Inject
annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The @Inject
annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).
Hopefully I've given you a flavour of how annotations are used in different frameworks.
All the answers so far don't address the trailing concern:
Is there an efficient method when there are hundreds of revisions after the one to be deleted?
The steps follow, but for reference, let's assume the following history:
[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]
C: commit just following the commit to be removed (clean)
R: The commit to be removed
B: commit just preceding the commit to be removed (base)
Because of the "hundreds of revisions" constraint, I'm assuming the following pre-conditions:
This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.
Here are the steps:
git branch base B
git branch remove-me R
git branch save
git rebase --preserve-merges --onto base remove-me
If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and rebase --continue
or decide to just live with the embarrassment and rebase --abort
.
Now you should be on master
that no longer has commit R in it. The save
branch points to where you were before, in case you want to reconcile.
How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with stash
, reset --hard
, and cherry-pick
. And you can delete the base
, remove-me
, and save
branches
is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>
, then you wrote <target name="build-subprojects"/>
(it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/>
print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277
You can inject .properties
as a map in your class using @Resource
annotation.
If you are working with XML based configuration
, then add below bean in your spring configuration file:
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:your.properties"/>
</bean>
For, Annotation based:
@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource(
"your.properties"));
return bean;
}
Then you can pick them up in your application as a Map:
@Resource(name = "myProperties")
private Map<String, String> myProperties;
"UPDATE member_profile SET points = points + 1 WHERE user_id = '".$userid."'"
By the way, if you are trying to find a way to send double quotes to the device, try the following:
adb shell input text '\"'
I'm not sure why there's no event code for quotes, but this workaround does the job. Also, if you're using MonkeyDevice (or ChimpChat) you should test each caracter before invoking monkeyDevice.type, otherwise you get nothing when you try to send "
In my case setting Java Max Heap Size from 2g to 1g worked.
Add following to application module's build.gradle file
android {
dexOptions {
javaMaxHeapSize "1g"
}
}
As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.
You have to press combination ctrl + z My os is Ubuntu
The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.
Please see the error below:
Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
which points to username
not getting populated
.
Please recheck system properties
dataSource.setUsername(System.getProperty("root"));
some packages seems to be missing as well pointing to a dependency issue:
package org.gjt.mm.mysql does not exist
Please run a mvn dependency:tree
command to check for dependencies
Use break
and continue
to do this. Breaking nested loops can be done in Python using the following:
for a in range(...):
for b in range(..):
if some condition:
# break the inner loop
break
else:
# will be called if the previous loop did not end with a `break`
continue
# but here we end up right after breaking the inner loop, so we can
# simply break the outer loop as well
break
Another way is to wrap everything in a function and use return
to escape from the loop.
document.querySelector('#from1').onsubmit = function(e){
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm){
swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
e.preventDefault();
}
});
};
In my case it was libjpeg
. All I had to do was run brew reinstall libjpeg
and everything just worked!
There is a new version of hotKeys.js that works with 1.10+ version of jQuery. It is small, 100 line javascript file. 4kb or just 2kb minified. Here are some Simple usage examples are :
$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);
$('#myBody').hotKey({ key: 'f4' }, doSomethingElse);
$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
doSomethingWithaParameter('Daniel');
});
$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);
Clone the repo from github : https://github.com/realdanielbyrne/HoyKeys.git or go to the github repo page https://github.com/realdanielbyrne/HoyKeys or fork and contribute.
In some cases a one-way request without a response can be fired to a TCP server, without a SSL certificate. A TCP server, in contrast to a HTTP server, will catch you request. However there will be no access to any data sent from the browser, because the browser will not send any data without a positive certificate check. And in special cases even a bare TCP signal without any data is enough to execute some tasks. For example for an IoT device within a LAN to start a connection to an external service. Link
This is a kind of a "Wake Up" trigger, that works on a port without any security.
In case a response is needed, this can be implemented using a secured public https server, which can send the needed data back to the browser using e.g. Websockets.
Maybe this is not the best choice, but you can do angular.element("#element").isolateScope()
or $("#element").isolateScope()
to access the scope and/or the controller of your directive.
Write code in this manner ...
<canvas id="canvas" width="640" height="480"></canvas>
<script>
var Grid = function(width, height) {
...
this.draw = function() {
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var context = canvas.getContext("2d");
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(isLive(i, j)) {
context.fillStyle = "lightblue";
}
else {
context.fillStyle = "yellowgreen";
}
context.fillRect(i*15, j*15, 14, 14);
}
}
}
}
}
First write canvas tag and then write script tag. And write script tag in body.
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
Python dictionary has get(key) function
>>> d.get(key)
For Example,
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None
If your key does'nt exist, will return None
value.
foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist
Content relevant to versions less than 3.0 and greater than 5.0.
.You have to override method handledType and everything will work
@Override
public Class<Item> handledType()
{
return Item.class;
}
So you are scrolling down because the Answers do not work:
This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)
1- Data Type in Database is "datetime" and "nullable" in my case.
Example data format in DB is like:
2018-11-06 15:33:43.640
An in C# when converted to string is like:
2019-01-03 4:45:16 PM
So the format is :
yyyy/MM/dd hh:mm:ss tt
2- So you need to prepare your datetime variables in the proper format first:
Example 1
yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")
Example 2 - Datetime range for the last 30 days
DateTime dateStart = DateTime.Now.AddDays(-30);
DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);
3- Finally the linq query you lost your day trying to find (Requires EF 6)
using System.Data.Entity;
_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();
To take time comparison into account as well :
(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)
Note the following method mentioned on other stackoverflow questions and answers will not work correctly:
....
&&
(
s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();
if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:
DatabaseCreatedAtItemThatWeWant = 2018/12/05
startDate = 2018/12/01
EndDate = 2019/01/04
the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail
And in case you have really big data you would execute Native SQL Query rather than linq
...
... where Shipments.Created_at BETWEEN CAST(@Created_at_from as datetime) AND CAST(@Created_at_to as datetime))
....
Thanks
This is an old question I know, but this is in the top five for several related Google searches. Here's the CSS-only solution without changing the images to background images:
width: auto;
height: auto;
max-width: MaxSize;
max-height: MaxSize;
"MaxSize" is a placeholder for whatever max-width
and max-height
you want to use, in pixels or percentage. auto
will increase (or decrease) the width and height to occupy the space you specify with MaxSize. It will override any defaults for images you or the viewer's browser might have for images. I've found it's especially important on Android's Firefox. Pixels or percentages work for max size. With both the height and width set to auto
, the aspect ratio of the original image will be retained.
If you want to fill the space entirely and don't mind the image being larger than its original size, change the two max-width
s to min-width: 100%
- this will make them completely occupy their space and maintain aspect ratio. You can see an example of this with a Twitter profile's background image.
Here is a stripped down example, using as little HTML markup as possible.
The overlay is provided by the :before
pseudo element on the .content
container.
No z-index is required, :before
is naturally layered over the video element.
The .content
container is position: relative
so that the position: absolute
overlay is positioned in relation to it.
The overlay is stretched to cover the entire .content
div width with left / right / bottom
and left
set to 0
.
The width of the video is controlled by the width of its container with width: 100%
.content {
position: relative;
width: 500px;
margin: 0 auto;
padding: 20px;
}
.content video {
width: 100%;
display: block;
}
.content:before {
content: '';
position: absolute;
background: rgba(0, 0, 0, 0.5);
border-radius: 5px;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
_x000D_
<div class="content">
<video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
I have used the below commands for removing any proxy set:
npm config rm proxy
npm config rm https-proxy
And it solved my problem :)
You might find it easier to understand by using a simple subquery
SELECT `settings`.*, (
SELECT `value` FROM `character_settings`
WHERE `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`
The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.
Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.
SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'
// An Answer w/o using Hashset or map or Arraylist
public class Count {
static String names[] = {"name1","name1","name2","name2", "name2"};
public static void main(String args[]) {
printCount(names);
}
public static void printCount(String[] names){
java.util.Arrays.sort(names);
int n = names.length, c;
for(int i=0;i<n;i++){
System.out.print(names[i]+" ");
}
System.out.println();
int result[] = new int[n];
for(int i=0;i<n;i++){
result[i] = 0;
}
for(int i =0;i<n;i++){
if (i != n-1){
for(int j=0;j<n;j++){
if(names[i] == names[j] )
result[i]++;
}
}
else if (names[n-2] == names[n-1]){
result[i] = result[i-1];
}
else result[i] = 1;
}
int max = 0,index = 0;
for(int i=0;i<n;i++){
System.out.print(result[i]+" ");
if (result[i] >= max){
max = result[i];
index = i;
}
}
}
}
For the ROW_NUMBER
technique, if you do not have a sorting column to use, you can use the CURRENT_TIMESTAMP
as follows:
SELECT TOP 20
col1,
col2,
col3,
col4
FROM (
SELECT
tbl.col1 AS col1
,tbl.col2 AS col2
,tbl.col3 AS col3
,tbl.col4 AS col4
,ROW_NUMBER() OVER (
ORDER BY CURRENT_TIMESTAMP
) AS sort_row
FROM dbo.MyTable tbl
) AS query
WHERE query.sort_row > 10
ORDER BY query.sort_row
This has worked well for me for searches over table sizes of even up to 700,000.
This fetches records 11 to 30.
When your font is stored inside res/asset/fonts/Helvetica.ttf
use the following:
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf");
txt.setTypeface(tf);
Or, if your font file is stores inside res/font/helvetica.ttf
use the following:
Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);
You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:
from matplotlib import pyplot
import seaborn
import mylib
a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)
Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>
Somehow "classpath:xxx" is not picking the file.
You can use the python sorting functions' key
parameter to sort the index array instead.
>>> s = [2, 3, 1, 4, 5, 3]
>>> sorted(range(len(s)), key=lambda k: s[k])
[2, 0, 1, 5, 3, 4]
>>>
Just like @Dampes8N said:
$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
fputcsv($fp, $row);
}
fclose($fp);
Hope this helps.
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
It should return
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
Example:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
This code is going to work with any type.
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
This is your dataArray
:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson
can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function MyApp() {
const location = useLocation();
useEffect(() => {
console.log('route has been changed');
...your code
},[location.pathname]);
}
with hooks
Found this to be a practical implementation:
[^@\s]+@[^@\s]+\.[^@\s]+
div's are used to give structure to a website or to contain a lot of text or elements, but you seem to use them as label, you should use span, it will put both text next to eachother automatically and you won't need to wright css code for it.
And even if other people tell you to float the elements it's best that you just change the tags.
Assuming you're intending to use Windows Authentication to impersonate the service account, you have to set up Windows Authentication in both IIS and ASP.NET.
In IIS, make sure that the Windows Authentication module is added and enabled. Also make sure your application pool is running under a domain account, not a local account.
In ASP.NET make sure the authentication mode attribute is set to "Windows"
<system.web>
<authentication mode="Windows"/>
</system.web>
Besides having to escape colons as in the original answer, I have found if the indentation is off you could potentially get the same problem. In one makefile, I had to replace spaces with a tab and that allowed me to get past the error.
Submit
is null
because it is not part of activity_main.xml
When you call findViewById
inside an Activity
, it is going to look for a View
inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="@+id/LoginTitle"
but what you want is probably
android:layout_below="@id/LoginTitle"
See this question about the difference between @id
and @+id
.
When you run
install.packages("whatever")
you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:
.libPaths()
If libPaths shows 2 locations, then paste into second one. Load library:
library(whatever)
Fixed.
I do recommend you to change the configuration of JDK used by NetBeans in netbeans.conf
config file:
netbeans_jdkhome="C:\Program Files\Java\..."
require
will throw a PHP Fatal Error if the file cannot be loaded. (Execution stops)
include
produces a Warning if the file cannot be loaded. (Execution continues)
Here is a nice illustration of include and require difference:
From: Difference require vs. include php (by Robert; Nov 2012)
After I changed
defaultConfig {
applicationId "com.example.bocheng.myapplication"
minSdkVersion 15
targetSdkVersion 'L' #change this to 19
versionCode 1
versionName "1.0"
}
in build.gradle
file.
it works
Just npm install
to install node_modules