I was having some trouble with this, and the "X:not():not()" method wasn't working for me.
I ended up resorting to this strategy:
INPUT {
/* styles */
}
INPUT[type="radio"], INPUT[type="checkbox"] {
/* styles that reset previous styles */
}
It's not nearly as fun, but it worked for me when :not() was being pugnacious. It's not ideal, but it's solid.
This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
This is because you have the following code:
class JSONDeserializer
{
Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};
This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).
class JSONDeserializer
{
Value ParseValue(TDR type, const json_string& valueString);
};
The error come from the fact that JSONDeserializer::ParseValue
is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.
var fileName = 'file.txt';
// Getting Extension
var ext = fileName.split('.')[1];
// OR
var ext = fileName.split('.').pop();
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
Nowadays, in Python 2.7 and up, you can use a dict comprehension:
{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
And in Python 3:
{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
My phone is xiaomi Redmi note 8 with MIUI 11.0.9 . There is no option for create hyperlink : So I use Telegram desktop or Telegram X for create hyperlink because Telegram X supports markdown. Type url and send message (in Telegram X) or there is an alternate way which is the easiest!
Select the text using Xiaomi's Word Editor and click in the three dots on the top right corner of the chat. It is usually used for accessing settings but if you select a text and click there, you can see Telegram's own Formatter!
A little help:
// an anonymous function_x000D_
_x000D_
(function () { console.log('allo') });_x000D_
_x000D_
// a self invoked anonymous function_x000D_
_x000D_
(function () { console.log('allo') })();_x000D_
_x000D_
// a self invoked anonymous function with a parameter called "$"_x000D_
_x000D_
var jQuery = 'I\'m not jQuery.';_x000D_
_x000D_
(function ($) { console.log($) })(jQuery);
_x000D_
You should execute the next query:
GRANT ALL ON TABLE mytable TO myuser;
Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:
GRANT ALL ON TABLE tbm_grupo TO myuser;
Sharon's method worked for me, however when a link in the iframe is followed and then the browser back button is pressed, the cached version of the page is loaded and the iframe is no longer scrollable. To overcome this I used some code to refresh the page as follows:
if ('ontouchstart' in document.documentElement)
{
document.getElementById('Scrolling').src = document.getElementById('SCrolling').src;
}
I know you said you would prefer a GUI, but the commandline tools will do the work nicely. See GnuWin for a port of unix tools to Windows. You'd need the patch command, obviously ;-)
You might run into a problem with the line termination, though. The GnuWin port will assume that the patchfile has DOS style line termination (CR/LF). Try to open the patchfile in a reasonably smart editor and it will convert it for you.
Quoting from wikipedia:
A pointer references a location in memory, and obtaining the value at the location a pointer refers to is known as dereferencing the pointer.
Dereferencing is done by applying the unary *
operator on the pointer.
int x = 5;
int * p; // pointer declaration
p = &x; // pointer assignment
*p = 7; // pointer dereferencing, example 1
int y = *p; // pointer dereferencing, example 2
"Dereferencing a NULL pointer" means performing *p
when the p
is NULL
When I look at the solutions, it seems the problem is always something that prevents the spring library to be loaded. It could be a dependency problem or a deployment problem.
In my case, it was the maven repository that somehow got corrupt. What solved the problem was to remove the folder `C:\Users(my name).m2\repository' and rebuild.
This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.
$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.
When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.
<div ng-view></div>
$routeProvider
.when('/contact/', {
templateUrl: 'app/views/core/contact/contact.html',
controller: 'ContactCtrl'
});
<div ui-view>
<div ui-view='abc'></div>
<div ui-view='abc'></div>
</div>
$stateProvider
.state("contact", {
url: "/contact/",
templateUrl: '/app/Aisel/Contact/views/contact.html',
controller: 'ContactCtrl'
});
the best place to change the size of the calendar is in the file jquery-ui.css
/* Component containers
----------------------------------*/
.ui-widget {
font-family: Verdana,Arial,sans-serif;
font-size: .7em; /* <--default is 1.1em */
}
//xn=list of parent nodes......
foreach (XmlNode xn in xnList)
{
foreach (XmlNode child in xn.ChildNodes)
{
if (child.Name.Equals("name"))
{
name = child.InnerText;
}
if (child.Name.Equals("age"))
{
age = child.InnerText;
}
}
}
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
It's required for extensibility -- if someone uses an API you've developed, the enums you define are static; they can't be added to or modified. However, if you let it implement an interface, the person using the API can develop their own enum using the same interface. You can then register this enum with an enum manager which conglomerates the enums together with the standard interface.
Edit: @Helper Method has the perfect example of this. Think about having other libraries defining new operators and then telling a manager class that 'hey, this enum exists -- register it'. Otherwise, you'd only be able to define Operators in your own code - there'd be no extensibility.
Reviving an old question because it seems to appear at the top of search results.
I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.
<div class="parent-style-one"> @Html.ActionLink("Homepage", "Home", "Home") </div>
.parent-style-one { /* your styles here */ }
.parent-style-one a { text-decoration: none; }
.parent-style-one a:hover { text-decoration: underline; -webkit-transition-duration: 1.1s; /* Safari */ transition-duration: 1.1s; }
This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.
You could do something like this: order your table by e.g. CustomerID (using the AdventureWorks Sales.Customer
sample table), and iterate over those customers using a WHILE loop:
-- define the last customer ID handled
DECLARE @LastCustomerID INT
SET @LastCustomerID = 0
-- define the customer ID to be handled now
DECLARE @CustomerIDToHandle INT
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = CustomerID
FROM Sales.Customer
WHERE CustomerID > @LastCustomerID
ORDER BY CustomerID
-- as long as we have customers......
WHILE @CustomerIDToHandle IS NOT NULL
BEGIN
-- call your sproc
-- set the last customer handled to the one we just handled
SET @LastCustomerID = @CustomerIDToHandle
SET @CustomerIDToHandle = NULL
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = CustomerID
FROM Sales.Customer
WHERE CustomerID > @LastCustomerID
ORDER BY CustomerID
END
That should work with any table as long as you can define some kind of an ORDER BY
on some column.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows
Apple's example:
var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
So in the OP's example, removing animals[2], "chimps":
var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }
This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.
You can get the UserProfile path with just this:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
An alternative to selecting the first element from np.where() is to use a generator expression together with enumerate, such as:
>>> import numpy as np
>>> x = np.arange(100) # x = array([0, 1, 2, 3, ... 99])
>>> next(i for i, x_i in enumerate(x) if x_i == 2)
2
For a two dimensional array one would do:
>>> x = np.arange(100).reshape(10,10) # x = array([[0, 1, 2,... 9], [10,..19],])
>>> next((i,j) for i, x_i in enumerate(x)
... for j, x_ij in enumerate(x_i) if x_ij == 2)
(0, 2)
The advantage of this approach is that it stops checking the elements of the array after the first match is found, whereas np.where checks all elements for a match. A generator expression would be faster if there's match early in the array.
1,Download the bat to exe converter and install it 2,Run the bat to exe application 3,Download .pco images if you want to make good looking exe 4,specify the bat file location(c:\my.bat) 5,Specify the location for saving the exe(ex:c:/my.exe) 6,Select Version Information Tab 7,Choose the icon file (downloaded .pco image) 8,if you want fill the information like version,comapny name etc 9,change the tab to option 10,Select the invisible application(This will hide the command prompt while running the application) 11,Choose 32 bit(if you select 64 bit exe will work only in 32 bit OS) 12,Compile 13,Copy the exe to the location where bat file executed properly 14,Run the exe
You can simulate this problem with a syntax mistake, however, %matplotlib inline
won't resolve the issue.
First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.
df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))
df_randNumbers1.ix[:,["A","B"]].plot.kde()
However, by leaving the ()
off the end of the plot type you receive a somewhat ambiguous non-error.
Erronious code:
df_randNumbers1.ix[:,["A","B"]].plot.kde
Example error:
<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.
The assert() function can diagnose program bugs. In C, it is defined in <assert.h>
, and in C++ it is defined in <cassert>
. Its prototype is
void assert(int expression);
The argument expression can be anything you want to test--a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr and aborts program execution.
How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement
assert(interest_rate >= 0); at locations in the program where interest_rate is used. If the variable ever does become negative, the assert() macro alerts you. You can then examine the relevant code to locate the cause of the problem.
To see how assert() works, run the sample program below. If you enter a nonzero value, the program displays the value and terminates normally. If you enter zero, the assert() macro forces abnormal program termination. The exact error message you see will depend on your compiler, but here's a typical example:
Assertion failed: x, file list19_3.c, line 13 Note that, in order for assert() to work, your program must be compiled in debug mode. Refer to your compiler documentation for information on enabling debug mode (as explained in a moment). When you later compile the final version in release mode, the assert() macros are disabled.
int x;
printf("\nEnter an integer value: ");
scanf("%d", &x);
assert(x >= 0);
printf("You entered %d.\n", x);
return(0);
Enter an integer value: 10
You entered 10.
Enter an integer value: -1
Error Message: Abnormal program termination
Your error message might differ, depending on your system and compiler, but the general idea is the same.
This is possible for Iterable.forEach()
(but not reliably with Stream.forEach()
). The solution is not nice, but it is possible.
WARNING: You should not use it for controlling business logic, but purely for handling an exceptional situation which occurs during the execution of the forEach()
. Such as a resource suddenly stops being accessible, one of the processed objects is violating a contract (e.g. contract says that all the elements in the stream must not be null
but suddenly and unexpectedly one of them is null
) etc.
According to the documentation for Iterable.forEach()
:
Performs the given action for each element of the
Iterable
until all elements have been processed or the action throws an exception... Exceptions thrown by the action are relayed to the caller.
So you throw an exception which will immediately break the internal loop.
The code will be something like this - I cannot say I like it but it works. You create your own class BreakException
which extends RuntimeException
.
try {
someObjects.forEach(obj -> {
// some useful code here
if(some_exceptional_condition_met) {
throw new BreakException();
}
}
}
catch (BreakException e) {
// here you know that your condition has been met at least once
}
Notice that the try...catch
is not around the lambda expression, but rather around the whole forEach()
method. To make it more visible, see the following transcription of the code which shows it more clearly:
Consumer<? super SomeObject> action = obj -> {
// some useful code here
if(some_exceptional_condition_met) {
throw new BreakException();
}
});
try {
someObjects.forEach(action);
}
catch (BreakException e) {
// here you know that your condition has been met at least once
}
Yes, its possible to have array of objects in PHP.
class MyObject {
private $property;
public function __construct($property) {
$this->Property = $property;
}
}
$ListOfObjects[] = new myObject(1);
$ListOfObjects[] = new myObject(2);
$ListOfObjects[] = new myObject(3);
$ListOfObjects[] = new myObject(4);
print "<pre>";
print_r($ListOfObjects);
print "</pre>";
even shorter using the dot:
#!/bin/bash
. CONFIG_FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool
The simplest, and best long-term solution
Go to the main menu on top of Eclipse and locate Window next to Run and expand it.
Window->Reset Perspective... to restore all views to their defaults
It will reset the default setting.
Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!
But how to add this flag by default for all C++ projects? Anybody?
Firstly find out the number's starting length then reverse the string to find out the first position again(which will give you end position of number from the end). Now if you deduct 1 from both number and deduct it from string whole length you'll get only number length. Now get the number using SUBSTRING
declare @fieldName nvarchar(100)='AAAA1221.121BBBB'
declare @lenSt int=(select PATINDEX('%[0-9]%', @fieldName)-1)
declare @lenEnd int=(select PATINDEX('%[0-9]%', REVERSE(@fieldName))-1)
select SUBSTRING(@fieldName, PATINDEX('%[0-9]%', @fieldName), (LEN(@fieldName) - @lenSt -@lenEnd))
An interesting observation I made while passing previous state params from one route to another is that $stateParams gets hoisted and overwrites the previous route's state params that were passed with the current state params, but using $state.param
s doesn't.
When using $stateParams
:
var stateParams = {};
stateParams.nextParams = $stateParams; //{item_id:123}
stateParams.next = $state.current.name;
$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{next:'app.details'}}
When using $state.params:
var stateParams = {};
stateParams.nextParams = $state.params; //{item_id:123}
stateParams.next = $state.current.name;
$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{item_id:123}}
There's a way to do it without branching, but it's not very pretty.
sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
http://graphics.stanford.edu/~seander/bithacks.html
Lots of other interesting, overly-clever stuff on that page, too...
To undo git checkout
do git checkout -
, similarly to cd
and cd -
in shell.
@Ludwig 's solution was brilliant. A couple of fixes (which didn't have to do with operating system, and I couldn't place as a comment on his original posting because this is too long):
Here they are:
(function (window) {
{
/* test cases
alert(
'browserInfo result: OS: ' + browserInfo.os +' '+ browserInfo.osVersion + '\n'+
'Browser: ' + browserInfo.browser +' '+ browserInfo.browserVersion + '\n' +
'Mobile: ' + browserInfo.mobile + '\n' +
'Cookies: ' + browserInfo.cookies + '\n' +
'Screen Size: ' + browserInfo.screen
);
*/
var unknown = 'Unknown';
// screen
var screenSize = '';
if (screen.width) {
width = (screen.width) ? screen.width : '';
height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
//browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
//IE 11 no longer identifies itself as MS IE, so trap it
//http://stackoverflow.com/questions/17907445/how-to-detect-ie11
else if ((browser == 'Netscape') && (nAgt.indexOf('Trident/') != -1)) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
if ((verOffset = nAgt.indexOf('rv:')) != -1) {
version = nAgt.substring(verOffset + 3);
}
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
// Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
// at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
// No mention of chrome in the user agent string. However it does mention CriOS, which presumably
// can be keyed on to detect it.
if (nAgt.indexOf('CriOS') != -1) {
//Chrome on iPad spoofing Safari...correct it.
browser = 'Chrome';
//Don't believe there is a way to grab the accurate version number, so leaving that for now.
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 3.11', r:/Win16/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows ME', r:/Windows ME/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Linux', r:/(Linux|X11)/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS X':
osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
break;
case 'Android':
osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
}
window.browserInfo = {
screen: screenSize,
browser: browser,
browserVersion: version,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled
};
}(this));
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
This should work:
select * from syscat.tables
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:
plt.axes[0].get_lines()[0].set_color('black')
You can escape a '
in JavaScript like \'
You can not alter constraints ever but you can drop them and then recreate.
Have look on this
ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;
and then recreate it with ON DELETE CASCADE
like this
ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
ON DELETE CASCADE;
hope this help
Same as Sergii Pozharov's answer, but with a PowerShell cmdlet:
New-Service -Name "MyService" -BinaryPathName "C:\Path\to\myservice.exe"
See New-Service
for more customization.
This will only work for executables that already implement the Windows Services API.
This function handels "HH:MM:SS" as well as "MM:SS" or "SS".
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0, m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.
HttpResponse response = httpClient.execute(get);
// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();
// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());
A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:
JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.
In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.
The required conventions are:
- The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
- The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
- The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.
Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.
A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb
interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:
POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:
"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."
The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.
The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).
As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.
A Value Object or VO is an object such as java.lang.Integer
that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:
In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.
You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.
A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.
Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.
You can find some more good material on value objects on the wiki and by Dirk Riehle.
Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.
The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).
In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.
So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
I hope it may useful to you.
Example:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
I have found one another simple way to store the data into the database
models.py
class LinkModel(models.Model):
link = models.CharField(max_length=500)
shortLink = models.CharField(max_length=30,unique=True)
In database I have only 2 variables
views.py
class HomeView(TemplateView):
def post(self,request, *args, **kwargs):
form = LinkForm(request.POST)
if form.is_valid():
text = form.cleaned_data['link'] # text for link
dbobj = LinkModel()
dbobj.link = text
self.no = self.gen.generateShortLink() # no for shortLink
dbobj.shortLink = str(self.no)
dbobj.save() # Saving from views.py
In this I have created the instance of model in views.py only and putting/saving data into 2 variables from views only.
It depends on how you want to use your String. This can help:
String total = Integer.toString(123) + Double.toString(456.789);
You can use updateMany()
methods of mongodb to update multiple document
Simple query is like this
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
As per your requirement the update code will be like this:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set
<%-- not rendered to browser --%>
For Scroll View:
if after adding android:windowSoftInputMode="stateHidden|adjustPan"
in your Android Manifest and still does not work.
It may be affected because when the keyboard appears, it will be into a scroll view and if your button/any objects is not in your scroll view then the objects will follow the keyboard and move its position.
Check out your xml where your button is and make sure it is under your scroll View bracket and not out of it.
Hope this helps out. :D
Ok, I know there is an accepted answer but… for more special cases you also could use this one:
array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);
Or in a more un-complex way:
function printItem($n){
echo $n['filename'];
echo $n['filepath'];
}
array_map('printItem', $array);
This will allow you to manipulate the data in an easier way.
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
I think this would do it:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".divlink").click(function(){
$("#content").attr("src" , $(this).attr("ref"));
});
});
</script>
</head>
<body>
<iframe id="content"></iframe>
<a href="#" ref="page1.html" class="divlink" >Page 1</a><br />
<a href="#" ref="page2.html" class="divlink" >Page 2</a><br />
<a href="#" ref="page3.html" class="divlink" >Page 3</a><br />
<a href="#" ref="page4.html" class="divlink" >Page 4</a><br />
<a href="#" ref="page5.html" class="divlink" >Page 5</a><br />
<a href="#" ref="page6.html" class="divlink" >Page 6</a><br />
</body>
</html>
By the way if you can avoid Jquery, you can just use the target
attribute of <a>
element:
<html>
<body>
<iframe id="content" name="content"></iframe>
<a href="page1.html" target="content" >Page 1</a><br />
<a href="page2.html" target="content" >Page 2</a><br />
<a href="page3.html" target="content" >Page 3</a><br />
<a href="page4.html" target="content" >Page 4</a><br />
<a href="page5.html" target="content" >Page 5</a><br />
<a href="page6.html" target="content" >Page 6</a><br />
</body>
</html>
To make a batch file for its current directory and sub directories:
cd %~dp0
attrib -h -r -s /s /d /l *.*
srand(time(NULL));
int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);
Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:
::-webkit-scrollbar
{
width: 12px; /* for vertical scrollbars */
height: 12px; /* for horizontal scrollbars */
}
::-webkit-scrollbar-track
{
background: rgba(0, 0, 0, 0.1);
}
::-webkit-scrollbar-thumb
{
background: rgba(0, 0, 0, 0.5);
}
This answer is a fantastic source of additional information.
Why could you not just do something like this?
class Foo {
constructor(myObj){
Object.assign(this, myObj);
}
get name() { return this._name; }
set name(v) { this._name = v; }
}
let foo = new Foo({ name: "bat" });
foo.toJSON() //=> your json ...
HISTORICAL MOTIVATION:
The existence of non-capturing groups can be explained with the use of parenthesis.
Consider the expressions (a|b)c
and a|bc
, due to priority of concatenation over |
, these expressions represent two different languages ({ac, bc}
and {a, bc}
respectively).
However, the parenthesis are also used as a matching group (as explained by the other answers...).
When you want to have parenthesis but not capture the sub-expression you use NON-CAPTURING GROUPS. In the example, (?:a|b)c
git diff > patchfile
and
patch -p1 < patchfile
work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile
if you need handle file adds, deletes and renames.
EDIT December 2015
Latest versions of patch
command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).
So provided one uses current/latest version of patch
there is no need to use git
to be able to apply its diff as a patch.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
#include stdlib.h
test=substring(i,j,s)
; m
as it is unused char substring(int i,int j,char *ch)
or define it before main Try :
height: 21px;
line-height: 21px; /* FOR IE */
Because on some versions of IE (< 9) the property height is not properly interpreted.
This checks if EAX
is zero. The instruction test
does bitwise AND
between the arguments, and if EAX
contains zero, the result sets the ZF, or ZeroFlag.
Use like this:
if( $('#foo').is(':visible') ) {
// it's visible, do something
}
else {
// it's not visible so do something else
}
Hope it helps!
function randomstring(L) {_x000D_
var s = '';_x000D_
var randomchar = function() {_x000D_
var n = Math.floor(Math.random() * 62);_x000D_
if (n < 10) return n; //1-10_x000D_
if (n < 36) return String.fromCharCode(n + 55); //A-Z_x000D_
return String.fromCharCode(n + 61); //a-z_x000D_
}_x000D_
while (s.length < L) s += randomchar();_x000D_
return s;_x000D_
}_x000D_
console.log(randomstring(5));
_x000D_
I was having troubles understanding an applying the accepted answer. I needed a little more context. Now that I have figured it out, here is a full example:
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button myButton;
View myView;
boolean isUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = findViewById(R.id.my_view);
myButton = findViewById(R.id.my_button);
// initialize as invisible (could also do in xml)
myView.setVisibility(View.INVISIBLE);
myButton.setText("Slide up");
isUp = false;
}
// slide the view from below itself to the current position
public void slideUp(View view){
view.setVisibility(View.VISIBLE);
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
view.getHeight(), // fromYDelta
0); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
// slide the view from its current position to below itself
public void slideDown(View view){
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
view.getHeight()); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
public void onSlideViewButtonClick(View view) {
if (isUp) {
slideDown(myView);
myButton.setText("Slide up");
} else {
slideUp(myView);
myButton.setText("Slide down");
}
isUp = !isUp;
}
}
activity_mail.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.slideview.MainActivity">
<Button
android:id="@+id/my_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:onClick="onSlideViewButtonClick"
android:layout_width="150dp"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/my_view"
android:background="#a6e1aa"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="200dp">
</LinearLayout>
</RelativeLayout>
INVISIBLE
.INVISIBLE
. If you are not animating completely off screen, though, then you can add an alpha animation and set the visibility with an AnimatorListenerAdapter
.You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database
Taken from here:
The following command finds folders that are greater than 100 MB in size on the D: drive:
diruse /s /m /q:100 /d d:
The /s option causes subdirectories to be searched, the /m option displays disk usage in megabytes, the /q:100 option causes folders that are greater than 100 MB to be marked, and the /d option displays only folders that exceed the threshold specified by /q.
Use the diskuse command to find files over a certain size. The following command displays files over 100 MB in size on the D: drive:
diskuse D: /x:104857600 /v /s
The /x:104857600 option causes files over 104,857,600 bytes to be displayed and is valid only if you include the /v option (verbose). The /s option means subdirectories from the specified path (in this case, the D: drive) are searched.
Using VBScript
' This code finds all files over a certain size.
' ------ SCRIPT CONFIGURATION ------
strComputer = "**<ServerName>**"
intSizeBytes = 1024 * 1024 * 500 ' = 500 MB
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colFiles = objWMI.ExecQuery _
("Select * from CIM_DataFile where FileSize > '" & intSizeBytes & "'")
for each objFile in colFiles
Wscript.Echo objFile.Name & " " & objFile.Filesize / 1024 / 1024 & "MB"
next
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
0
\u0000
or 0
0.0
false
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
For a quick n' dirty self-signed cert, you can also use flask run --cert adhoc
or set the FLASK_RUN_CERT
env var.
$ export FLASK_APP="app.py"
$ export FLASK_ENV=development
$ export FLASK_RUN_CERT=adhoc
$ flask run
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 329-665-000
The adhoc
option isn't well documented (for good reason, never do this in production), but it's mentioned in the cli.py source code.
There's a thorough explanation of this by Miguel Grinberg at Running Your Flask Application Over HTTPS.
A primary use case for a DTO is in returning data from a web service. In this instance, POCO and DTO are equivalent. Any behavior in the POCO would be removed when it is returned from a web service, so it doesn't really matter whether or not it has behavior.
For basic out of the box python with bs4 installed then you can process your xml with
soup = BeautifulSoup(html, "html5lib")
If however you want to use formatter='xml' then you need to
pip3 install lxml
soup = BeautifulSoup(html, features="xml")
before PHP 5.3
session_register("name");
since PHP 5.3
$_SESSION['name'] = $name;
You can check whether object
contains attribute by using hasattr
builtin method.
For an instance if your object is a
and you want to check for attribute stuff
>>> class a:
... stuff = "something"
...
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False
The method signature itself is hasattr(object, name) -> bool
which mean if object
has attribute which is passed to second argument in hasattr
than it gives boolean True
or False
according to the presence of name
attribute in object.
For this you can use .9 Patch Image and just simply set it in to background.
android:background="@drawable/spin"
Here i'll give you .9patch image. try with this.
Right click on image and click Save Image as
set image name like this : anyname.9.png and hit save.
Enjoy.. Happy Coading. :)
I couldn't find any good information on this, so I did some trial and error. The following attributes and fields (and only these) are recognized by Jenkins (v1.585).
<?xml version="1.0" encoding="UTF-8"?>
<testsuite>
<!-- if your classname does not include a dot, the package defaults to "(root)" -->
<testcase name="my testcase" classname="my package.my classname" time="29">
<!-- If the test didn't pass, specify ONE of the following 3 cases -->
<!-- option 1 --> <skipped />
<!-- option 2 --> <failure message="my failure message">my stack trace</failure>
<!-- option 3 --> <error message="my error message">my crash report</error>
<system-out>my STDOUT dump</system-out>
<system-err>my STDERR dump</system-err>
</testcase>
</testsuite>
(I started with this sample XML document and worked backwards from there.)
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<a href="index.html"><button>Cancel changes</button></a>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered. I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"[email protected]",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
The actual Apple reference documentation is quite comprehensive
Scroll down until you see this part
Since the aggregates string can be longer than 4000 bytes, you can't use the LISTAGG
function. You could potentially create a user-defined aggregate function that returns a CLOB
rather than a VARCHAR2
. There is an example of a user-defined aggregate that returns a CLOB
in the original askTom discussion that Tim links to from that first discussion.
You can use user defined comparator class.
class comparator
{
int x;
bool operator()( const comparator &m, const comparator &n )
{
return m.x<n.x;
}
}
Try \r\n
in place of \n
The difference between \n and \r\n
It should be noted that this is applicable to line returns in emails. For other scenarios, please refer to rokjarc's answer.
I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.
String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";
SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);
Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);
This worked. Thanks.
Simply put all the images thumbnails inside a row/col divs like this:
<div class="row text-center">
<div class="col-12">
# your images here...
</div>
</div>
and everything will work fine!
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException
to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1
(where Length
is total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can't use Array.Length
for both dimension, you have to use Array.GetLength()
:
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color
. Each item represents a pixel, indices are from (0, 0)
to (imageWidth - 1, imageHeight - 1)
.
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]
:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException
for this code (for example if you're using GetPixel
method on a Bitmap
class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>()
, this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don't forget that valid indices are from 0
to Length - 1
. If you simply try to assign an item at Length
you'll get IndexOutOfRangeException
(this behavior may confuse you if you think they may increase with a syntax similar to Insert
method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray
will satisfy search condition because Array.IndexOf()
will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum
.
How it applies to List<T>
?
Same cases as array - range of valid indexes - 0 (List
's indexes always start with 0) to list.Count
- accessing elements outside of this range will cause the exception.
Note that List<T>
throws ArgumentOutOfRangeException
for the same cases where arrays use IndexOutOfRangeException
.
Unlike arrays, List<T>
starts empty - so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>
) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you're trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString()
will throw IndexOutOfRangeException
because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader
implementations (SqlDataReader
, OleDbDataReader
and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".
Others
There is another (documented) case when this exception is thrown: if, in DataView
, data column name being supplied to the DataViewSort
property is not valid.
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0
with GetLowerBound(0)
and .Length
with GetUpperBound(0)
(of course if you have parameters of type System.Arra
y, it doesn't apply for T[]
). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it'll throw InvalidCastException
), that's why if your parameters are T[]
you're safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException
or ArgumentOutOfRangeException
). In the next example, wrong parameters may cause IndexOutOfRangeException
, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if
logic with Debug.Assert()
:
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert()
, throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf()
return value. If we know it may fail then it's better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:
array[index] = newValue;
You found your error, check how index
increases. Is it right? Check how array is allocated, is coherent with how index
increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.
If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
Use the replace()
method on string:
>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'
ANSI encoding is a slightly generic term used to refer to the standard code page on a system, usually Windows. It is more properly referred to as Windows-1252 on Western/U.S. systems. (It can represent certain other Windows code pages on other systems.) This is essentially an extension of the ASCII character set in that it includes all the ASCII characters with an additional 128 character codes. This difference is due to the fact that "ANSI" encoding is 8-bit rather than 7-bit as ASCII is (ASCII is almost always encoded nowadays as 8-bit bytes with the MSB set to 0). See the article for an explanation of why this encoding is usually referred to as ANSI.
The name "ANSI" is a misnomer, since it doesn't correspond to any actual ANSI standard, but the name has stuck. ANSI is not the same as UTF-8.
Almost everyone I've seen expressing an opinion prefers
if (foo)
{
}
Indeed, I've seen many people criticize the explicit comparison, and I may even have done so myself before now. I'd say the "short" style is idiomatic.
EDIT:
Note that this doesn't mean that line of code is always incorrect. Consider:
bool? maybeFoo = GetSomeNullableBooleanValue();
if (maybeFoo == true)
{
...
}
That will compile, but without the "== true" it won't, as there's no implicit conversion from bool?
to bool
.
The array will be initialized to false when you allocate it.
All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.
You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?
If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.
You could use a more generic converter
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}
And in the XAML-Part you use:
<Grid>
<Grid.Resources>
<l:EnumBooleanConverter x:Key="enumBooleanConverter" />
</Grid.Resources>
<StackPanel >
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
</StackPanel>
</Grid>
Try using replaceWith()
or replaceAll()
There are some very optimal ways to implement the algorithm. But if you don't know much about maths and you simply follow the definition of prime as the requirement: a number that is only divisible by 1 and by itself (and nothing else), here's a simple to understand code for positive numbers.
public bool IsPrime(int candidateNumber)
{
int fromNumber = 2;
int toNumber = candidateNumber - 1;
while(fromNumber <= toNumber)
{
bool isDivisible = candidateNumber % fromNumber == 0;
if (isDivisible)
{
return false;
}
fromNumber++;
}
return true;
}
Since every number is divisible by 1 and by itself, we start checking from 2 onwards until the number immediately before itself. That's the basic reasoning.
You probably have a forward declaration of the class, but haven't included the header:
#include <sstream>
//...
QString Stats_Manager::convertInt(int num)
{
std::stringstream ss; // <-- also note namespace qualification
ss << num;
return ss.str();
}
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
First Way:
In Kotlin we can create a simple extension for view:
fun View.getLocationOnScreen(): Point
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return Point(location[0],location[1])
}
And simply get coordinates:
val location = yourView.getLocationOnScreen()
val absX = location.x
val absY = location.y
Second Way:
The Second way is more simple :
fun View.absX(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[0]
}
fun View.absY(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[1]
}
and simply get absolute X by view.absX()
and Y by view.absY()
Yes you can add text inside <span>
and override css. jsfiddle
html:
<h1>**This text should be bold**, <span>but this text should not</span><h1>
css:
span{
font-weight: normal;
}
In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?
Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:
myLog = function() {
var _div = null;
this.toJson = function(obj) {
if (typeof window.uneval == 'function') { return uneval(obj); }
if (typeof obj == 'object') {
if (!obj) { return 'null'; }
var list = [];
if (obj instanceof Array) {
for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
return '[' + list.join(',') + ']';
} else {
for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
return '{' + list.join(',') + '}';
}
} else if (typeof obj == 'string') {
return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
} else {
return new String(obj);
}
};
this.createDiv = function() {
myLog._div = document.body.appendChild(document.createElement('div'));
var props = {
position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333',
color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
fontSize: '11px', whiteSpace: 'nowrap'
}
for (var key in props) { myLog._div.style[key] = props[key]; }
};
if (!myLog._div) { this.createDiv(); }
var logEntry = document.createElement('span');
for (var i=0; i < arguments.length; i++) {
logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
}
logEntry.innerHTML += '<br />';
myLog._div.appendChild(logEntry);
// Scroll automatically to the bottom
myLog._div.scrollTop = myLog._div.scrollHeight;
}
Why not go even simpler with either one of these options:
$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Or, if you want to append it to existing content:
$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
Note: I put the id="myid"
right into the HTML string rather than using separate code to set it.
Both the .html()
and .append()
jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.
Try to do something like this:
db.getCollection('collectionName').find({'ArrayName.1': {$exists: true}})
1 is number, if you want to fetch record greater than 50 then do ArrayName.50 Thanks.
The FileNameExtensionFilter
class is intended for Swing to be used in a JFileChooser
.
Try using a FilenameFilter
instead. For example:
File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
tldr:
docker image inspect myimage:mytag
By way of demonstration...
success, found image:
$ docker image pull busybox:latest
latest: Pulling from library/busybox
Digest: sha256:32f093055929dbc23dec4d03e09dfe971f5973a9ca5cf059cbfb644c206aa83f
Status: Image is up to date for busybox:latest
$ docker image inspect busybox:latest >/dev/null 2>&1 && echo yes || echo no
yes
failure, missing image:
$ docker image rm busybox:latest
Untagged: busybox:latest
Untagged: busybox@sha256:32f093055929dbc23dec4d03e09dfe971f5973a9ca5cf059cbfb644c206aa83f
$ docker image inspect busybox:latest >/dev/null 2>&1 && echo yes || echo no
no
Reference:
https://docs.docker.com/engine/reference/commandline/image_inspect/
logrotate -d [your_config_file]
invokes debug mode, giving you a verbose description of what would happen, but leaving the log files untouched.
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
You have to access lists a little differently than arrays in Java. See the javadocs for the List
interface for more information.
playersList.get(0)
However if you want to find the smallest element in playersList
, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.
For example:
int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
if (playersList.get(i) < playersList.get(smallestIndex))
smallestIndex = i;
}
playersList.get(smallestIndex);
The above code will find the smallest element in O(n)
instead of O(n log n)
time.
I needed to copy all .md files from one directory into another, so here is what I did.
for i in **/*.md;do mkdir -p ../docs/"$i" && rm -r ../docs/"$i" && cp "$i" "../docs/$i" && echo "$i -> ../docs/$i"; done
Which is pretty hard to read, so lets break it down.
first cd into the directory with your files,
for i in **/*.md;
for each file in your pattern
mkdir -p ../docs/"$i"
make that directory in a docs folder outside of folder containing your files. Which creates an extra folder with the same name as that file.
rm -r ../docs/"$i"
remove the extra folder that is created as a result of mkdir -p
cp "$i" "../docs/$i"
Copy the actual file
echo "$i -> ../docs/$i"
Echo what you did
; done
Live happily ever after
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:
CATALINA_OPTS='-Xms512m -Xmx1024m'
My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.
Solved the problem with:
sudo chown -R $USER:$USER /var/www/folder-name
sudo chmod -R 755 /var/www
Grant permissions
There's no need to use jQuery to change the title. Try:
document.title = "blarg";
See this question for more details.
To dynamically change on button click:
$(selectorForMyButton).click(function(){
document.title = "blarg";
});
To dynamically change in loop, try:
var counter = 0;
var titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
To string the two together so that it dynamically changes on button click, in a loop:
var counter = 0;
$(selectorForMyButton).click(function(){
titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
});
Here, this api allows you to get fb, google and twitter profile pics easily
It's an API that returns the profile image when given a username for a variety of social networks including Twitter, Facebook, Instagram, and gravatar. It has libraries for iOS, Android, Ruby, Node, PHP, Python, and JavaScript.
Would Activity.onWindowFocusChanged(boolean hasFocus)
be useful here? That, plus a class-level flag, something like isFocused
that onWindowFocusChanged
sets, would be an easy way to tell at any point in your activity if it is focused or not. From reading the docs, it looks like it would properly set "false" in any situation where the activity isn't directly in the physical "foreground", like if a dialog is being displayed or the notification tray is pulled down.
Example:
boolean isFocused;
@Override
void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
isFocused = hasFocus;
}
void someMethod() {
if (isFocused) {
// The activity is the foremost object on the screen
} else {
// The activity is obscured or otherwise not visible
}
}
You want to enclose it with a scrollView
.
prkey whatsthat cash
890 "abb " 32 32
43 "abbz " 2 34
4 "bttu " 1 35
45 "gasstuff " 2 37
545 "gasz " 5 42
80009 "hoo " 9 51
2321 "ibm " 1 52
998 "krk " 2 54
42 "kx-5010 " 2 56
32 "lto " 4 60
543 "mp " 5 65
465 "multipower " 2 67
455 "O.N. " 1 68
7887 "prem " 7 75
434 "puma " 3 78
23 "retractble " 3 81
242 "Trujillo's stuff " 4 85
That's a result of query. Table used as source is the same exept that it has no last column. This column is a moving sum of third one.
Query:
SELECT prkey,whatsthat,cash,SUM(cash) over (order by whatsthat)
FROM public.iuk order by whatsthat,prkey
;
(table goes as public.iuk)
sql version: 2012
It's a little over dbase(1986) level, I don't know why 25+ years has been needed to finish it up.
Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.
Read this article to know more about Collection Types: Swift Programming Language
count()
function works with array. But if you want to count object's length then you can use this method.
$total = $obj->length;
An update to the iOS Developer Agreement means that you can use whatever you like, as long as you meet the developer guidelines. Section 3.3.1, which restricted what developers could use for iOS development, has been entirely removed.
Source: http://daringfireball.net/2010/09/app_store_guidelines
You can use System.IO.Path.GetFileName
to do this.
E.g.,
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
Console.WriteLine(Path.GetFileName(file));
While you could use FileInfo
, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles
unless you need the additional functionality of the FileInfo
class.
if u cant use " export " cmd
then Just use:
setenv path /dir
like this
setenv ORACLE_HOME /data/u01/apps/oracle/11.2.0.3.0
Are you sure that this is a bottleneck? Have you done any performance analysis?
Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.
Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.
Debugging inside IPython
Cell Example:
%%debug
...: for n in range(4):
...: n>2
IPython inside debugging
pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
breakpoint()
, python -m ipdb
, etc.I agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.
https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68
See also Is it possible to run commands in IPython with debugging?
J2EE traditionally referred to products and standards released by Sun. For example if you were developing a standard J2EE web application, you would be using EJBs, Java Server Faces, and running in an application server that supports the J2EE standard. However since there is such a huge open source plethora of libraries and products that do the same jobs as well as (and many will argue better) then these Sun offerings, the day to day meaning of J2EE has migrated into referring to these as well (For instance a Spring/Tomcat/Hibernate solution) in many minds.
This is a great book in my opinion that discusses the 'open source' approach to J2EE http://www.theserverside.com/tt/articles/article.tss?l=J2EEWithoutEJB_BookReview
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work. Inside my servlet to do GET using url like e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
On CYGwin, you can install this as a typical package in the first screen. Look for
libssl-devel
You need to unzip it and check its META-INF/MANIFEST.MF
file, e.g.
unzip -p file.jar | head
or more specific:
unzip -p file.jar META-INF/MANIFEST.MF
In my case, it wasn't due to image caching (Used SDWebImage). It was because of custom cell's tag mismatch with indexPath.row.
On cellForRowAtIndexPath :
1) Assign an index value to your custom cell. For instance,
cell.tag = indexPath.row
2) On main thread, before assigning the image, check if the image belongs the corresponding cell by matching it with the tag.
dispatch_async(dispatch_get_main_queue(), ^{
if(cell.tag == indexPath.row) {
UIImage *tmpImage = [[UIImage alloc] initWithData:imgData];
thumbnailImageView.image = tmpImage;
}});
});
Line from above answer:
HtmlDocument doc = new HtmlDocument();
This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument
any more.
Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb
and check out this link for some sample code.
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
The dplyr
select
function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by
function. For example:
library(dplyr)
# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))
# Return the distinct values of x
dat %>%
group_by(x) %>%
summarise()
x
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
If you want to change the column name you can add the following:
dat %>%
group_by(x) %>%
summarise() %>%
select(unique.x=x)
This both selects column x
from among all the columns in the data frame that dplyr
returns (and of course there's only one column in this case) and changes its name to unique.x
.
You can also get the unique values directly in base R
with unique(dat$x)
.
If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE),
y=sample(letters[1:5], 100, replace=TRUE))
dat %>%
group_by(x,y) %>%
summarise() %>%
select(unique.x=x, unique.y=y)
BTW, Yandex Metrica also uses IDFA.
./Pods/YandexMobileMetrica/libYandexMobileMetrica.a
They say on their GitHub page that
"Starting from version 1.6.0 Yandex AppMetrica became also a tracking instrument and uses Apple idfa to attribute installs. Because of that during submitting your application to the AppStore you will be prompted with three checkboxes to state your intentions for idfa usage. As Yandex AppMetrica uses idfa for attributing app installations you need to select Attribute this app installation to a previously served advertisement."
So, I will try to select this checkbox and send my app without actually no any ads in it.
Generally
In jQuery
JSON strings are wrapped in double quotes; single quotes are not a valid substitute.
{"who": "Hello World"}
is valid but this is not...
{'who': 'Hello World'}
Whilst not the OP's issue, thought it worth noting for others who land here.
Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:
(function($) {
$.fn.getAttributes = function () {
var elem = this,
attr = {};
if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) {
n = n.nodeName||n.name;
v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
if(v != undefined && v !== false) attr[n] = v
})
return attr
}
})(jQuery);
Usage:
var attribs = $('#some_id').getAttributes();
try
ini_set('max_execution_time', $time);
$articles = Article::all();
where $time
is in seconds, set it to 0 for no time. make sure to make it 60 back after your function finish
You must specify the file to be downloaded (attachment) by the client in the http header:
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"
http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html
If you want to remove derived data manually just run:
rm -rf ~/Library/Developer/Xcode/DerivedData
If you want to free up more disk space there's a few other directories you might want to clear out as well though.
I have created a Bash script for removing all kinds of files generated by Xcode. Removing DerivedData content can be done by running:
./xcode-clean.sh -d
More info at https://github.com/niklasberglund/xcode-clean.sh
Use a timer. There are 3 basic kinds, each suited for different purposes.
Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.
When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.
This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.
For most cases, I recommend System.Timers.Timer.
$arr1 = array(
"0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
"1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
"2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
"3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
"4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
);
if you want to convert this array as following:
$arr2 = array(
"0" => array(
"0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
"1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
"2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
"3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
),
"1" => array(
"0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
)
);
so, my answer will be like this:
$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
{
$inner_array = array();
$fid_value = $value['fid'];
if(!in_array($value['fid'], $unique_array))
{
array_push($unique_array, $fid_value);
unset($value['fid']);
array_push($inner_array, $value);
$outer_array[$fid_value] = $inner_array;
}else{
unset($value['fid']);
array_push($outer_array[$fid_value], $value);
}
}
var_dump(array_values($outer_array));
hope this answer will help somebody sometime.
base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z
, a-z
, 0-9
, +
, /
* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.
Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b''
syntax.
If you remove the b
, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)
In your second example:
>>> encoded = base64.b64encode('data to be encoded')
All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with
>>> encoded = 'data to be encoded'.encode('ascii')
Or simpler:
>>> encoded = b'data to be encoded'
Which would be the same thing in this case.
* Most base64 flavours may also include a =
at the end as padding. In addition, some base64 variants may use characters other than +
and /
. See the Variants summary table at Wikipedia for an overview.
I would like to add some more suggestions based on my most recent implementation. I've looked at some code from Apple and I think my code behaves in much the same way.
The posts above already explain how to create NSError objects and return them, so I won't bother with that part. I'll just try to suggest a good way to integrate errors (codes, messages) in your own app.
I recommend creating 1 header that will be an overview of all the errors of your domain (i.e. app, library, etc..). My current header looks like this:
FSError.h
FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;
enum {
FSUserNotLoggedInError = 1000,
FSUserLogoutFailedError,
FSProfileParsingFailedError,
FSProfileBadLoginError,
FSFNIDParsingFailedError,
};
FSError.m
#import "FSError.h"
NSString *const FSMyAppErrorDomain = @"com.felis.myapp";
Now when using the above values for errors, Apple will create some basic standard error message for your app. An error could be created like the following:
+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
if (profileInfo)
{
/* ... lots of parsing code here ... */
if (profileInfo.username == nil)
{
*error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];
return nil;
}
}
return profileInfo;
}
The standard Apple-generated error message (error.localizedDescription
) for the above code will look like the following:
Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"
The above is already quite helpful for a developer, since the message displays the domain where the error occured and the corresponding error code. End users will have no clue what error code 1002
means though, so now we need to implement some nice messages for each code.
For the error messages we have to keep localisation in mind (even if we don't implement localized messages right away). I've used the following approach in my current project:
1) create a strings
file that will contain the errors. Strings files are easily localizable. The file could look like the following:
FSError.strings
"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."
2) Add macros to convert integer codes to localized error messages. I've used 2 macros in my Constants+Macros.h file. I always include this file in the prefix header (MyApp-Prefix.pch
) for convenience.
Constants+Macros.h
// error handling ...
#define FS_ERROR_KEY(code) [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code) NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)
3) Now it's easy to show a user friendly error message based on an error code. An example:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
This would work
setInterval(function(){$("#myButtonId").click();}, 1000);
I prefer to use exists
method:
RepairItem::find($id)->option()->exists()
to check if related model exists or not. It's working fine on Laravel 5.2
Follow these 3 steps :
- start postgres server -
sudo systemctl start postgresql
- enable same -
sudo systemctl enable postgresql
- restore command -
pg_restore -h localhost -p 5432 -U postgres -d old_db
assuming that the dump is there in the same directory
Links :
https://www.postgresqltutorial.com/postgresql-restore-database https://askubuntu.com/questions/50621/cannot-connect-to-postgresql-on-port-5432
One possible explanation is a database trigger that fires for each DROP TABLE
statement. To find the trigger, query the _TRIGGERS
dictionary views:
select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')
disable any suspicious trigger with
alter trigger <trigger_name> disable;
and try re-running your DROP TABLE
statement
VB Version (using port 9100 - tested on Zebra ZM400)
Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
Dim lAddress As Net.IPEndPoint
Dim lSocket As System.Net.Sockets.Socket = Nothing
Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
Dim lBytes As Byte()
Try
lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _ ProtocolType.Tcp)
lSocket.Connect(lAddress)
lNetStream = New NetworkStream(lSocket)
lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
lNetStream.Write(lBytes, 0, lBytes.Length)
Catch ex As Exception When Not App.Debugging
Msgbox ex.message & vbnewline & ex.tostring
Finally
If Not lNetStream Is Nothing Then
lNetStream.Close()
End If
If Not lSocket Is Nothing Then
lSocket.Close()
End If
End Try
End Sub
This has been driving me mad looking for a simple answer. Finally I made this function that seems to catch all input and give a good SQL string that is correct or at least valid and checkable. If it's 1999-12-31 it's probably wrong but won't throw a bad error in MySQL.
function MakeSQLDate($date) {
if (is_null($date)) {
//use 1999-12-31 as a valid date or as an alert
return date('Y-m-d', strtotime('1999-12-31'));
}
if (($t = strtotime($date)) === false) {
//use 1999-12-31 as a valid date or as an alert
return date('Y-m-d', strtotime('1999-12-31'));
} else {
return date('Y-m-d H:i:s', strtotime($date));
}
}
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
I got this answer from here. and its works for me
Require local
Change to
Require all granted
Order Deny,Allow
Allow from all
your code used in python2.x, you can use like this:
from urllib.request import urlopen
urlopen(url)
by the way, suggest another module called requests
is more friendly to use, you can use pip
install it, and use like this:
import requests
requests.get(url)
requests.post(url)
I thought it is easily to use, i am beginner too....hahah
It appears to be relate to the graphics driver. In the emulator configuration, changing Emulated Graphics to Software - GLES 2.0
caused the crashes to stop.
Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).
{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>
To get the fragment instance in a class that extends FragmentActivity:
MyclassFragment instanceFragment=
(MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);
To get the fragment instance in a class that extends Fragment:
MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition
The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)
Code::where(function ($query) {
$query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');
})->get();
ExPanDaR’s package function prepare_missing_values_graph
can be used to explore panel data:
I think you were planning to use Angular template reference variable based on your html template.
// in html
<input #nameInput type="text" class="form-control" placeholder=''/>
// in add-player.ts file
import { OnInit, ViewChild, ElementRef } from '@angular/core';
export class AddPlayerComponent implements OnInit {
@ViewChild('nameInput') nameInput: ElementRef;
constructor() { }
ngOnInit() { }
addPlayer() {
// you can access the input value via the following syntax.
console.log('player name: ', this.nameInput.nativeElement.value);
}
}
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
After reading the posts above, I decided to use this code:
itemModel.findOne({'pid':obj.pid},function(e,r){
if(r!=null)
{
itemModel.update({'pid':obj.pid},obj,{upsert:true},cb);
}
else
{
var item=new itemModel(obj);
item.save(cb);
}
});
if r is null, we create new item. Otherwise, use upsert in update because update does not create new item.
Check your git repo before committing
gitrepo/.git/hooks/commit-msg
if this file is not present in that location then you will get this error "missing Change-Id in commit message" .
To solve this just copy paste the commit hook in .git folder.
You can use boolean indexing
:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
A Sales
0 3 10
1 4 20
2 7 30
3 6 40
4 1 50
s = 30
df1 = df[df['Sales'] >= s]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
df2 = df[df['Sales'] < s]
print (df2)
A Sales
0 3 10
1 4 20
It's also possible to invert mask
by ~
:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
print (df2)
A Sales
0 3 10
1 4 20
print (mask)
0 False
1 False
2 True
3 True
4 True
Name: Sales, dtype: bool
print (~mask)
0 True
1 True
2 False
3 False
4 False
Name: Sales, dtype: bool
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Well, it might help someone. I was stupid enough to put var_dump('testing');
in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json
response, and with dataType
set to json
defined, the request fails.
====== store =====_x000D_
import Vue from 'vue'_x000D_
import Vuex from 'vuex'_x000D_
import axios from 'axios'_x000D_
_x000D_
Vue.use(Vuex)_x000D_
_x000D_
export default new Vuex.Store({_x000D_
state: {_x000D_
showRegisterLoginPage: true,_x000D_
user: null,_x000D_
allitem: null,_x000D_
productShow: null,_x000D_
userCart: null_x000D_
},_x000D_
mutations: {_x000D_
SET_USERS(state, payload) {_x000D_
state.user = payload_x000D_
},_x000D_
HIDE_LOGIN(state) {_x000D_
state.showRegisterLoginPage = false_x000D_
},_x000D_
SHOW_LOGIN(state) {_x000D_
state.showRegisterLoginPage = true_x000D_
},_x000D_
SET_ALLITEM(state, payload) {_x000D_
state.allitem = payload_x000D_
},_x000D_
SET_PRODUCTSHOW(state, payload) {_x000D_
state.productShow = payload_x000D_
},_x000D_
SET_USERCART(state, payload) {_x000D_
state.userCart = payload_x000D_
}_x000D_
},_x000D_
actions: {_x000D_
getUserLogin({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/users',_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_USERS', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
addItem({ dispatch }, payload) {_x000D_
let formData = new FormData()_x000D_
formData.append('name', payload.name)_x000D_
formData.append('file', payload.file)_x000D_
formData.append('category', payload.category)_x000D_
formData.append('price', payload.price)_x000D_
formData.append('stock', payload.stock)_x000D_
formData.append('description', payload.description)_x000D_
axios({_x000D_
method: 'post',_x000D_
url: 'http://localhost:3000/products',_x000D_
data: formData,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log('data hasbeen created ', data)_x000D_
dispatch('getAllItem')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
getAllItem({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/products'_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_ALLITEM', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
addUserCart({ dispatch }, { payload, productId }) {_x000D_
let newCart = {_x000D_
count: payload_x000D_
}_x000D_
// console.log('ini dari store nya', productId)_x000D_
_x000D_
axios({_x000D_
method: 'post',_x000D_
url: `http://localhost:3000/transactions/${productId}`,_x000D_
data: newCart,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
dispatch('getUserCart')_x000D_
// console.log('cart hasbeen added ', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
getUserCart({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/transactions/user',_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_USERCART', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
cartCheckout({ commit, dispatch }, transactionId) {_x000D_
let count = null_x000D_
axios({_x000D_
method: 'post',_x000D_
url: `http://localhost:3000/transactions/checkout/${transactionId}`,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
},_x000D_
data: {_x000D_
sesuatu: 'sesuatu'_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
count = data.count_x000D_
console.log(count, data)_x000D_
_x000D_
dispatch('getUserCart')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
deleteTransactions({ dispatch }, transactionId) {_x000D_
axios({_x000D_
method: 'delete',_x000D_
url: `http://localhost:3000/transactions/${transactionId}`,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
console.log('success delete')_x000D_
_x000D_
dispatch('getUserCart')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
}_x000D_
},_x000D_
modules: {}_x000D_
})
_x000D_
The best way now is to use the "Quit" button that is just to the left of the "Logout" button. I have to admit that I do not understand the utility of the Logout button. However, I am glad that they have added the exceedingly useful Quit button.
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
Id be inclined to create classes that match the structure and add an instance to a collection then serialise and deserialise the collection to load and save the document.
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
I had the same problem;
textStatus = 'error'
errorThrown = (empty)
xhr.status = 0
That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)
I have tried calling it this way also:
var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
but without success.
This post solved it for me: jQuery AJAX cross domain
This question is some years old but i came via a duplicate to it. I want to suggest a more general solution too. If you know you always have a fixed number of ancestors you can use some self joins as already suggested in the answers. If you want a generic approach go on reading.
What you need here is called Quotient in relational Algebra. The Quotient is more or less the reversal of the Cartesian Product (or Cross Join in SQL).
Let's say your ancestor set A
is (i use a table notation here, i think this is better for understanding)
ancestry
-----------
'England'
'France'
'Germany'
and your user set U
is
user_id
--------
1
2
3
The cartesian product C=AxU
is then:
user_id | ancestry
---------+-----------
1 | 'England'
1 | 'France'
1 | 'Germany'
2 | 'England'
2 | 'France'
2 | 'Germany'
3 | 'England'
3 | 'France'
3 | 'Germany'
If you calculate the set quotient U=C/A
then you get
user_id
--------
1
2
3
If you redo the cartesian product UXA
you will get C
again. But note that for a set T
, (T/A)xA
will not necessarily reproduce T
. For example, if T
is
user_id | ancestry
---------+-----------
1 | 'England'
1 | 'France'
1 | 'Germany'
2 | 'England'
2 | 'France'
then (T/A)
is
user_id
--------
1
(T/A)xA
will then be
user_id | ancestry
---------+------------
1 | 'England'
1 | 'France'
1 | 'Germany'
Note that the records for user_id=2
have been eliminated by the Quotient and Cartesian Product operations.
Your question is: Which user_id has ancestors from all countries in your ancestor set? In other words you want U=T/A
where T
is your original set (or your table).
To implement the quotient in SQL you have to do 4 steps:
So let's do it step by step. I will use TSQL syntax (Microsoft SQL server) but it should easily be adaptable to other DBMS. As a name for the table (user_id, ancestry)
i choose ancestor
CREATE TABLE ancestry_set (ancestry nvarchar(25))
INSERT INTO ancestry_set (ancestry) VALUES ('England')
INSERT INTO ancestry_set (ancestry) VALUES ('France')
INSERT INTO ancestry_set (ancestry) VALUES ('Germany')
CREATE TABLE ancestor ([user_id] int, ancestry nvarchar(25))
INSERT INTO ancestor ([user_id],ancestry) VALUES (1,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(1,'Ireland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(2,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Poland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'Germany')
1) Create the Cartesian Product of your ancestry set and the set of all user_ids.
SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry
2) Find all records in the Cartesian Product which have no partner in the original set (Left Join) and
3) Extract the user_ids from the resultset of 2)
SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry) cp
LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null
4) Return all user_ids from the original set which are not included in the result set of 3)
SELECT DISTINCT [user_id]
FROM ancestor
WHERE [user_id] NOT IN (
SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry) cp
LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null
)
I use WinMerge. It is free and works pretty well (works for files and directories).
Try this code, I get working fine.
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
SELECT SUBSTRING(subject, 1, 10) FROM tbl
Would this do?
var selected = [];
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this).attr('name'));
}
});
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
Here's the link that gives me the answer:
[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip
[Modify] the php.ini file to use it (commented out the other lines): [mail function] ; For Win32 only. ; SMTP = smtp.gmail.com ; smtp_port = 25 ; For Win32 only. ; sendmail_from = <e-mail username>@gmail.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(ignore the "Unix only" bit, since we actually are using sendmail)
You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:
[sendmail] smtp_server=smtp.gmail.com smtp_port=25 error_logfile=error.log debug_logfile=debug.log auth_username=<username> auth_password=<password> force_sender=<e-mail username>@gmail.com
To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)
To achieve this you can try below steps:
I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:
.dropdown-menu li {
position: relative;
}
I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).
Here is the full less/css change (replace the above with this):
.dropdown-menu li {
position: relative;
[class^="icon-"] {
float: right;
}
&:hover {
// Switch to white icons on hover
[class^="icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
}
}
Add the following property:
.c{
...
overflow: hidden;
}
This will force the container to respect the height of all elements within it, regardless of floating elements.
http://jsfiddle.net/gtdfY/3/
Recently, I was working on a project that required this trick, but needed to allow overflow to show, so instead, you can use a pseudo-element to clear your floats, effectively achieving the same effect while allowing overflow on all elements.
.c:after{
clear: both;
content: "";
display: block;
}
git rm -r .
git checkout HEAD~3 .
git commit
After the commit, files in the new HEAD
will be the same as they were in the revision HEAD~3
.
You could also try fetching the db using root explorer app. And if that does not work then you can try this:
adb shell
'su
chmod 777 /data /data/data /data/data/com.application.package /data/data/com.application.package/*
After this you should be able to browse the files on the rooted device.
table
{
table-layout:fixed;
}
td,th
{
width:20px;
word-wrap:break-word;
}
:first-child ... :nth-child(1) or ...
let toSort = {a:2323, b: 14, c: 799}
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1])
Output:
[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]
An OutputStream
is one where you write data to. If some module exposes an OutputStream
, the expectation is that there is something reading at the other end.
Something that exposes an InputStream
, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.
So it is possible to connect an InputStream
to an OutputStream
InputStream----read---> intermediateBytes[n] ----write----> OutputStream
As someone metioned, this is what the copy()
method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense
UPDATE:
Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped
input/ouput streams, but there is another possibility.
If the output stream that is exposed is a ByteArrayOutputStream
, then you can always get the full contents by calling the toByteArray()
method. Then you can create an input stream wrapper by using the ByteArrayInputStream
sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
This error occurs because the transaction log becomes full due to LOG_BACKUP. Therefore, you can’t perform any action on this database, and In this case, the SQL Server Database Engine will raise a 9002 error.
To solve this issue you should do the following
I wrote an article with all details regarding this error and how to solve it at The transaction log for database ‘SharePoint_Config’ is full due to LOG_BACKUP
What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient
request.
At worst, it won't work.
function isEmpty(val){
return !val;
}
but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:
if(!val)...
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.