Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:
It is also possible to change the default username "user" and the default password "live".
I tried the username user
and password live
and it did work. If you want to run commands as root you can preface each command with sudo
You can use this
@echo off
for /F %%i in ('dir /b "c:\test directory\*.*"') do (
echo Folder is NON empty
goto :EOF
)
echo Folder is empty or does not exist
Taken from here.
That should do what you need.
Updated:
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
That .toggle()
method was removed from jQuery in version 1.9. You can do this instead:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').slideToggle("fast");
});
});
Demo: http://jsfiddle.net/APA2S/1/
...but as with the code in your question that would slide up or down. To slide left or right you can do the following:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').toggle("slide");
});
});
Demo: http://jsfiddle.net/APA2S/2/
Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.
Editing the path of the keystore file solved my problem.
Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:
buttonName.performClick();
if we have multiple databases and we need to select all tables for a particular database we can use TABLE_SCHEMA
to define database name as:
select table_name from information_schema.tables where TABLE_SCHEMA='dbname';
This query should work for you:
SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
If you're OK with "random" but entirely predictable license plates, you can use a linear-feedback shift register to choose the next plate number - it's guaranteed to go through every number before repeating. However, without some complex math, you won't be able to go through every 8 character alphanumeric string (you'll get 2^41 out of the 36^8 (78%) possible plates). To make this fill your space better, you could exclude a letter from the plates (maybe O), giving you 97%.
1.1 ls
It will show you default location.
1.2 CD "C:\Users\user\Desktop\HTML" We need to assign project path
1.3 git init It will initialize the empty git repository in C:\Users\user\Desktop\HTML
1.4 ls It will list all files name
1.5 git remote add origin https://github.com/repository/test.git it is your https://github.com/repository/test.git is your repository path
1.6 git remote -v To check weather we have fetch or push permisson or not
1.7 git add . If you put . then it mean whatever we have in perticular folder publish all.
1.8 git commit -m "First time"
1.9 git push -u origin master
Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :
javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);
That's all! Now you can visit any website, and click that button in BOOKMARK BAR!
The above method sends data using XMLHttpRequest
method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:
javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0);
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
Go to SETTINGS->Location and Security-> Device Administrator and deselect the admin which you want to uninstall.
Now uninstall the application. If it still says you need to deactivate the application before uninstalling, you may need to Force Stop the application before uninstalling.
Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example .
The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command.
And that's it. You have a bidirectional link between the two process.
Using this example you can test you the application by sending all kind of data, and see if it works correctly.
Also, you can always symlink the device, so you don't need to re-compile the application you are testing.
try using HttpClient as Sephy said:
public String getHtml(String url) {
HttpClient vClient = new DefaultHttpClient();
HttpGet vGet = new HttpGet(url);
String response = "";
try {
ResponseHandler<String> vHandler = new BasicResponseHandler();
response = vClient.execute(vGet, vHandler);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
Another way to do that is:
var extScope;
var app = angular.module('myApp', []);
app.controller('myController',function($scope, $http){
extScope = $scope;
})
//below you do what you want to do with $scope as extScope
extScope.$apply(function(){
extScope.test = 'Hello world';
})
Before using v-html
, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.
More info here: https://vuejs.org/v2/guide/security.html
I highly encourage you that instead of using v-html
to use this npm package
Use theme():
d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))
The following worked for me:
The interface consist of you logic methods plus additional identity method:
public interface MyService {
String getType();
void checkStatus();
}
Some implementations:
@Component
public class MyServiceOne implements MyService {
@Override
public String getType() {
return "one";
}
@Override
public void checkStatus() {
// Your code
}
}
@Component
public class MyServiceTwo implements MyService {
@Override
public String getType() {
return "two";
}
@Override
public void checkStatus() {
// Your code
}
}
@Component
public class MyServiceThree implements MyService {
@Override
public String getType() {
return "three";
}
@Override
public void checkStatus() {
// Your code
}
}
And the factory itself as following:
@Service
public class MyServiceFactory {
@Autowired
private List<MyService> services;
private static final Map<String, MyService> myServiceCache = new HashMap<>();
@PostConstruct
public void initMyServiceCache() {
for(MyService service : services) {
myServiceCache.put(service.getType(), service);
}
}
public static MyService getService(String type) {
MyService service = myServiceCache.get(type);
if(service == null) throw new RuntimeException("Unknown service type: " + type);
return service;
}
}
I've found such implementation easier, cleaner and much more extensible. Adding new MyService is as easy as creating another spring bean implementing same interface without making any changes in other places.
Class.getResources
would retrieve the resource by the classloader which load the object. While ClassLoader.getResource
would retrieve the resource using the classloader specified.
It should wait until get request completed. After that I'll return get request body from where function is called.
function foo() {
var jqXHR = $.ajax({
url: url,
type: 'GET',
async: false,
});
return JSON.parse(jqXHR.responseText);
}
Use underscore js or lodash,
var arrObj = [
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}
];
arrObj = _.sortBy(arrObj,"updated_at");
_.sortBy()
returns a new array
refer http://underscorejs.org/#sortBy and lodash docs https://lodash.com/docs#sortBy
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.
https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5
From the commit:
This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like
edit/color/:color/largecode/*largecode
will match with something like thishttp://appdomain.com/edit/color/brown/largecode/code/with/slashs
.
I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
a picture is worth a thousand words
public void reverse(){
if(isEmpty()){
return;
}
Node<T> revHead = new Node<T>();
this.reverse(head.next, revHead);
this.head = revHead;
}
private Node<T> reverse(Node<T> node, Node<T> revHead){
if(node.next == null){
revHead.next = node;
return node;
}
Node<T> reverse = this.reverse(node.next, revHead);
reverse.next = node;
node.next = null;
return node;
}
It's not necessary to cast both of them. Result datatype for a division is always the one with the higher data type precedence. Thus the solution must be:
SELECT CAST(1 AS float) / 3
or
SELECT 1 / CAST(3 AS float)
To install Docker for Mac with homebrew:
brew cask install docker
To install the command line completion:
brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
We can also set the vertical alignment with using this way
$style_cell = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
)
);
with this cell set the vertically aligned into the middle.
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
I found a complete solution for this question. (I've tested this in Chrome 27 and Firefox 21).
There are two things to know:
For Firefox 21, 'Save password' is triggered when it detects that there is a form containing input text field and input password field is submitted. So we just need to use
$('#loginButton').click(someFunctionForLogin);
$('#loginForm').submit(function(event){event.preventDefault();});
someFunctionForLogin()
does the ajax login and reload/redirect to the signed in page while event.preventDefault()
blocks the original redirection due to submitting the form.
If you deal with Firefox only, the above solution is enough but it doesn't work in Chrome 27. Then you will ask how to trigger 'Save password' in Chrome 27.
For Chrome 27, 'Save password' is triggered after it is redirected to the page by submitting the form which contains input text field with attribute name='username' and input password field with attribute name='password'. Therefore, we cannot block the redirection due to submitting the form but we can make the redirection after we've done the ajax login. (If you want the ajax login not to reload the page or not to redirect to a page, unfortunately, my solution doesn't work.) Then, we can use
<form id='loginForm' action='signedIn.xxx' method='post'>
<input type='text' name='username'>
<input type='password' name='password'>
<button id='loginButton' type='button'>Login</button>
</form>
<script>
$('#loginButton').click(someFunctionForLogin);
function someFunctionForLogin(){
if(/*ajax login success*/) {
$('#loginForm').submit();
}
else {
//do something to show login fail(e.g. display fail messages)
}
}
</script>
Button with type='button' will make the form not to be submitted when the button is clicked.
Then, binding a function to the button for ajax login. Finally, calling $('#loginForm').submit();
redirects to the signed-in page. If the signed-in page is current page, then you can replace 'signedIn.xxx' by current page to make the 'refresh'.
Now, you will find that the method for Chrome 27 also works in Firefox 21. So it is better to use it.
If you already have the loginForm hard-coded as HTML, then you will found no problem to restore the saved password in the loginForm.
However, the saved username/password will not be bind to the loginForm if you use js/jquery to make the loginForm dynamically, because the saved username/password is bind only when the document loads.
Therefore, you needed to hard-code the loginForm as HTML and use js/jquery to move/show/hide the loginForm dynamically.
Remark:
If you do the ajax login, do not add autocomplete='off'
in tag form like
<form id='loginForm' action='signedIn.xxx' autocomplete='off'>
autocomplete='off'
will make the restoring username/password into the loginForm fails because you do not allow it 'autocompletes' the username/password.
As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:
if (!window.location.hash) {
window.location.href = window.location.href;
} else {
window.location.reload();
}
Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:
<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>
Goodluck!
Backticks (`
) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.
Features:
Note: we can easily use single quotes ('
) and double quotes ("
) inside the backticks (`
).
Example:
var nameStr = `I'm "Rohit" Jindal`;
To interpolate the variables or expression we can use the ${expression}
notation for that.
var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal
Multi-line strings means that you no longer have to use \n
for new lines anymore.
Example:
const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);
Output:
Hello Rohit!
How are you?
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
ArrayList files = new ArrayList();
foreach (string ext in exts)
files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());
use this code in teminal :
python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME
for example i want update pip pakage :
python -m pip install --upgrade pip
more example :
python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...
Stacked by this issue and have resolved it in 2020, in Windows 10. I'm using Java 8 RE and 14.1 JDK and it worked well until Eclipse upgrade to version 2020-09. After that I can't run Eclipse because it needed to use Java 11 or newer and it found only 8 version. It was because of order of environment variables of "Path":
I suppose C:\Program Files (x86)\Common Files\Oracle\Java\javapath
is path to link to installed JRE exe files (in my case Java 8) and the issue was resolved by move down this link after %JAVA_HOME%
, what leads to Java 14.1/bin folder.
It seems that order of environment variables affects order of searched folders while executable file is requested. Thanks for your comment or better explanation.
Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful.
Have you tried the match()
or charmatch()
functions?
Example use:
match(c("A1", "A9", "A6"), myfile$Letter)
You need to use document.getElementById()
in line 3.
If you try this right now in the console:
var img = document.createElement("img");_x000D_
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";_x000D_
var src = document.getElementById("header");_x000D_
src.appendChild(img);
_x000D_
<div id="header"></div>
_x000D_
... you'd get this:
try out this if you want to assign value to object and it is showing this error in angular..
crate object in construtor
this.modelObj = new Model();
//<---------- after declaring object above
By the way, VB, having the same underlying architecture, allows much more flexible Select Case
statements (the above code would work in VB) and still produces efficient code where this is possible so the argument by techical constraint has to be considered carefully.
Replace options with this snippet, will fix for Vanilla JavaScript Developers
options: {
title: {
text: 'Hello',
display: true
},
scales: {
xAxes: [{
ticks: {
display: false
}
}]
},
legend: {
display: false
}
}
_x000D_
That'd be .delay()
.
If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.
You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all
Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.
There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request
in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:
import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text)
some_elements = soup.find_all("div", class_="myCssClass")
Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.
When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:
from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)
I would advice to start your own solution. You'll understand Scrapy's benefits doing so.
ps: take a look at scrapely: https://github.com/scrapy/scrapely
pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia
Another solution I ran across tonight, which worked for my needs, was to add box-sizing
attributes:
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
These attributes force the border to be part of the box model's width and height and correct the issue as well.
According to caniuse.com » box-sizing, box-sizing
is supported in IE8+.
If you're using LESS or Sass there is a Bootstrap mixin for this.
LESS:
.box-sizing(border-box);
Sass:
@include box-sizing(border-box);
You can use
android:ellipsize="marquee"
with your textview.
But remember to put focus on the desired textview.
I had the same problem. The thing is. The selected item doesnt know which object it should use from the collection. So you have to say to the selected item to use the item from the collection.
public MyObject SelectedObject
{
get
{
Objects.find(x => x.id == _selectedObject.id)
return _selectedObject;
}
set
{
_selectedObject = value;
}
}
I hope this helps.
What you're looking for is setattr
I believe.
Use this to set an attribute on an object.
>>> def printme(s): print repr(s)
>>> class A: pass
>>> setattr(A,'printme',printme)
>>> a = A()
>>> a.printme() # s becomes the implicit 'self' variable
< __ main __ . A instance at 0xABCDEFG>
On Ubuntu 14.04 none of these suggestions worked. Postfix would override with the logged in system user as the sender. What worked was the following solution listed at this link --> Change outgoing mail address from root@servername - rackspace sendgrid postfix
STEPS:
1) Make sure this is set in /etc/postfix/main.cf:
smtp_generic_maps = hash:/etc/postfix/generic
2) echo 'www-data [email protected]' >> /etc/postfix/generic
3) sudo postmap /etc/postfix/generic
4) sudo service postfix restart
Try this:
skill -KILL -v pts/6
skill -KILL -v pts/9
skill -KILL -v pts/10
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
In bootstrap 4 is easiest.
You can use the classes:
bg-transparent
and border-0
You can also do:
return InternalServerError(new Exception("SOME CUSTOM MESSAGE"));
Error:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
String cannot be returned by size()
size() should return int
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception might occur in wrongly written multi-threaded
tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to
stub spies -
- with doReturn|Throw() family of methods. More in javadocs for
Mockito.spy() method.
Actual Code:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Object.class, ByteString.class})
@Mock
private ByteString mockByteString;
String testData = “dsfgdshf”;
PowerMockito.when(mockByteString.toStringUtf8()).thenReturn(testData);
// throws above given exception
Solution to fix this issue:
1st Remove annotation “@Mock”.
private ByteString mockByteString;
2nd Add PowerMockito.mock
mockByteString = PowerMockito.mock(ByteString.class);
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
You can use:
msiexec /i "c:\package.msi"
You can also add some more optional parameters. There are common msi parameters and parameters which are specific for your installer. For common parameters just call msiexec
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
Can be pretty easily done assuming you're using jQuery and css3:
HTML:
<div id="clicker">Click Here</div>
<div id="rotating"></div>
CSS:
#clicker {
width: 100px;
height: 100px;
background-color: Green;
}
#rotating {
width: 100px;
height: 100px;
background-color: Red;
margin-top: 50px;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.rotated {
transform:rotate(25deg);
-webkit-transform:rotate(25deg);
-moz-transform:rotate(25deg);
-o-transform:rotate(25deg);
}
JS:
$(document).ready(function() {
$('#clicker').click(function() {
$('#rotating').toggleClass('rotated');
});
});
I used ng-click
directive to call a function, while requesting route templateUrl, to decide which <div>
has to be show
or hide
inside route templateUrl page or for different scenarios.
AngularJS 1.6.9
Lets see an example, when in routing page, I need either the add <div>
or the edit <div>
, which I control using the parent controller models $scope.addProduct
and $scope.editProduct
boolean.
RoutingTesting.html
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Testing</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>_x000D_
<script>_x000D_
var app = angular.module("MyApp", ["ngRoute"]);_x000D_
_x000D_
app.config(function($routeProvider){_x000D_
$routeProvider_x000D_
.when("/TestingPage", {_x000D_
templateUrl: "TestingPage.html"_x000D_
});_x000D_
});_x000D_
_x000D_
app.controller("HomeController", function($scope, $location){_x000D_
_x000D_
$scope.init = function(){_x000D_
$scope.addProduct = false;_x000D_
$scope.editProduct = false;_x000D_
}_x000D_
_x000D_
$scope.productOperation = function(operationType, productId){_x000D_
$scope.addProduct = false;_x000D_
$scope.editProduct = false;_x000D_
_x000D_
if(operationType === "add"){_x000D_
$scope.addProduct = true;_x000D_
console.log("Add productOperation requested...");_x000D_
}else if(operationType === "edit"){_x000D_
$scope.editProduct = true;_x000D_
console.log("Edit productOperation requested : " + productId);_x000D_
}_x000D_
_x000D_
//*************** VERY IMPORTANT NOTE ***************_x000D_
//comment this $location.path("..."); line, when using <a> anchor tags,_x000D_
//only useful when <a> below given are commented, and using <input> controls_x000D_
$location.path("TestingPage");_x000D_
};_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body ng-app="MyApp" ng-controller="HomeController">_x000D_
_x000D_
<div ng-init="init()">_x000D_
_x000D_
<!-- Either use <a>anchor tag or input type=button -->_x000D_
_x000D_
<!--<a href="#!TestingPage" ng-click="productOperation('add', -1)">Add Product</a>-->_x000D_
<!--<br><br>-->_x000D_
<!--<a href="#!TestingPage" ng-click="productOperation('edit', 10)">Edit Product</a>-->_x000D_
_x000D_
<input type="button" ng-click="productOperation('add', -1)" value="Add Product"/>_x000D_
<br><br>_x000D_
<input type="button" ng-click="productOperation('edit', 10)" value="Edit Product"/>_x000D_
<pre>addProduct : {{addProduct}}</pre>_x000D_
<pre>editProduct : {{editProduct}}</pre>_x000D_
<ng-view></ng-view>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
TestingPage.html
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Title</title>_x000D_
<style>_x000D_
.productOperation{_x000D_
position:fixed;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width:30em;_x000D_
height:18em;_x000D_
margin-left: -15em; /*set to a negative number 1/2 of your width*/_x000D_
margin-top: -9em; /*set to a negative number 1/2 of your height*/_x000D_
border: 1px solid #ccc;_x000D_
background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="productOperation" >_x000D_
_x000D_
<div ng-show="addProduct">_x000D_
<h2 >Add Product enabled</h2>_x000D_
</div>_x000D_
_x000D_
<div ng-show="editProduct">_x000D_
<h2>Edit Product enabled</h2>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
both pages -
RoutingTesting.html
(parent), TestingPage.html
(routing page) are in the same directory,
Hope this will help someone.
Just because you declare your struct B
inside class A
does not mean that an instance of class A
automatically has the properties of struct B
as members, nor does it mean that it automatically has an instance of struct B
as a member.
There is no true relation between the two classes (A
and B
), besides scoping.
struct A {
struct B {
int v;
};
B inner_object;
};
int
main (int argc, char *argv[]) {
A object;
object.inner_object.v = 123;
}
You could start by using git merge --no-commit
, and then edit the merge however you like i.e. by unstaging config.xml
or any other file, then commit. I suspect you'd want to automate it further after that using hooks, but I think it'd be worth going through manually at least once.
Try to remove ib_logfile0
and ib_logfile1
files and then run mysql again
rm /usr/local/var/mysql/ib_logfile0
rm /usr/local/var/mysql/ib_logfile1
It works for me.
I suspect you don't actually have that problem - I suspect you've really got:
double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0
// Now cast
int b = (int) a;
// Now a is 3668
What makes me say that is that although it's true that many decimal values cannot be stored exactly in float
or double
, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)
I strongly suspect that your double
value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.
Assuming your double
type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly
3668.99999999999954525264911353588104248046875
So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.
ACID are desirable properties of any transaction processing engine.
A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.
But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).
Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:
Use the form Initialize event, e.g.:
Private Sub UserForm_Initialize()
TextBox1.Value = Format(Date, "mm/dd/yyyy")
End Sub
You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
From the JavaDocs
setOpaque
public void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds. Otherwise,
the component may not paint some or all of its pixels, allowing the underlying
pixels to show through.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
I had these choices:
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
+ 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
3 /home/ec2-user/local/java/jre1.7.0_25/bin/java
When I chose 3, it didn't work. When I chose 2, it did work.
jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:
$("a.directions-link").attr("href", function(i, href) {
return href + '?q=testing';
});
That loops over all the elements too, so no need for $.each
I hit this page trying to pad hexadecimal values when I realized that DEC2HEX()
provides that very feature for free.
You just need to add a second parameter. For example, tying to turn 12
into 0C
DEC2HEX(12,2)
=> 0C
DEC2HEX(12,4)
=> 000C
... and so on
Use set -e
#!/bin/bash
set -e
/bin/command-that-fails
/bin/command-that-fails2
The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run.
If you were to check the return status of every single command, your script would look like this:
#!/bin/bash
# I'm assuming you're using make
cd /project-dir
make
if [[ $? -ne 0 ]] ; then
exit 1
fi
cd /project-dir2
make
if [[ $? -ne 0 ]] ; then
exit 1
fi
With set -e it would look like:
#!/bin/bash
set -e
cd /project-dir
make
cd /project-dir2
make
Any command that fails will cause the entire script to fail and return an exit status you can check with $?. If your script is very long or you're building a lot of stuff it's going to get pretty ugly if you add return status checks everywhere.
This did the trick for me (I still was on the master branch):
git reset --hard origin/master
Failed to open stream error occurs because the given path is wrong such as:
$uploadedFile->saveAs(Yii::app()->request->baseUrl.'/images/'.$model->user_photo);
It will give an error if the images folder will not allow you to store images, be sure your folder is readable
Try this:
<?php
# Init the MySQL Connection
if( !( $db = mysql_connect( 'localhost' , 'root' , '' ) ) )
die( 'Failed to connect to MySQL Database Server - #'.mysql_errno().': '.mysql_error();
if( !mysql_select_db( 'ram' ) )
die( 'Connected to Server, but Failed to Connect to Database - #'.mysql_errno().': '.mysql_error();
# Prepare the INSERT Query
$insertTPL = 'INSERT INTO `name` VALUES( "%s" , "%s" , "%s" , "%s" )';
$insertSQL = sprintf( $insertTPL ,
mysql_real_escape_string( $name ) ,
mysql_real_escape_string( $add1 ) ,
mysql_real_escape_string( $add2 ) ,
mysql_real_escape_string( $mail ) );
# Execute the INSERT Query
if( !( $insertRes = mysql_query( $insertSQL ) ) ){
echo '<p>Insert of Row into Database Failed - #'.mysql_errno().': '.mysql_error().'</p>';
}else{
echo '<p>Person\'s Information Inserted</p>'
}
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `names`';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead>
<tr>
<th>Name</th>
<th>Address Line 1</th>
<th>Address Line 2</th>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr><td>{$row['name']}</td><td>{$row['addr1']}</td><td>{$row['addr2']}</td><td>{$row['mail']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
}
?>
Your initial solution did not show any obvious santisation of the values before passing them into the Database. This is how SQL Injection attacks (or even un-intentional errors being passed through SQL) occur. Don't do it!
Your database does not seem to have a Primary Key. Whilst these are not, technically, necessary in all usage, they are a good practice, and make for a much more reliable way of referring to a specific row in a table, whether for adding related tables, or for making changes within that table.
You need to check every action, at every stage, for errors. Most PHP functions are nice enough to have a response they will return under an error condition. It is your job to check for those conditions as you go - never assume that PHP will do what you expect, how you expect, and in the order you expect. This is how accident happen...
My provided code above contains alot of points where, if an error has occured, a message will be returned. Try it, see if any error messages are reported, look at the Error Message, and, if applicable, the Error Code returned and do some research.
Good luck.
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
I always have to look this one up time and time again, so here is my answer.
Suppose we have a heavy duty class (which we want to mock):
In [1]: class HeavyDuty(object):
...: def __init__(self):
...: import time
...: time.sleep(2) # <- Spends a lot of time here
...:
...: def do_work(self, arg1, arg2):
...: print("Called with %r and %r" % (arg1, arg2))
...:
here is some code that uses two instances of the HeavyDuty
class:
In [2]: def heavy_work():
...: hd1 = HeavyDuty()
...: hd1.do_work(13, 17)
...: hd2 = HeavyDuty()
...: hd2.do_work(23, 29)
...:
Now, here is a test case for the heavy_work
function:
In [3]: from unittest.mock import patch, call
...: def test_heavy_work():
...: expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
...:
...: with patch('__main__.HeavyDuty') as MockHeavyDuty:
...: heavy_work()
...: MockHeavyDuty.return_value.assert_has_calls(expected_calls)
...:
We are mocking the HeavyDuty
class with MockHeavyDuty
. To assert method calls coming from every HeavyDuty
instance we have to refer to MockHeavyDuty.return_value.assert_has_calls
, instead of MockHeavyDuty.assert_has_calls
. In addition, in the list of expected_calls
we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work
, as opposed to simply call
.
Exercising the test case shows us it is successful:
In [4]: print(test_heavy_work())
None
If we modify the heavy_work
function, the test fails and produces a helpful error message:
In [5]: def heavy_work():
...: hd1 = HeavyDuty()
...: hd1.do_work(113, 117) # <- call args are different
...: hd2 = HeavyDuty()
...: hd2.do_work(123, 129) # <- call args are different
...:
In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)
AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]
To contrast with the above, here is an example that shows how to mock multiple calls to a function:
In [7]: def work_function(arg1, arg2):
...: print("Called with args %r and %r" % (arg1, arg2))
In [8]: from unittest.mock import patch, call
...: def test_work_function():
...: expected_calls = [call(13, 17), call(23, 29)]
...: with patch('__main__.work_function') as mock_work_function:
...: work_function(13, 17)
...: work_function(23, 29)
...: mock_work_function.assert_has_calls(expected_calls)
...:
In [9]: print(test_work_function())
None
There are two main differences. The first one is that when mocking a function we setup our expected calls using call
, instead of using call.some_method
. The second one is that we call assert_has_calls
on mock_work_function
, instead of on mock_work_function.return_value
.
import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)
yields:
[[ 1. 1. 1.]
[ 2. 2. 2.]
[ 3. 3. 3.]]
WARNING: slaveOk() is deprecated and may be removed in the next major release. Please use secondaryOk() instead. rs.secondaryOk()
In windows server 2012, even after installing asp.net you might run into this issue.
Check for "Http activation" feature. This feature is present under Web services as well.
Make sure you add the above and everything should be awesome for you !!!
The following works as of now (tested in chrome and firefox):
<form onsubmit="event.preventDefault(); return validateMyForm();">
where validateMyForm() is a function that returns false
if validation fails. The key point is to use the name event
. We cannot use for e.g. e.preventDefault()
I've been using:
new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
Make sure your Activity extends FragmentActivity or AppCompatActivity
Java 8 implementation (List initialized with 60
zeroes):
List<Integer> list = IntStream.of(new int[60])
.boxed()
.collect(Collectors.toList());
new int[N]
- creates an array filled with zeroes & length N boxed()
- each element boxed to an Integercollect(Collectors.toList())
- collects elements of streamAll strings meant for humans should use u"".
I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u""
syntax. The ""
syntax is for byte arrays, only.
Before the bashing begins, let me explain. Most Python programs start out with using ""
for strings. But then they need to support documentation off the Internet, so they start using "".decode
and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of ""
for strings. In this case, Unicode does act like a virus and will wreak havoc.
But, if you follow my rule, you won't have this infection (because you will already be infected).
I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:
public class Test {
//Bypassing the SSL verification to execute our code successfully
static {
disableSSLVerification();
}
public static void main(String[] args) {
//Access HTTPS URL and do something
}
//Method used for bypassing SSL verification
public static void disableSSLVerification() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}
It worked for me. try it!!
It is very easy using removeAttr.
$(element).removeAttr("onclick");
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
To Post Rest/JSON Request
We can simply use request package and save the values we have to send in Json variable.
First install the require package in your console by npm install request --save
var request = require('request');
var options={
'key':'28',
'key1':'value',
'key2':'value'
}
request({
url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?
minorRev="+options.key+
"&cid="+options.key1+
"&apiKey="+options.key2,
method:"POST",
json:true},function(error,response,body){
console.log(body)
}
);
Use xsd:include to bring in an XSD from the same or no namespace.
Use xsd:import to bring in an XSD from a different namespace.
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Simple, for python 3.4 and above
print (type(variable_name))
Python 2.7 and above
print type(variable_name)
You can ping an address that doesn't exist and specify the desired timeout:
ping 192.0.2.2 -n 1 -w 10000 > nul
And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.
-w 10000
part specifies the desired timeout in milliseconds.-n 1
part tells ping that it should only try once (normally it'd try 4 times).> nul
part is appended so the ping command doesn't output anything to screen.You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:
rem SLEEP.BAT - sleeps by the supplied number of seconds
@ping 192.0.2.2 -n 1 -w %1000 > nul
NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:
192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.
Flow the flowing steps :
Edit your listener.ora and tnsnames.ora file in $Oracle_home\product\11.2.0\client_1\NETWORK\ADMIN location
a. add listener.ora file
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
)
)
ADR_BASE_LISTENER = C: [here c is oralce home directory]
b. add in tnsnames.ora file
SCHEMADEV =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = dabase_ip)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = SCHEMADEV)
)
)
Example :
username : your_database_username
password : Your_database_password
oracle_connection_alias : SCHEMADEV for above example.
Using delegates, the following code is able to provide reusability if you find yourself needing the nullable parsing for more than one structure type. I've shown both the .Parse() and .TryParse() versions here.
This is an example usage:
NullableParser.TryParseInt(ViewState["Id"] as string);
And here is the code that gets you there...
public class NullableParser
{
public delegate T ParseDelegate<T>(string input) where T : struct;
public delegate bool TryParseDelegate<T>(string input, out T outtie) where T : struct;
private static T? Parse<T>(string input, ParseDelegate<T> DelegateTheParse) where T : struct
{
if (string.IsNullOrEmpty(input)) return null;
return DelegateTheParse(input);
}
private static T? TryParse<T>(string input, TryParseDelegate<T> DelegateTheTryParse) where T : struct
{
T x;
if (DelegateTheTryParse(input, out x)) return x;
return null;
}
public static int? ParseInt(string input)
{
return Parse<int>(input, new ParseDelegate<int>(int.Parse));
}
public static int? TryParseInt(string input)
{
return TryParse<int>(input, new TryParseDelegate<int>(int.TryParse));
}
public static bool? TryParseBool(string input)
{
return TryParse<bool>(input, new TryParseDelegate<bool>(bool.TryParse));
}
public static DateTime? TryParseDateTime(string input)
{
return TryParse<DateTime>(input, new TryParseDelegate<DateTime>(DateTime.TryParse));
}
}
On MacOS when your are working on an iCloud drive, your $PWD will contain a directory "Mobile Documents". It does not seem to like the space!
As a workaround, I copied my project to local drive where there is no space in the path to my project folder.
I do not see a way you can get around changnig the default path to iCloud which is ~/Library/Mobile Documents/com~apple~CloudDocs
The space in the path in "Mobile Documents" seems to be what docker run does not like.
On Windows you can query the precise state of any port on any network-adapter using: GetExtendedTcpTable
You can filter it to only those related to your process, etc and do as you wish periodically monitoring as needed. This is "an alternative" approach.
You could also duplicate the socket handle and set up an IOCP/Overlapped i/o wait on the socket and monitor it that way as well.
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
OK, what you can try is
Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.
That should replace all blank cells in the USED range with NULL
I strongly suggest to use httrack.
ex: httrack -v -w http://example.com/
It will do a mirror with 8 simultaneous connections as default. Httrack has a tons of options where to play. Have a look.
Default options are read from the following files in the given order:
/etc/mysql/my.cnf
/etc/my.cnf
~/.my.cnf
For PowerShell versions less than 3.0:
The FileInfo
object returned by Get-ChildItem
has a "base" property, PSIsContainer
. You want to select only those items.
Get-ChildItem -Recurse | ?{ $_.PSIsContainer }
If you want the raw string names of the directories, you can do
Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
For PowerShell 3.0 and greater:
Get-ChildItem -Directory
You can also use the aliases dir
, ls
, and gci
A different point is that the first sentence is parsed as:
scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)
Whereas the second example is parsed as:
scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)
So if you are using macros, you should take care.
Besides, ++
for two lists is calling :::
but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.
Micro-Benchmarks after warming up.
scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46
As Daniel C. Sobrai said, you can append the content of any collection to a list using ++
, whereas with :::
you can only concatenate lists.
For Linux
Check you have installed latest version of chrome brwoser-> chromium-browser -version
If not, install latest version of chrome sudo apt-get install chromium-browser
get appropriate version of chrome driver from here
Unzip the chromedriver.zip
Move the file to /usr/bin
directory sudo mv chromedriver /usr/bin
Goto /usr/bin
directory cd /usr/bin
Now, you would need to run something like sudo chmod a+x chromedriver
to mark it executable.
finally you can execute the code.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com")
print driver.page_source.encode('utf-8')
driver.quit()
The skipping elements bug in this (code from above)
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)
var len = cells.length;
for(var i = len-1; i >-1; i--) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
It is not possible.
ObjectA.PropertyA.PropertyB
will fail if ObjectA
is null due to null dereferencing, which is an error.
if(ObjectA != null && ObjectA.PropertyA
... works due to short circuiting, ie ObjectA.PropertyA
will never be checked if ObjectA
is null
.
The first way you propose is the best and most clear with intent. If anything you could try to redesign without having to rely on so many nulls.
Activity
class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.
ActionBarActivity
was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.
AppCompatActivity
is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0'
in your Gradle file. I use it in API 10 and it works perfect.
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
If you want to put the environment for system-wide use you can do so with /etc/environment
file.
Could be solved in the declaration file (lib.d.ts) if TypeScript would define HTMLCollection instead of NodeList as a return type.
DOM4 also specifies this as the correct return type, but older DOM specifications are less clear.
What is Git:
"Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency"
Git is a distributed peer-peer version control system. Each node in the network is a peer, storing entire repositories which can also act as a multi-node distributed back-ups. There is no specific concept of a central server although nodes can be head-less or 'bare', taking on a role similar to the central server in centralised version control systems.
What is GitHub:
"GitHub is a web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features."
Github provides access control and several collaboration features such as wikis, task management, and bug tracking and feature requests for every project.
You do not need GitHub to use Git.
GitHub (and any other local, remote or hosted system) can all be peers in the same distributed versioned repositories within a single project.
Github allows you to:
I found the problem that was causing the HTTP error.
In the setFalse()
function that is triggered by the Save button my code was trying to submit the form that contained the button.
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
document.submitForm.submit();
when I remove the document.submitForm.submit();
it works:
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit()
@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!
I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.
private void ResizeListViewColumns(ListView lv)
{
foreach(ColumnHeader column in lv.Columns)
{
column.Width = -2;
}
}
The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView
.
function unique(arrayName)_x000D_
{_x000D_
var newArray=new Array();_x000D_
label: for(var i=0; i<arrayName.length;i++ )_x000D_
{ _x000D_
for(var j=0; j<newArray.length;j++ )_x000D_
{_x000D_
if(newArray[j]==arrayName[i]) _x000D_
continue label;_x000D_
}_x000D_
newArray[newArray.length] = arrayName[i];_x000D_
}_x000D_
return newArray;_x000D_
}_x000D_
_x000D_
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
var union = unique(arr1.concat(arr2));_x000D_
console.log(union);
_x000D_
You can see it by using -iv
$> curl -ivH "apikey:ad9ff3d36888957" --form "file=@/home/mar/workspace/images/8.jpg" --form "language=eng" --form "isOverlayRequired=true" https://api.ocr.space/Parse/Image
NPM
- Manages packages but doesn't make life easy executing any.NPX
- A tool for executing Node packages.
NPX
comes bundled withNPM
version5.2+
NPM
by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json
file.
When executables are installed via NPM packages, NPM links to them:
./node_modules/.bin/
directory.bin/
directory (e.g. /usr/local/bin
) on Linux or at %AppData%/npm
on Windows.One might install a package locally on a certain project:
npm install some-package
Now let's say you want NodeJS to execute that package from the command line:
$ some-package
The above will fail. Only globally installed packages can be executed by typing their name only.
To fix this, and have it run, you must type the local path:
$ ./node_modules/.bin/some-package
You can technically run a locally installed package by editing your packages.json
file and adding that package in the scripts
section:
{
"name": "whatever",
"version": "1.0.0",
"scripts": {
"some-package": "some-package"
}
}
Then run the script using npm run-script
(or npm run
):
npm run some-package
npx
will check whether <command>
exists in $PATH
, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package
all you need to do is type:
npx some-package
Another major advantage of npx
is the ability to execute a package which wasn't previously installed:
$ npx create-react-app my-app
The above example will generate a react
app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.
npx
command may be helpful in the script
section of a package.json
file,
when it is unwanted to define a dependency which might not be commonly used or any other reason:
"scripts": {
"start": "npx [email protected]",
"serve": "npx http-server"
}
Call with: npm run serve
If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}
map(&:name) takes an enumerable object (tags in your case) and runs the name method for each element/tag, outputting each returned value from the method.
It is a shorthand for
array.map { |element| element.name }
which returns the array of element(tag) names
Whenever a TypeInitializationException
is thrown, check all initialization logic of the type you are referring to for the first time in the statement where the exception is thrown - in your case: Logger
.
Initialization logic includes: the type's static constructor (which - if I didn't miss it - you do not have for Logger
) and field initialization.
Field initialization is pretty much "uncritical" in Logger
except for the following lines:
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_commonAppData
is null
at the point where Path.Combine(s_commonAppData, "XXXX");
is called. As far as I'm concerned, these initializations happen in the exact order you wrote them - so put s_commonAppData
up by at least two lines ;)
If you want to use SimpleDateFormat
, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat
, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat
is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
All you need to do is add android:theme="@style/Theme.AppCompat.Light"
to your application tag in the AndroidManifest.xml
file.
If you want to move files around and keep the csproj files up to date, the easiest way is to use a Visual Studio plugin like AnkhSVN. That will automatically commit both the move action (as an delete + add with history, because that's how Subversion works) and a change in the .csproj
Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
7 years passed and...
actually there's this new SQL Server 2016 feature that does exactly what you need.
It is called AT TIME ZONE and it converts date to a specified time zone considering DST (daylight saving time) changes.
More info here:
https://msdn.microsoft.com/en-us/library/mt612795.aspx
Hash maps are built-in in Python, they're called dictionaries:
streetno = {} #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar" #assign value to key "1"
Usage:
"1" in streetno #check if key "1" is in streetno
streetno["1"] #get the value from key "1"
See the documentation for more information, e.g. built-in methods and so on. They're great, and very common in Python programs (unsurprisingly).
If you cannot use TRUNCATE
(e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:
ALTER TABLE mytable AUTO_INCREMENT = 1
It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:
#!/usr/bin/perl
use strict;
use warnings;
my %sparse;
@sparse{0, 5, 23} = (1 .. 3);
print "there are ", scalar keys %sparse, " items in the sparse array\n",
map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;
The keys
function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.
You must also remember to use the delete
function to remove items from the sparse array (just setting their value to undef is not enough).
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
Just another idea:
>>> bin(6)[2:].zfill(8)
'00000110'
Shorter way via string interpolation (Python 3.6+):
>>> f'{6:08b}'
'00000110'
I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.
HTML/CSS Approach
If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div>
and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:
HTML
<div id="wrapper">
<div id="fixed">
[Fixed Content]
</div><!-- /fixed -->
<div id="scroller">
[Scrolling Content]
</div><!-- /scroller -->
</div><!-- /wrapper -->
CSS
#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }
JS
//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
//Determine the difference in widths between
//the wrapper and the scroller. This value is
//the width of the scroll bar (if any).
var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;
//Set the right offset
$('#fixed').css('right', offset + 'px');?
});
Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).
Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
rects = ax.patches
# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha) # Horizontally align label differently for
# positive and negative values.
plt.savefig("image.png")
I believe the syntax for this is /rev:<revisionNumber>
Documentation for this can be found here
double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);
TimeSpan.TotalMinutes: The total number of minutes represented by this instance.
First set position
of the parent DIV to relative
(specifying the offset, i.e. left
, top
etc. is not necessary) and then apply position: absolute
to the child DIV with the offset you want.
It's simple and should do the trick well.
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3)
+ "-"
+ Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");
C# Example Below:
string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();
A very simple way is to check if the child exists.
If a child does not have any child, the exist
command will return false.
IF EXIST %1\. (
echo %1 is a folder
) else (
echo %1 is a file
)
You may have some false negative if you don't have sufficient access right (I have not tested it).
For me just SET FOREIGN_KEY_CHECKS=0;
wasn't enough.
I was still having a com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
.
I had to add ALTER TABLE myTable DISABLE KEYS;
.
So:
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE myTable DISABLE KEYS;
DELETE FROM myTable;
ALTER TABLE myTable ENABLE KEYS;
SET FOREIGN_KEY_CHECKS=1;
This is the best way:
http://github.com/guides/completely-remove-a-file-from-all-revisions
Just be sure to backup the copies of the files first.
EDIT
The edit by Neon got unfortunately rejected during review.
See Neons post below, it might contain useful information!
E.g. to remove all *.gz
files accidentally committed into git repository:
$ du -sh .git ==> e.g. 100M
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch *.gz' HEAD
$ git push origin master --force
$ rm -rf .git/refs/original/
$ git reflog expire --expire=now --all
$ git gc --prune=now
$ git gc --aggressive --prune=now
That still didn't work for me? (I am currently at git version 1.7.6.1)
$ du -sh .git ==> e.g. 100M
Not sure why, since I only had ONE master branch. Anyways, I finally got my git repo truely cleaned up by pushing into a new empty and bare git repository, e.g.
$ git init --bare /path/to/newcleanrepo.git
$ git push /path/to/newcleanrepo.git master
$ du -sh /path/to/newcleanrepo.git ==> e.g. 5M
(yes!)
Then I clone that to a new directory and moved over it's .git folder into this one. e.g.
$ mv .git ../large_dot_git
$ git clone /path/to/newcleanrepo.git ../tmpdir
$ mv ../tmpdir/.git .
$ du -sh .git ==> e.g. 5M
(yeah! finally cleaned up!)
After verifying that all is well, then you can delete the ../large_dot_git
and ../tmpdir
directories (maybe in a couple weeks or month from now, just in case...)
You need spaces inside the [
and ]
brackets:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]
then
mkdir -p /home/mlzboy/b2c2/shared/db
fi
{ flex: 1, resizeMode: 'contain' }
worked for me. I didn't need the aspectRatio
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know:
I also fixed this issue by running
aspnet_regiis -i
using the visual studio command line tools as an administrator
There are several ways to do this, lets see them one by one:
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
_x000D_
console.log(myObject);
_x000D_
let myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
I had to use [\\]
or [/]
to be able to make this work, FYI.
awk '!/[\\]/' file > temp && mv temp file
and
awk '!/[/]/' file > temp && mv temp file
I was using awk to remove backlashes and forward slashes from a list.
Just a quick answer to run your container using:
docker exec -it <container name> /bin/bash
once the container is open:
cd ..
then
`cd etc`
and then you can
cat hosts
or:
apt-get update
apt-get vim
or any editor you like and open it in vim, here you can modify say your startup ip to 0.0.0.0
Here's a cute trick to deal with directories and make. Instead of using multiline strings, or "cd ;" on each command, define a simple chdir function as so:
CHDIR_SHELL := $(SHELL)
define chdir
$(eval _D=$(firstword $(1) $(@D)))
$(info $(MAKE): cd $(_D)) $(eval SHELL = cd $(_D); $(CHDIR_SHELL))
endef
Then all you have to do is call it in your rule as so:
all:
$(call chdir,some_dir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
You can even do the following:
some_dir/myTest:
$(call chdir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
A ready-to-use method:
/**
* Convert JSONArray to ArrayList<String>.
*
* @param jsonArray JSON array.
* @return String array.
*/
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) {
ArrayList<String> stringArray = new ArrayList<String>();
int arrayIndex;
JSONObject jsonArrayItem;
String jsonArrayItemKey;
for (
arrayIndex = 0;
arrayIndex < jsonArray.length();
arrayIndex++) {
try {
jsonArrayItem =
jsonArray.getJSONObject(
arrayIndex);
jsonArrayItemKey =
jsonArrayItem.getString(
"name");
stringArray.add(
jsonArrayItemKey);
} catch (JSONException e) {
e.printStackTrace();
}
}
return stringArray;
}
To clear the SQL window you can use:
clear screen;
which can also be shortened to
cl scr;
I would just mention that you can use the cat
command to concatenate the input files prior to piping them to markdown_py
which has the same effect as what pandoc
does with multiple input files coming in.
cat *.md | markdown_py > youroutputname.html
works pretty much the same as the pandoc example above for the Python version of Markdown on my Mac.
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.
The following code does what is required
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}
This solution does not apply to C#
For people who found this question via other languages, Javascript, Java, and D allows labeled breaks and continues:
outer: while(fn1())
{
while(fn2())
{
if(fn3()) continue outer;
if(fn4()) break outer;
}
}
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.
wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.
gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.
Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.
Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.
To create your filter, you'd call buttord as
fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
gpass=0.0, gstop=30.0)
The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.
Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:
BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib
MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)
Provided your arrays are not huge (see caveat below), you can use the push()
method of the array to which you wish to append values. push()
can take multiple parameters so you can use its apply()
method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat()
of adding elements to the array in place rather than creating a new array.
However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);
You might want to generalize this into a function:
function pushArray(arr, arr2) {
arr.push.apply(arr, arr2);
}
... or add it to Array
's prototype:
Array.prototype.pushArray = function(arr) {
this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);
... or emulate the original push()
method by allowing multiple parameters using the fact that concat()
, like push()
, allows multiple parameters:
Array.prototype.pushArray = function() {
this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);
Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:
Array.prototype.pushArray = function() {
var toPush = this.concat.apply([], arguments);
for (var i = 0, len = toPush.length; i < len; ++i) {
this.push(toPush[i]);
}
};
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
its a matter of speed. using the iterator accesses the elements faster. a similar question was answered here:
What's faster, iterating an STL vector with vector::iterator or with at()?
Edit: speed of access varies with each cpu and compiler
Here is a solution in php that:
Create a file like syncDirs.php
with this content:
<?php
foreach (new DirectoryIterator($argv[1]) as $f) {
if($f->isDot() || !$f->isDir()) continue;
mkdir($argv[2].'/'.$f->getFilename(), $f->getPerms());
chown($argv[2].'/'.$f->getFilename(), $f->getOwner());
chgrp($argv[2].'/'.$f->getFilename(), $f->getGroup());
}
Run it as user that has enough rights:
sudo php syncDirs.php /var/source /var/destination
Surprised to see no one mentioned more capable, interactive and easier to use alternatives.
Just two lines and you get:
interactivity,
smooth scale,
colors based on whole dataframe instead of individual columns,
column names & row indices on axes,
zooming in,
panning,
built-in one-click ability to save it as a PNG format,
auto-scaling,
comparison on hovering,
bubbles showing values so heatmap still looks good and you can see values wherever you want:
import plotly.express as px
fig = px.imshow(df.corr())
fig.show()
All the same functionality with a tad much hassle. But still worth it if you do not want to opt-in for plotly and still want all these things:
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)
p.rect(x="level_1", y="level_0", width=1, height=1,
source=data,
fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
ticker=BasicTicker(desired_num_ticks=len(colors)),
formatter=PrintfTickFormatter(format="%f"),
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
show(p)
It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.
This is another example using defined column/table names.
DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';
You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";_x000D_
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
Java 8's stream()
interface provides a great way to update a list in place.
To safely update items in the list, use map()
:
List<String> letters = new ArrayList<>();
// add stuff to list
letters = letters.stream().map(x -> "D").collect(Collectors.toList());
To safely remove items in place, use filter()
:
letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());
DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT @colsUpd = STUF ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
WHERE object_id = (
SELECT top 1 object_id
FROM sys.objects
WHERE name = ''+@TableNameTest+''
)
and name not in ('Action','Record_ID')
FOR XML PATH('')
), 1, 2, ''
) + ']'
Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)
There's a much better way to achieve your desired result, using SQL Server's analytic (or windowing) functions.
SELECT DISTINCT Date, MAX(Score) OVER(PARTITION BY Date) FROM ScoresTable
If you need more than just the date and max score combinations, you can use ranking functions, eg:
SELECT *
FROM ScoresTable t
JOIN (
SELECT
ScoreId,
ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Score DESC) AS [Rank]
FROM ScoresTable
) window ON window.ScoreId = p.ScoreId AND window.[Rank] = 1
You may want to use RANK() instead of ROW_NUMBER() if you want multiple records to be returned if they both share the same MAX(Score).
After the byte code (which is architecture neutral) has been generated by the Java compiler, the execution will be handled by the JVM (in Java). The byte code will be loaded in to JVM by the loader and then each byte instruction is interpreted.
When we need to call a method multiple times, we need to interpret the same code many times and this may take more time than is needed. So we have the JIT (just-in-time) compilers. When the byte has been is loaded in to JVM (its run time), the whole code will be compiled rather than interpreted, thus saving time.
JIT compilers works only during run time, so we do not have any binary output.
I liked this solution on GitHub.
It is a single hpp file and it uses the vector<byte> type for raw data unlike the accepted answer.
#pragma once
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdint>
namespace base64
{
inline static const char kEncodeLookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
inline static const char kPadCharacter = '=';
using byte = std::uint8_t;
inline std::string encode(const std::vector<byte>& input)
{
std::string encoded;
encoded.reserve(((input.size() / 3) + (input.size() % 3 > 0)) * 4);
std::uint32_t temp{};
auto it = input.begin();
for(std::size_t i = 0; i < input.size() / 3; ++i)
{
temp = (*it++) << 16;
temp += (*it++) << 8;
temp += (*it++);
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6 ]);
encoded.append(1, kEncodeLookup[(temp & 0x0000003F) ]);
}
switch(input.size() % 3)
{
case 1:
temp = (*it++) << 16;
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(2, kPadCharacter);
break;
case 2:
temp = (*it++) << 16;
temp += (*it++) << 8;
encoded.append(1, kEncodeLookup[(temp & 0x00FC0000) >> 18]);
encoded.append(1, kEncodeLookup[(temp & 0x0003F000) >> 12]);
encoded.append(1, kEncodeLookup[(temp & 0x00000FC0) >> 6 ]);
encoded.append(1, kPadCharacter);
break;
}
return encoded;
}
std::vector<byte> decode(const std::string& input)
{
if(input.length() % 4)
throw std::runtime_error("Invalid base64 length!");
std::size_t padding{};
if(input.length())
{
if(input[input.length() - 1] == kPadCharacter) padding++;
if(input[input.length() - 2] == kPadCharacter) padding++;
}
std::vector<byte> decoded;
decoded.reserve(((input.length() / 4) * 3) - padding);
std::uint32_t temp{};
auto it = input.begin();
while(it < input.end())
{
for(std::size_t i = 0; i < 4; ++i)
{
temp <<= 6;
if (*it >= 0x41 && *it <= 0x5A) temp |= *it - 0x41;
else if(*it >= 0x61 && *it <= 0x7A) temp |= *it - 0x47;
else if(*it >= 0x30 && *it <= 0x39) temp |= *it + 0x04;
else if(*it == 0x2B) temp |= 0x3E;
else if(*it == 0x2F) temp |= 0x3F;
else if(*it == kPadCharacter)
{
switch(input.end() - it)
{
case 1:
decoded.push_back((temp >> 16) & 0x000000FF);
decoded.push_back((temp >> 8 ) & 0x000000FF);
return decoded;
case 2:
decoded.push_back((temp >> 10) & 0x000000FF);
return decoded;
default:
throw std::runtime_error("Invalid padding in base64!");
}
}
else throw std::runtime_error("Invalid character in base64!");
++it;
}
decoded.push_back((temp >> 16) & 0x000000FF);
decoded.push_back((temp >> 8 ) & 0x000000FF);
decoded.push_back((temp ) & 0x000000FF);
}
return decoded;
}
}
Opera will soon start having builds available with gradient support, as well as other CSS features.
The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.
Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.
I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.
This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?
Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)
Moving to local folder is the quickest solution, nothing else worked for me esp because I was not admin on my system (can't edit registery etc), which is a typical case in a work environment.
Create a folder in C:\help drive, lets call it help and copy the files there and open.
Do not copy to mydocuments or anywhere else, those locations are usually on network drive in office setup and will not work.
iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.
Maybe you installed python from source. In this case, you can recompile python with tcl/tk supported.
/home/xxx/local/tcl-tk/
.# install tcl
wget -c https://prdownloads.sourceforge.net/tcl/tcl8.6.9-src.tar.gz
tar -xvzf tcl8.6.9-src.tar.gz
cd tcl8.6.9
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
# install tk
wget -c https://prdownloads.sourceforge.net/tcl/tk8.6.9.1-src.tar.gz
tar -xvzf tk8.6.9.1-src.tar.gz
cd tk8.6.9.1
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
# download the source code of python and decompress it first.
cd <your-python-src-dir>
./configure --prefix=/home/xxx/local/python \
--with-tcltk-includes=/home/xxx/local/tcl-tk/include \
--with-tcltk-libs=/home/xxx/local/tcl-tk/lib
make
make install
As I've always heard the terms used in a load-balancing scenario, they are interchangeable. Both mean that once a session is started, the same server serves all requests for that session.
The case of if abc == nil
is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil
and you can check if != nil
use the NSString
functions from foundation.
In case of String?
you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.
You were doing following but without "!". Hope this clears it.
From apple docs look at this:
let assumedString: String! = "An implicitly unwrapped optional string."
You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:
if assumedString != nil {
println(assumedString)
}
// prints "An implicitly unwrapped optional string."
If somebody is seeking to update data from one database to another no matter which table they are targeting, there must be some criteria to do it.
This one is better and clean for all levels:
UPDATE dbname1.content targetTable
LEFT JOIN dbname2.someothertable sourceTable ON
targetTable.compare_field= sourceTable.compare_field
SET
targetTable.col1 = sourceTable.cola,
targetTable.col2 = sourceTable.colb,
targetTable.col3 = sourceTable.colc,
targetTable.col4 = sourceTable.cold
Traaa! It works great!
With the above understanding, you can modify the set fields and "on" criteria to do your work. You can also perform the checks, then pull the data into the temp table(s) and then run the update using the above syntax replacing your table and column names.
Hope it works, if not let me know. I will write an exact query for you.
Just for information - if instead of an integer your required field is a single bit within a larger type, use the 'xor' operator instead:
int flags;
int flag_a = 0x01;
int flag_b = 0x02;
int flag_c = 0x04;
/* I want to flip 'flag_b' without touching 'flag_a' or 'flag_c' */
flags ^= flag_b;
/* I want to set 'flag_b' */
flags |= flag_b;
/* I want to clear (or 'reset') 'flag_b' */
flags &= ~flag_b;
/* I want to test 'flag_b' */
bool b_is_set = (flags & flag_b) != 0;
the repr
function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"
writing to a file is pretty standard stuff, like any other file write:
f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
The SQL:2003 standard changed some precedence rules so a JOIN statement takes precedence over a "comma" join. This can actually change the results of your query depending on how it is setup. This cause some problems for some people when MySQL 5.0.12 switched to adhering to the standard.
So in your example, your queries would work the same. But if you added a third table: SELECT ... FROM table1, table2 JOIN table3 ON ... WHERE ...
Prior to MySQL 5.0.12, table1 and table2 would be joined first, then table3. Now (5.0.12 and on), table2 and table3 are joined first, then table1. It doesn't always change the results, but it can and you may not even realize it.
I never use the "comma" syntax anymore, opting for your second example. It's a lot more readable anyway, the JOIN conditions are with the JOINs, not separated into a separate query section.
Depending on your browser, you may access to your local files. But this may not work for all the users of your app.
To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Once your file is loaded, you can retrieve the data using:
var jsonData = JSON.parse(theTextContentOfMyFile);
try this:
type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
var headers = XMLHttpRequest.getAllResponseHeaders();
}
This is a personal and situational choice. The important thing to remember is that the empty string and the number zero are conceptually distinct from null
.
In the case of a count
you probably always want some valid number (unless the count
is unknown or undefined), but in the case of strings, who knows? The empty string could mean something in your application. Or maybe it doesn't. That's up to you to decide.
Apache Commons Collections 4 has a partition method in the ListUtils
class. Here’s how it works:
import org.apache.commons.collections4.ListUtils;
...
int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
Thanks for sharing this, I used with 2.6.7 and following query just worked,
for all docs:
db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})
for single doc:
db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})
Traditionally, if you only want to change the variable in your terminal windows, set it in .bashrc
file, which is sourced each time a new terminal is opened. .profile
file is not sourced each time you open a new terminal.
See the difference between .profile and .bashrc in question: What's the difference between .bashrc, .bash_profile, and .environment?
.bashrc
should solve your problem. However, it is not the proper solution since you are using Ubuntu. See the relevant Ubuntu help page "Session-wide environment variables". Thus, no wonder that .profile
does not work for you. I use Ubuntu 12.04 and xfce. I set up my .profile
and it is simply not taking effect even if I log out and in. Similar experience here. So you may have to use .pam_environment
file and totally forget about .profile
, and .bashrc
. And NOTE that .pam_environment
is not a script file.
this solved my problem
android:adjustViewBounds="true"
android:scaleType="fitXY"
Top answers don't point to an even simpler and more flexible solution.
just place a
@TestPropertySource(properties=
{"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.example.FooAutoConfiguration"})
@SpringBootTest
public class MySpringTest {...}
annotation above your test class. This means other tests aren't affected by the current test's special case. If there is a configuration affecting most of your tests, then consider using the spring profile instead as the current top answer suggests.
Thanks to @skirsch for encouraging me to upgrade this from a comment to an answer.
It also happened to me
I use this code and it worked
require('events').EventEmitter.defaultMaxListeners = infinity;
Try it out. It may help
Thanks
If you don't want to make the const
data member in class static, You can initialize the const
data member using the constructor of the class.
For example:
class Example{
const int x;
public:
Example(int n);
};
Example::Example(int n):x(n){
}
if there are multiple const
data members in class you can use the following syntax to initialize the members:
Example::Example(int n, int z):x(n),someOtherConstVariable(z){}
Not my code, but I think it's pretty nicely written. It allows to check by the key as well as by the Object element itself and handles both the On Error method and iterating through all Collection elements.
https://danwagner.co/how-to-check-if-a-collection-contains-an-object/
I'll not copy the full explanation since it is available on the linked page. Solution itself copied in case the page eventually becomes unavailable in the future.
The doubt I have about the code is the overusage of GoTo in the first If block but that's easy to fix for anyone so I'm leaving the original code as it is.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT : Kollection, the collection we would like to examine
' : (Optional) Key, the Key we want to find in the collection
' : (Optional) Item, the Item we want to find in the collection
'OUTPUT : True if Key or Item is found, False if not
'SPECIAL CASE: If both Key and Item are missing, return False
Option Explicit
Public Function CollectionContains(Kollection As Collection, Optional Key As Variant, Optional Item As Variant) As Boolean
Dim strKey As String
Dim var As Variant
'First, investigate assuming a Key was provided
If Not IsMissing(Key) Then
strKey = CStr(Key)
'Handling errors is the strategy here
On Error Resume Next
CollectionContains = True
var = Kollection(strKey) '<~ this is where our (potential) error will occur
If Err.Number = 91 Then GoTo CheckForObject
If Err.Number = 5 Then GoTo NotFound
On Error GoTo 0
Exit Function
CheckForObject:
If IsObject(Kollection(strKey)) Then
CollectionContains = True
On Error GoTo 0
Exit Function
End If
NotFound:
CollectionContains = False
On Error GoTo 0
Exit Function
'If the Item was provided but the Key was not, then...
ElseIf Not IsMissing(Item) Then
CollectionContains = False '<~ assume that we will not find the item
'We have to loop through the collection and check each item against the passed-in Item
For Each var In Kollection
If var = Item Then
CollectionContains = True
Exit Function
End If
Next var
'Otherwise, no Key OR Item was provided, so we default to False
Else
CollectionContains = False
End If
End Function
In addition to all the other answers you received, I want to explain the unknown option -- o
error: Your command was
$ adb shell 'su -c mount -o rw,remount /system'
which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell
. However, su -c <cmd>
also needs you to quote the command with arguments it shall pass to the shell's -c
option. (YMMV depending on su
variants.) Therefore, you might want to try
$ adb shell 'su -c "mount -o rw,remount /system"'
(and potentially add the actual device listed in the output of mount | grep system
before the /system
arg – see the other answers.)
I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break
statement:
finished = False
while not finished:
... do something...
finished = evaluate_end_condition()
You can also force to table columns in table using force: true
, if you table is already exist.
example:
ActiveRecord::Schema.define(version: 20080906171750) do
create_table "authors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end