It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
For Windows 7 macros are stored at C:\Users\
Username
\AppData\Roaming\Notepad++\shortcuts.xml
.
$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
public interface IRepository
{
void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}
public class Repository : DbContext, IRepository
{
public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
{
Set<T>().Attach(obj);
propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
SaveChanges();
}
}
Microsoft's AntiXss library AntiXssEncoder Class in System.Web.dll has methods for this:
AntiXss.XmlEncode(string s)
AntiXss.XmlAttributeEncode(string s)
it has HTML as well:
AntiXss.HtmlEncode(string s)
AntiXss.HtmlAttributeEncode(string s)
You can do something like this, to handle the host key checking as well
import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")
The HTMLParser project (http://htmlparser.sourceforge.net/) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:
Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter =
new CssSelectorNodeFilter("DIV.targetClassName");
NodeList nodes = parser.parse(cssFilter);
Because the vertical-align
is set at baseline as default.
Use vertical-align:top
instead:
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align:top;
}
http://jsfiddle.net/Lighty_46/RHM5L/9/
Or as @f00644 said you could apply float
to the child elements as well.
This could be as simple as a template conflict. Revert to default template in System/Configuration/Design/Themes.
Tip for 1 website resizing the height. But you can change to 2 websites.
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).
This is worked for me
If your having .so file in armeabi then mention inside ndk that folder alone.
defaultConfig {
applicationId "com.xxx.yyy"
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
renderscriptTargetApi 26
renderscriptSupportModeEnabled true
ndk {
abiFilters "armeabi"
}
}
and then use this
android.useDeprecatedNdk=true;
in gradle.properties file
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
default_scope
This works for Rails 4+:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
For Rails 2.3, 3, you need this instead:
default_scope order('created_at DESC')
For Rails 2.x:
default_scope :order => 'created_at DESC'
Where created_at
is the field you want the default sorting to be done on.
Note: ASC is the code to use for Ascending and DESC is for descending (desc
, NOT dsc
!).
scope
Once you're used to that you can also use scope
:
class Book < ActiveRecord::Base
scope :confirmed, :conditions => { :confirmed => true }
scope :published, :conditions => { :published => true }
end
For Rails 2 you need named_scope
.
:published
scope gives you Book.published
instead of
Book.find(:published => true)
.
Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed
.
With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.
You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:
scope :recent_books, lambda
{ |since_when| where("created_at >= ?", since_when) }
# Note the `where` is making use of AREL syntax added in Rails 3.
Finally you can disable default scope with:
Book.with_exclusive_scope { find(:all) }
or even better:
Book.unscoped.all
which will disable any filter (conditions) or sort (order by).
Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+
So
... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end
but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!
In fact they are Class level methods as they operate on the 1 set of 'all' records.
Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }
.
As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where
's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where
selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published
where published
is a named scope.
In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.
It's quite simple actually if you're using PostgreSQL, just use distinct(columns)
(documentation).
Productorder.objects.all().distinct('category')
Note that this feature has been included in Django since 1.4
You could try this:
deptSelected(selected: { id: string; text: string }) {
console.log(selected) // Shows proper selection!
// This is how I am trying to set the value
this.form.controls['dept'].updateValue(selected.id);
}
For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue
method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.
Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.
In AngularJS2 I found a new way, maybe is just the same thing but in this new version :
import {Router, RouteConfig, ROUTER_DIRECTIVES, Location} from 'angular2/router';
(...)
constructor(private _router: Router, private _location: Location) {}
onSubmit() {
(...)
self._location.back();
}
After my function, I can see that my application is going to the previous page usgin location from angular2/router.
https://angular.io/docs/ts/latest/api/common/index/Location-class.html
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
If you are using an array (and purely an array), the lookup of "contains" is O(N)
, because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N)
with the overhead of the sort.
If this is something that is invoked repeatedly, place it in a function:
private boolean inArray(int[] array, int value)
{
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
return true;
}
}
return false;
}
I had the same problem during running tests with separate php.ini. I had to add these lines to my own php.ini file:
[PHP]
extension = mysqlnd.so
extension = pdo.so
extension = pdo_mysql.so
Notice: Exactly in this order
public class DummyViewModel : ViewModelBase
{
private bool isfocused= false;
public bool IsFocused
{
get
{
return isfocused;
}
set
{
isfocused= value;
OnPropertyChanged("IsFocused");
}
}
}
(You should you as Else-If
statement to check the for the three different state (positive, negative, 0)
Here is a simple example (excludes the possibility of non-integer values)
import java.util.Scanner;
public class Compare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is equal to zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
}
}
I would like to say that Microsoft LDAP has some special ways to search recursively for all of memberships of a user.
The Matching Rule you can specify for the "member" attribute. In particular, using the Microsoft Exclusive LDAP_MATCHING_RULE_IN_CHAIN rule for "member" attribute allows recursive/nested membership searching. The rule is used when you add it after the member attribute. Ex. (member:1.2.840.113556.1.4.1941:= XXXXX )
For the same Domain as the Account, The filter can use <SID=S-1-5-21-XXXXXXXXXXXXXXXXXXXXXXX> instead of an Accounts DistinguishedName attribute which is very handy to use cross domain if needed. HOWEVER it appears you need to use the ForeignSecurityPrincipal <GUID=YYYY> as it will not resolve your SID as it appears the <SID=> tag does not consider ForeignSecurityPrincipal object type. You can use the ForeignSecurityPrincipal DistinguishedName as well.
Using this knowledge, you can LDAP query those hard to get memberships, such as the "Domain Local" groups an Account is a member of but unless you looked at the members of the group, you wouldn't know if user was a member.
//Get Direct+Indirect Memberships of User (where SID is XXXXXX)
string str = "(& (objectCategory=group)(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";
//Get Direct+Indirect **Domain Local** Memberships of User (where SID is XXXXXX)
string str2 = "(& (objectCategory=group)(|(groupType=-2147483644)(groupType=4))(member:1.2.840.113556.1.4.1941:=<SID=XXXXXX>) )";
//TAA DAA
Feel free to try these LDAP queries after substituting the SID of a user you want to retrieve all group memberships of. I figure this is similiar if not the same query as what the PowerShell Command Get-ADPrincipalGroupMembership uses behind the scenes. The command states "If you want to search for local groups in another domain, use the ResourceContextServer parameter to specify the alternate server in the other domain."
If you are familiar enough with C# and Active Directory, you should know how to perform an LDAP search using the LDAP queries provided.
Additional Documentation:
Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).
You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.
If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L]
Where 000 000 000 000 should be replaced by your ip adress.
Source:
http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/
For system applications only!
Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();
Note: System applications don't need to run "su" to execute this command.
I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.
function renameCloneIdsAndNames( objClone ) {
if( !objClone.attr( 'data-row-id' ) ) {
console.error( 'Cloned object must have \'data-row-id\' attribute.' );
}
if( objClone.attr( 'id' ) ) {
objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
}
objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
objClone.find( '[id]' ).each( function() {
var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
$( this ).attr( 'id', strNewId );
if( $( this ).attr( 'name' ) ) {
var strNewName = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
strName = strName.replace( /[\[\]']+/g, '' );
var intNumber = parseInt( strName ) + 1;
return '[' + intNumber + ']'
} );
$( this ).attr( 'name', strNewName );
}
});
return objClone;
}
Use Number
from the numbers
module to test isinstance(n, Number)
(available since 2.6).
isinstance(n, numbers.Number)
Here it is in action with various kinds of numbers and one non-number:
>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
... print '%15s %s' % (n.__repr__(), isinstance(n, Number))
2 True
2.0 True
Decimal('2.0') True
(2+0j) True
Fraction(2, 1) True
'2' False
This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.
Works for Navigation Based for particular view controller in swift4
let app = UIApplication.shared
let statusBarHeight: CGFloat = app.statusBarFrame.size.height
let statusbarView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: statusBarHeight))
statusbarView.backgroundColor = UIColor.red
view.addSubview(statusbarView)
There are many different ways to convert
a datetime
to a string. Here is one way:
SELECT convert(varchar(25), getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
See Demo
Here is a website that has a list of all of the conversions:
All you need to do is... close the terminal window and reopen new one to fix this issue.
The issue is, new python path is not added to bashrc(Either source or new terminal window would help).
Have you try $ sudo ./catalina.sh stop
? It worked in my case.
This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.
HTML:
<div rel="this-should-be-the-target">
</div>
JQuery:
$(function() {
var targetElement = 'rel="this-should-be-the-target"';
initPopover(targetElement, "Test Popover Content");
// use this line if you want it to show by default
$(targetElement).popover('show');
function initPopover(target, popOverContent) {
$(target).each(function(i, obj) {
$(this).popover({
placement : 'auto',
trigger : 'hover',
"html": true,
content: popOverContent
});
});
}
});
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.
Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.
You can also do:
tree | grep filename
This pipes the output of the tree command to grep for a search. This will only tell you whether the file exists though.
You need to add the attribute "formnovalidate" to the control that is triggering the browser validation, e.g.:
<input type="image" id="fblogin" formnovalidate src="/images/facebook_connect.png">
This has a regular expression so it's easier to just copy and paste the youtube url. Is great for when you use a CMS for clients.
/*fancybox yt video*/
$(".fancybox-video").click(function() {
$.fancybox({
padding: 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 795,
'height' : 447,
'href' : this.href.replace(new RegExp("watch.*v=","i"), "v/"),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
return false;
});
Below is an example of how to update the value in the array of objects more dynamically.
Person.findOneAndUpdate({_id: id},
{
"$set": {[`items.$[outer].${propertyName}`]: value}
},
{
"arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
...
})
Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilters
and positional operator like so:
"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value}
"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]
More usage can be found in the official docs.
Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
This works (pandas v'0.19.2'):
df.rename(columns=df.iloc[0])
chartr
is also convenient for these types of substitutions:
chartr("_", "-", data1$c)
# [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"
Thus, you can just do:
data1$c <- chartr("_", "-", data1$c)
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}
TLDR? Try: file = open(filename, encoding='cp437)
Why? When one use:
file = open(filename)
text = file.read()
Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.
If such characters are unneeded, one may decide to replace them by question marks, with:
file = open(filename, errors='replace')
Another workaround is to use:
file = open(filename, errors='ignore')
The characters are then left intact, but other errors will be masked too.
Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):
file = open(filename, encoding='cp437')
Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).
This will do the trick:
public void itemClicked(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MyAndroidAppActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}
}
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.
http://www.bettersolutions.com/excel/EED883/YI416010881.htm
Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales
This should fix your problem.
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Okay, my 2 cents, using the default value of Laravel's old() function.
<select name="type">
@foreach($options as $key => $text)
<option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
@endforeach
</select>
No, a null check is not needed before using instanceof.
The expression x instanceof SomeClass
is false
if x
is null
.
From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":
"At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
."
So if the operand is null, the result is false.
The easiest solution today is to used Apache common io :
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
The only drawback is to add this dependency in your build.gradle
app :
implementation 'commons-io:commons-io:2.5'
+ 1562 Methods count
window.location.hash = 'something';
That is just plain JavaScript.
Your comment...
Hi, what I really need is to add only the hash... something like this:
window.location.hash = '#';
but in this way nothing is added.
Try this...
window.location = '#';
Also, don't forget about the window.location.replace()
method.
Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.
Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4
The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.
The results may vary from browser to browser.
http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx
Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html
The W3C's definition of defer: http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:
"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."
I faced this error when I was trying to build Selenium source on Ubuntu. The simple shell script with correct shebang was not able to run even after I had all pre-requisites covered.
file file-name # helped me in understanding that CRLF ending were present in the file.
I opened the file in Vim and I could see that just because I once edited this file on a Windows machine, it was in DOS format. I converted the file to Unix format with below command:
dos2unix filename # actually helped me and things were fine.
I hope that we should take care whenever we edit files across platforms we should take care for the file formats as well.
There are two things to remember if you want to browse everything on your device.
adb root
You could use Mono for Android
:
http://xamarin.com/monoforandroid
An alternative is dot42
:
dot42 provides a free community licence as well as a professional licence for $399.
The accepted answer has a couple of shortcomings:
Considering the above, your options could even have different values, but toggle the same class:
<select class="div-toggle" data-target=".my-info-1">
<option value="orange" data-show=".citrus">Orange</option>
<option value="lemon" data-show=".citrus">Lemon</option>
<option value="apple" data-show=".pome">Apple</option>
<option value="pear" data-show=".pome">Pear</option>
</select>
<div class="my-info-1">
<div class="citrus hide">Citrus is...</div>
<div class="pome hide">A pome is...</div>
</div>
jQuery:
$(document).on('change', '.div-toggle', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.div-toggle').trigger('change');
});
CSS:
.hide {
display: none;
}
Here's a JSFiddle to see it in action.
This is how I would do it, in order to get in the var4 restriction:
dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )
Rgds, Rainer
To explain the difference between these two let me explain the difference between encodeURI
and encodeURIComponent
.
The main difference is that:
encodeURI
function is intended for use on the full URI.encodeURIComponent
function is intended to be used on .. well .. URI components that is
any part that lies between separators (; / ? : @ & = + $ , #).So, in encodeURIComponent
these separators are encoded also because they are regarded as text and not special characters.
Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
You should wrap your elements inside a container, then use new CSS3 features like css grid, free course, and then use grid-gap:value
that was created for your specific problem
span{_x000D_
border:1px solid red;_x000D_
}_x000D_
.inRow{_x000D_
display:grid;_x000D_
grid-template-columns:repeat(auto-fill,auto);_x000D_
grid-gap:10px /*This add space between elements, only works on grid items*/_x000D_
}_x000D_
.inColumn{_x000D_
display:grid;_x000D_
grid-template-rows:repeat(auto-fill,auto);_x000D_
grid-gap:15px;_x000D_
}
_x000D_
<div class="inrow">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
</div>_x000D_
<div class="inColumn">_x000D_
<span>4</span>_x000D_
<span>5</span>_x000D_
<span>6</span>_x000D_
</div>
_x000D_
Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.
<div class="featured-image" style="height:300px">
<img id="thumbnail" src="01.jpg"/>
</div>
<div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
<img src='01.jpg'>
<img src='02.jpg'>
<img src='03.jpg'>
<img src='04.jpg'>
</div>
<script type="text/javascript">
function changeThumbnail()
{
$("#thumbnail").fadeOut(200);
var path=$("#thumbnail").attr('src');
var arr= new Array(); var i=0;
$("#thumblist img").each(function(index, element) {
arr[i]=$(this).attr('src');
i++;
});
var index= arr.indexOf(path);
if(index==(arr.length-1))
path=arr[0];
else
path=arr[index+1];
$("#thumbnail").attr('src',path).fadeIn(200);
setTimeout(changeThumbnail, 5000);
}
setTimeout(changeThumbnail, 5000);
</script>
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
$('.class').length
This one does not work for me. I'd rather use this:
$('.class').children().length
I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.
First, describe nodes and see if it reports anything:
$ kubectl describe nodes
Look for conditions, capacity and allocatable:
Conditions:
Type Status
---- ------
OutOfDisk False
MemoryPressure False
DiskPressure False
Ready True
Capacity:
cpu: 2
memory: 2052588Ki
pods: 110
Allocatable:
cpu: 2
memory: 1950188Ki
pods: 110
If everything is alright here, SSH into the node and observe kubelet
logs to see if it reports anything. Like certificate erros, authentication errors etc.
If kubelet
is running as a systemd service, you can use
$ journalctl -u kubelet
I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:
public static bool ToBoolean(this string s)
{
string[] trueStrings = { "1", "y" , "yes" , "true" };
string[] falseStrings = { "0", "n", "no", "false" };
if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return true;
if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
return false;
throw new InvalidCastException("only the following are supported for converting strings to boolean: "
+ string.Join(",", trueStrings)
+ " and "
+ string.Join(",", falseStrings));
}
<remote_name>
you'd like to use (feel free to use origin
and skip step 1.)git remote add <remote_name> <remote_url>
git fetch <remote_name> <branch>
<your_local_branch_name>
you'd like to use. Could be the same as <branch>
.git checkout <remote_name>/<branch> -b <your_local_branch_name>
Hope that helps!
You can download language pack and use "Install or Uninstall display languages" wizard. To do this:
Win+R
, paste lpksetup
and press Enter
Install display languages
buttonBrowse
and pick the *.cab file of the MUI language you downloadedYou can insert this code in your xml file
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:textColor="#000000"
android:textSize="20dp"
android:id="@+id/toolbar_title" />
</androidx.appcompat.widget.Toolbar>
You should explore SQL Server\Memory Manager performance counters.
Using &
operator, don't forget to wrap the sub-statements with ()
:
males = df[(df[Gender]=='Male') & (df[Year]==2014)]
To store your dataframes in a dict
using a for loop:
from collections import defaultdict
dic={}
for g in ['male', 'female']:
dic[g]=defaultdict(dict)
for y in [2013, 2014]:
dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict
A demo for your getDF
:
def getDF(dic, gender, year):
return dic[gender][year]
print genDF(dic, 'male', 2014)
I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.
Support for string view arguments to url() is deprecated and will be removed in Django 1.10
My solution is just small correction to Conrado solution above.
from django.conf import settings
import os
from django.views.static import serve as staticserve
if settings.DEBUG404:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', staticserve,
{'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
)
Here is an alternative way to solve this using a DIV and the 'contenteditable' property:
HTML:
<div contenteditable = "true" class = "fluidInput" data-placeholder = ""></div>
CSS: (to give the DIV some dimensions and make it easier to see)
.fluidInput {
display : inline-block;
vertical-align : top;
min-width : 1em;
height : 1.5em;
font-family : Arial, Helvetica, sans-serif;
font-size : 0.8em;
line-height : 1.5em;
padding : 0px 2px 0px 2px;
border : 1px solid #aaa;
cursor : text;
}
.fluidInput * {
display : inline;
}
.fluidInput br {
display : none;
}
.fluidInput:empty:before {
content : attr(data-placeholder);
color : #ccc;
}
Note: If you are planning on using this inside of a FORM element that you plan to submit, you will need to use Javascript / jQuery to catch the submit event so that you can parse the 'value' ( .innerHTML
or .html()
respectively) of the DIV.
Example: Let us switch from php 7.4 to 7.3
brew unlink [email protected]
brew install [email protected]
brew link [email protected]
If you get Warning: [email protected] is keg-only and must be linked with --force
Then try with:
brew link [email protected] --force
function getMonthDays(MonthYear) {
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var Value=MonthYear.split(" ");
var month = (months.indexOf(Value[0]) + 1);
return new Date(Value[1], month, 0).getDate();
}
console.log(getMonthDays("March 2011"));
In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.
v5.1 introduces the useful hook useLocation
https://reacttraining.com/blog/react-router-v5-1/#uselocation
import { Switch, useLocation } from 'react-router-dom'
function usePageViews() {
let location = useLocation()
useEffect(
() => {
ga.send(['pageview', location.pathname])
},
[location]
)
}
function App() {
usePageViews()
return <Switch>{/* your routes here */}</Switch>
}
In the pop up
You end up with a big line. Then
In the pop up
So you end up with lines that end by dot
And if you have to do the same process lots of times
I have 2 accounts on my windows machine and I was experiencing this problem with one of them. I did not want to use the sa
account, I wanted to use Windows login. It was not immediately obvious to me that I needed to simply sign into the other account that I used to install SQL Server, and add the permissions for the new account from there
(SSMS > Security > Logins > Add a login there)
Easy way to get the full domain name you need to add there open cmd echo each one.
echo %userdomain%\%username%
Add a login for that user and give it all the permissons for master db and other databases you want. When I say "all permissions" make sure NOT to check of any of the "deny" permissions since that will do the opposite.
you can connect to the database using SqlConnection and SqlCommand and execute the following command text for example:
BACKUP DATABASE [MyDatabase] TO DISK = 'C:\....\MyDatabase.bak'
See here for examples.
you can use the left_on and right_on options as follows:
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)
pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')
You invoke the function with 2 parameters (@GenId and @Description):
EXEC etl.etl_M_Update_Promo @GenID, @Description
However you have declared the function to take 1 argument:
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0
SQL Server is telling you that [etl_M_Update_Promo]
only takes 1 parameter (@GenId
)
You can alter the procedure to take two parameters by specifying @Description
.
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0,
@Description NVARCHAR(50)
AS
.... Rest of your code.
You can add more than 1 element in one shot to array using array_push,
e.g. array_push($array_name, $element1, $element2,...)
Where $element1, $element2,... are elements to be added to array.
But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.
Although not any better, just for the reference, you can also do this:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
It can be useful for example when someone wants to print {argument}
. It is maybe more readable than '{{{}}}'.format('argument')
Note that you omit argument positions (e.g. {}
instead of {0}
) after Python 2.7
An example use-case to plot CPU usage in real-time.
import time
import psutil
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
i = 0
x, y = [], []
while True:
x.append(i)
y.append(psutil.cpu_percent())
ax.plot(x, y, color='b')
fig.canvas.draw()
ax.set_xlim(left=max(0, i - 50), right=i + 50)
fig.show()
plt.pause(0.05)
i += 1
I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.
def sectohmsus(seconds):
x = seconds
hmsus = []
for i in [3600, 60, 1]: # seconds in a hour, minute, and second
hmsus.append(int(x / i))
x %= i
hmsus.append(int(round(x * 1000000))) # microseconds
return hmsus # hours, minutes, seconds, microsecond
Windows
1- Find: CTRL + F
2- Select-in: Alt + Enter
Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.
Credit goes to : https://superuser.com/a/921806/342825
The error vanished after I did Clean->Run xDoclet->Run xPackaging.
In my workspace, in ecllipse.
If you don't want your image to be pre-scaled you can move it to the res/drawable-nodpi/
folder.
More info: https://developer.android.com/training/multiscreen/screendensities#DensityConsiderations
Check if window.history.length
is equal to 0.
Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.
Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy()
doesn't so it will always copy the exact number of bytes you tell it to copy.
If your string is an actual array, i.e.:
struct {
char string[32];
size_t len;
} a, b;
strcpy(a.string, "hello");
a.len = strlen(a.string);
Then you can still use plain assignment:
b = a;
To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.
Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.
For these situations a "deep copy" is really the only choice, and that needs to go in a function.
As short as @jumbo's answer is :-) you can do it even more tersely.
This just returns the Count
property of the array returned by the antecedent sub-expression:
@(Get-Alias).Count
A couple points to note:
You can put an arbitrarily complex expression in place of Get-Alias
, for example:
@(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count
property to exist by forcing the output to be an array.)
2012.01.30 Update
The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count
property even for singletons, so the at-sign becomes unimportant for this scenario.
I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type):
db:
image: postgres
web:
image: app
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
depends_on:
- migration
migration:
build: .
image: app
command: python manage.py migrate
volumes:
- .:/code
links:
- db
depends_on:
- db
This helps things keeping clean and separate. Two things to consider:
You have to ensure the correct startup sequence (using depends_on).
You want to avoid multiple builds which is achieved by tagging it the first time round using build and image; you can refer to image in other containers then.
There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180) accepted separator is the comma ',' not the semi-colon ';'. Programs like MS Excel expect a comma as a separator.
There are some programs that treat the comma as a decimal and the semi-colon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files.
So, when creating a CSV you create your filestream and add your lines like so:
#include <iostream>
#include <fstream>
int main( int argc, char* argv[] )
{
std::ofstream myfile;
myfile.open ("example.csv");
myfile << "This is the first cell in the first column.\n";
myfile << "a,b,c,\n";
myfile << "c,s,v,\n";
myfile << "1,2,3.456\n";
myfile << "semi;colon";
myfile.close();
return 0;
}
This will result in a CSV file that looks like this when opened in MS Excel:
DFS(analysis):
O(1)
timeO(n + m)
time provided the graph is represented by the adjacency list structureSv deg(v) = 2m
BFS(analysis):
Li
O(n + m)
time provided the graph is represented by the adjacency list structureSv deg(v) = 2m
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
If you need it in SELECT section can use like this.
SELECT ct.ID,
ISNULL(NULLIF(ct.LaunchDate, ''), null) [LaunchDate]
FROM [dbo].[CustomerTable] ct
you can replace the null
with your substitution value.
I had the same issue, but I followed the following steps:-
;(function() {
var redirect = false
if (navigator.userAgent.match(/iPhone/i)) {
redirect = true
}
if (navigator.userAgent.match(/iPod/i)) {
redirect = true
}
var isAndroid = /(android)/i.test(navigator.userAgent)
var isMobile = /(mobile)/i.test(navigator.userAgent)
if (isAndroid && isMobile) {
redirect = true
}
if (redirect) {
window.location.replace('jQueryMobileSite')
}
})()
You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:
apply_async(func[, args[, kwds[, callback]]])
E.g.:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=1) # Start a worker processes.
result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.
This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.
If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.
INI file has the format:
[Section]
key = value
key with spaces = somevalue
For width it's easy, simply remove the width: 100%
rule. By default, the div
will stretch to fit the parent container.
Height is not quite so simple. You could do something like the equal height column trick.
html, body {width:100%;height:100%;margin:0;padding:0;}
.border {border:1px solid black;}
.margin { margin:5px;}
#one {width:500px;height:300px; overflow: hidden;}
#two {height:50px;}
#three {width:100px; padding-bottom: 30000px; margin-bottom: -30000px;}
The cleanest solution will be to manually pass default argument if none were given on the command line:
parser.parse_args(args=None if sys.argv[1:] else ['--help'])
Complete example:
import argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
# use your args
print("connecting to {}".format(args.host))
This will print complete help (not short usage) if called w/o arguments.
Adapt this example to your code
HTML
<div class="img-holder">
<img src="images/img-1.png" alt="image description"/>
<a class="link" href=""></a>
</div>
CSS
.img-holder {position: relative;}
.img-holder .link {
position: absolute;
bottom: 10px; /*your button position*/
right: 10px; /*your button position*/
}
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
Also possible like this
<button type="submit" class="icon-search icon-large"></button>
Put the part from BEGIN....END{}
inside a file and name it like my.awk.
And then execute it like below:
awk -f my.awk life.csv >output.txt
Also I see a field separator as ,
. You can add that in the begin block of the .awk file as FS=","
By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?
I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd
which has issues with OverlayFS. I found information about this here:
It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.
http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204
You can configure and rebuild bash with bash_cv_getcwd_malloc=yes
(if you're actually building bash and your C library does malloc a getcwd call).
For next examples assumed that you use C++11. Example with ranged-based for loops:
for (auto &attack : m_attack) // access by reference to avoid copying
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
You should use const auto &attack
depending on the behavior of makeDamage()
.
You can use std::for_each
from standard library + lambdas:
std::for_each(m_attack.begin(), m_attack.end(),
[](Attack * attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
);
If you are uncomfortable using std::for_each
, you can loop over m_attack
using iterators:
for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
Use m_attack.cbegin()
and m_attack.cend()
to get const
iterators.
First, go to that folder which is containing pycharm.sh and open terminal from there. Then type
./pycharm.sh
this will open pycharm.
bin folder contains pycharm.sh file.
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
You can create a function with the pattern ShouldSerialize{PropertyName}
which tells the XmlSerializer if it should serialize the member or not.
For example, if your class property is called MyNullableInt
you could have
public bool ShouldSerializeMyNullableInt()
{
return MyNullableInt.HasValue;
}
Here is a full sample
public class Person
{
public string Name {get;set;}
public int? Age {get;set;}
public bool ShouldSerializeAge()
{
return Age.HasValue;
}
}
Serialized with the following code
Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);
Results in the followng XML - Notice there is no Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Chris</Name>
</Person>
If your UITableView is managed by a subclass of UITableViewController and not UITableView, and the text field delegate is the UITableViewController, it should manage all the scrolling automatically -- all these other comments are very difficult to implement in practice.
For a good example see the apple example code project: TaggedLocations.
You can see that it scrolls automatically, but there doesn't seem to be any code that does this. This project also has custom table view cells, so if you build your application with it as a guide, you should get the desired result.
I tried this:
python -m pipenv # for python2
python3 -m pipenv # for python3
Hope this can help you.
I would go for substr() functionality in MySql.
Basically, this function takes account of three parameters i.e. substr(str,pos,len)
http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php
SELECT * FROM artists
WHERE lower(substr(name,1,1)) in ('a','b','c');
package basicprogm;
public class pallindrome {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s= "madam" ;
//to store the values that we got in loop
String t="";
for(int i=s.length()-1;i>=0;i--){
t=t+s.charAt(i);
}
System.out.println("reversed word is "+ t);
if (t.matches(s)){
System.out.println("pallindrome");
}
else{
System.out.println("not pallindrome");
}
}
}
¿Are you recently changed the pg_hba.conf? if you did just check for any typo in:
local all all password
host all all 127.0.0.1/32 password
host all all ::1/128 password
Sometimes a simple mistake can give us a headache. I hope this help and sorry if my english is no good at all.
None of the above solutions worked for me. I was trying to add a line feed and additional text to a <p>
element. I typically use Firefox, but I do need browser compatibility. I read that only Firefox supports the textContent
property, only Internet Explorer supports the innerText
property, but both support the innerHTML
property. However, neither adding <br />
nor \n
nor \r\n
to any of those properties resulted in a new line. The following, however, did work:
<html>
<body>
<script type="text/javascript">
function modifyParagraph() {
var p;
p=document.getElementById("paragraphID");
p.appendChild(document.createElement("br"));
p.appendChild(document.createTextNode("Additional text."));
}
</script>
<p id="paragraphID">Original text.</p>
<input type="button" id="pbutton" value="Modify Paragraph" onClick="modifyParagraph()" />
</body>
</html>
Note: Note to Win32 Users In order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
This note solved my problem. Thought of sharing. libeay32.dll & ssleay.dll you will find in your php installation folder.
The required SQL will be some like:-
SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....
Hope it helps.
<input type="number" id="n" value="0" step=".5" />
<input type="hidden" id="v" value = "0"/>
<script>
$("#n").bind('keyup mouseup', function () {
var current = $("#n").val();
var prevData = $("#v").val();
if(current > prevData || current < prevData){
$("#v").val(current);
var newv = $("#v").val();
alert(newv);
}
});
</script>
http://jsfiddle.net/patrickrobles53/s10wLjL3/
I've used a hidden input type to be the container of the previous value that will be needed for the comparison on the next change.
There is another instance still same error will shown after you doing everything above mentioned. When you change your codes accordingly mentioned solutions make sure to keep originals. So you can easily go back. So go and again check dispatcher-servelet configuration file's base package location. Is it scanning all relevant packages when you running application.
<context:component-scan base-package="your.pakage.path.here"/>
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - More complete example
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
from the code-behind, or you'll have two "" items.
I think a better way is using the static method fromString to avoid those regular expressions.
id = UUID.randomUUID();
UUID uuid = UUID.fromString(id.toString());
Assert.assertEquals(id.toString(), uuid.toString());
On the other hand
UUID uuidFalse = UUID.fromString("x");
throws java.lang.IllegalArgumentException: Invalid UUID string: x
Use app.use( express.static('public'));
and in index.html
correct path of scripts to <script type="text/javascript" src="/javasrc/example.js"></script>
And Now all things work fine.
remove
user.setId(1);
because it is auto generate on the DB, and continue with persist command.
StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
"||");
while(st.hasMoreTokens()){
System.out.println(st.nextElement());
}
Answer will print
1 1 Abdul-Jabbar Karim 1996 1974
NSLog(@"%s %d %s %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);
Outputs file name, line number, and function name:
/proj/cocoa/cdcli/cdcli.m 121 managedObjectContext managedObjectContext
__FUNCTION__
in C++ shows mangled name __PRETTY_FUNCTION__
shows nice function name, in cocoa they look the same.
I'm not sure what is the proper way of disabling NSLog, I did:
#define NSLog
And no logging output showed up, however I don't know if this has any side effects.
It should be like this:
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No Results" />
Note the id attribute.
For me the problem was with my activity_main.xml(21) in which the recycleView didn't have an id.
activity_main.xml(21)
<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button3"
tools:listitem="@layout/transaction_list_row" />
activity_main.xml
<android.support.v7.widget.RecyclerView
android:id="@+id/transac_recycler_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button3"
/>
It worked when i added a android:id="@+id/transac_recycler_view" to the activity_main.xml(21) recycleView
For me the basic oracle only was not installed. Please ensure you have oracle installed and then try checking host and port.
Just wanted to let you know that up until today I was first obtaining an app access token (via GET request to Facebook), and then using the received token as the app-token-or-admin-token
in:
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app-token-or-admin-token}
However, I just realized a better way of doing this (with the added benefit of requiring one less GET request):
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app_id}|{app_secret}
As described in Facebook's documentation for Access Tokens here.
Here is a tidyverse
option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:
library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format
read_dir <- function(dir_path, file_name){
read_csv(paste0(dir_path, file_name)) %>%
mutate(file_name = file_name) %>% # add the file name as a column
gather(variable, value, A:B) %>% # convert the data from wide to long
group_by(file_name, variable) %>%
summarize(sum = sum(value, na.rm = TRUE),
min = min(value, na.rm = TRUE),
mean = mean(value, na.rm = TRUE),
median = median(value, na.rm = TRUE),
max = max(value, na.rm = TRUE))
}
df_summary <-
list.files(dir_path, pattern = file_pattern) %>%
map_df(~ read_dir(dir_path, .))
df_summary
# A tibble: 8 x 7
# Groups: file_name [?]
file_name variable sum min mean median max
<chr> <chr> <int> <dbl> <dbl> <dbl> <dbl>
1 Df.1.csv A 34 4 5.67 5.5 8
2 Df.1.csv B 22 1 3.67 3 9
3 Df.2.csv A 21 1 3.5 3.5 6
4 Df.2.csv B 16 1 2.67 2.5 5
5 Df.3.csv A 30 0 5 5 11
6 Df.3.csv B 43 1 7.17 6.5 15
7 Df.4.csv A 21 0 3.5 3 8
8 Df.4.csv B 42 1 7 6 16
Here You Go:
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
Script:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
A simpler way of doing it is:
var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
We can also use -
$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth') <!-- Width -->
From my little date difference calculator:
var startDate = new Date(2000, 1-1, 1); // 2000-01-01
var endDate = new Date(); // Today
// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
var ndays;
var tv1 = d1.valueOf(); // msec since 1970
var tv2 = d2.valueOf();
ndays = (tv2 - tv1) / 1000 / 86400;
ndays = Math.round(ndays - 0.5);
return ndays;
}
So you would call:
var nDays = diffDays(startDate, endDate);
(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)
Addendum
The code can be improved by changing these lines:
var tv1 = d1.getTime(); // msec since 1970
var tv2 = d2.getTime();
Why not use: CopyOnWriteArraySet from java.util.concurrent?
In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path
(make sure you use this in the script context).
The reason you should use that and not anything else can be illustrated with this example script.
## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path
Here are some results.
PS C:\Users\JasonAr> .\ScriptTest.ps1 InvocationName: .\ScriptTest.ps1 Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> . .\ScriptTest.ps1 InvocationName: . Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> & ".\ScriptTest.ps1" InvocationName: & Path: C:\Users\JasonAr\ScriptTest.ps1
In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot
:
## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1 Script: C:\Users\jarcher\ScriptTest.ps1 Path: C:\Users\jarcher
To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>
The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.
Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.
https://help.github.com/articles/remove-sensitive-data/
You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.
To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.
It looked intimidating at first, but really, was easy and worked like a charm ! :-)
This is an easy way to rename a file:
File oldfile =new File("test.txt");
File newfile =new File("test1.txt");
if(oldfile.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
Have you tried using .prop()?
$("#password").prop('type','text');
Standard WCF Tracing/Diagnostics
If for some reason you are unable to get Fiddler to work, or would rather log the requests another way, another option is to use the standard WCF tracing functionality. This will produce a file that has a nice viewer.
Docs
See https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging
Configuration
Add the following to your config, make sure c:\logs
exists, rebuild, and make requests:
<system.serviceModel>
<diagnostics>
<!-- Enable Message Logging here. -->
<!-- log all messages received or sent at the transport or service model levels -->
<messageLogging logEntireMessage="true"
maxMessagesToLog="300"
logMessagesAtServiceLevel="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information,ActivityTracing"
propagateActivity="true">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
name="xml" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.
I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
run conda navigator, you can upgrade your packages easily in the friendly GUI
as suggested in git status
,
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: a.jl
both modified: b.jl
I used git add
to finish the merging, then git checkout
works fine.
Below funtions worked well for me across devices.
It is taken from https://gist.github.com/laaptu/7867851
public static float convertPixelsToDp(float px){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return Math.round(dp);
}
public static float convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
}
A general solution to convert from byte array to string when you don't know the encoding:
static string BytesToStringConverted(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3)
- Returns substring of first 3 chars. //One
Substring(3, 3)
- Returns substring of second 3 chars. //Two
Substring(6)
- Returns substring of all chars after first 6. //Three
Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()
If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:
Underscore.js makes the transformation pretty clean:
var keys = _.map(x, function(v, k) { return k; });
Edit: I missed that you can do this too:
var keys = _.keys(x);
Swift 2.x
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
print("do some work")
}
Swift 3.x --&-- Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
print("do some work")
}
or pass a escaping closure
func delay(seconds: Double, completion: @escaping()-> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
}
In terms of javascript, one difference is that the this
keyword in the onclick
handler will refer to the DOM element whose onclick
attribute it is (in this case the <a>
element), whereas this
in the href
attribute will refer to the window
object.
In terms of presentation, if an href
attribute is absent from a link (i.e. <a onclick="[...]">
) then, by default, browsers will display the text
cursor (and not the often-desired pointer
cursor) since it is treating the <a>
as an anchor, and not a link.
In terms of behavior, when specifying an action by navigation via href
, the browser will typically support opening that href
in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick
.
However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
$('a#link').click(function(){ /* ... action ... */ })
</script>
I use this and it works great for me for setting any color I want.
public static final int MY_COLOR = Color.rgb(255, 102, 153);
Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.
Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.
Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems
This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.
If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").
@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.
Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.
Add this line before main function:
void swapCase (char* name);
int main()
{
...
swapCase(name); // swapCase prototype should be known at this point
...
}
This is called forward declaration: compiler needs to know function prototype when function call is compiled.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
I did however, create a test page that confirmed calling should onchange() work:
<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>
Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.
In git you do not 'checkout' files before you update them - it seems like this is what you are after.
Many systems like clearcase, csv and so on require you to 'checkout' a file before you can make changes to it. Git does not require this. You clone a repository and then make changes in your local copy of repository.
Once you updated files you can do:
git status
To see what files have been modified. You add the ones you want to commit to index
first with (index
is like a list to be checked in):
git add .
or
git add blah.c
Then do git status
will show you which files were modified and which are in index
ready to be commited or checked in.
To commit files to your copy of repository do:
git commit -a -m "commit message here"
See git
website for links to manuals and guides.
A little late to the game here, but I was running into some performance issues with HYRY's solution, so I had to come up with another one.
It works by finding the frequency of each key-value, and then, for each key, only keeping the value that appears with it most often.
There's also an additional solution that supports multiple modes.
On a scale test that's representative of the data I'm working with, this reduced runtime from 37.4s to 0.5s!
Here's the code for the solution, some example usage, and the scale test:
import numpy as np
import pandas as pd
import random
import time
test_input = pd.DataFrame(columns=[ 'key', 'value'],
data= [[ 1, 'A' ],
[ 1, 'B' ],
[ 1, 'B' ],
[ 1, np.nan ],
[ 2, np.nan ],
[ 3, 'C' ],
[ 3, 'C' ],
[ 3, 'D' ],
[ 3, 'D' ]])
def mode(df, key_cols, value_col, count_col):
'''
Pandas does not provide a `mode` aggregation function
for its `GroupBy` objects. This function is meant to fill
that gap, though the semantics are not exactly the same.
The input is a DataFrame with the columns `key_cols`
that you would like to group on, and the column
`value_col` for which you would like to obtain the mode.
The output is a DataFrame with a record per group that has at least one mode
(null values are not counted). The `key_cols` are included as columns, `value_col`
contains a mode (ties are broken arbitrarily and deterministically) for each
group, and `count_col` indicates how many times each mode appeared in its group.
'''
return df.groupby(key_cols + [value_col]).size() \
.to_frame(count_col).reset_index() \
.sort_values(count_col, ascending=False) \
.drop_duplicates(subset=key_cols)
def modes(df, key_cols, value_col, count_col):
'''
Pandas does not provide a `mode` aggregation function
for its `GroupBy` objects. This function is meant to fill
that gap, though the semantics are not exactly the same.
The input is a DataFrame with the columns `key_cols`
that you would like to group on, and the column
`value_col` for which you would like to obtain the modes.
The output is a DataFrame with a record per group that has at least
one mode (null values are not counted). The `key_cols` are included as
columns, `value_col` contains lists indicating the modes for each group,
and `count_col` indicates how many times each mode appeared in its group.
'''
return df.groupby(key_cols + [value_col]).size() \
.to_frame(count_col).reset_index() \
.groupby(key_cols + [count_col])[value_col].unique() \
.to_frame().reset_index() \
.sort_values(count_col, ascending=False) \
.drop_duplicates(subset=key_cols)
print test_input
print mode(test_input, ['key'], 'value', 'count')
print modes(test_input, ['key'], 'value', 'count')
scale_test_data = [[random.randint(1, 100000),
str(random.randint(123456789001, 123456789100))] for i in range(1000000)]
scale_test_input = pd.DataFrame(columns=['key', 'value'],
data=scale_test_data)
start = time.time()
mode(scale_test_input, ['key'], 'value', 'count')
print time.time() - start
start = time.time()
modes(scale_test_input, ['key'], 'value', 'count')
print time.time() - start
start = time.time()
scale_test_input.groupby(['key']).agg(lambda x: x.value_counts().index[0])
print time.time() - start
Running this code will print something like:
key value
0 1 A
1 1 B
2 1 B
3 1 NaN
4 2 NaN
5 3 C
6 3 C
7 3 D
8 3 D
key value count
1 1 B 2
2 3 C 2
key count value
1 1 2 [B]
2 3 2 [C, D]
0.489614009857
9.19386196136
37.4375009537
Hope this helps!
tl;dr: baz() { this.foo(); this.bar() }
In ES2015 this construct:
var obj = {
foo() { console.log('foo') }
}
is equal to this ES5 code:
var obj = {
foo : function foo() { console.log('foo') }
}
exports.default = {}
is like creating an object, your default export translates to ES5 code like this:
exports['default'] = {
foo: function foo() {
console.log('foo');
},
bar: function bar() {
console.log('bar');
},
baz: function baz() {
foo();bar();
}
};
now it's kind of obvious (I hope) that baz
tries to call foo
and bar
defined somewhere in the outer scope, which are undefined. But this.foo
and this.bar
will resolve to the keys defined in exports['default']
object. So the default export referencing its own methods shold look like this:
export default {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { this.foo(); this.bar() }
}
i recently encountered this. I used: display:block;
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...
Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:
Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.
The BusinessCtrl
is initialised before the createBusinessForm
's FormController
.
Even if you have the ngController
on the form won't work the way you wanted.
You can't help this (you can create your ngControllerDirective
, and try to trick the priority.) this is how angularjs works.
See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview
I had this script in app.js in laravel which automatically adds all components in the component folder.
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))
To make it work just add default
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
I think you could use the following JavaScript to track the last-focused textbox:
<script>
var holdFocus;
function updateFocus(x)
{
holdFocus = x;
}
function appendTextToLastFocus(text)
{
holdFocus.value += text;
}
</script>
Usage:
<input type="textbox" onfocus="updateFocus(this)" />
<a href="#" onclick="appendTextToLastFocus('textToAppend')" />
A previous solution (props to gclaghorn) uses textarea and calculates the position of the cursor too, so it may be better for what you want. On the other hand, this one would be more lightweight, if that's what you're looking for.
The only "right" way to compare colors is to do it with deltaE in CIELab or CIELuv.
But for a lot of applications I think this is a good enough approximation:
distance = 3 * |dR| + 4 * |dG| + 3 * |dB|
I think a weighted manhattan distance makes a lot more sense when comparing colors. Remember that color primaries are only in our head. They don't have any physical significance. CIELab and CIELuv is modelled statistically from our perception of color.
In this case a[4]
is the 5th
integer in the array a
, ap
is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap
now holds 45
and when you try to de-reference it (by doing *ap
) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.
You should do ap = &(a[4]);
or ap = a + 4;
In c
array names decays to pointer, so a
points to the 1st element of the array.
In this way, a
is equivalent to &(a[0])
.
In a word, no. You can have several forms in a page but they should not be nested.
From the html5 working draft:
4.10.3 The
form
elementContent model:
Flow content, but with no form element descendants.
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
Spark 1.6+
sc.getConf.getAll.foreach(println)
I have tried a product called Rummage and it does a good job in giving you some control ... Although it lacks many things that Eziriz offers but price for Rummage is too good...
textview.setTypeface(Typeface.DEFAULT_BOLD);
setTypeface is the Attribute textStyle.
As Shankar V added, to preserve the previously set typeface attributes you can use:
textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.
I have done this several times under svn and under cvs.
According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.
I've listed a few options below that might be helpful to you:
With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..
You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.
Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.
<input type="number" formnovalidate />
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
you can use below to deep copy Hash objects.
deeply_copied_hash = Marshal.load(Marshal.dump(original_hash))
Piping output to xargs
will concatenate each line of output to a single line with spaces:
grep pattern file | xargs
Or any command, eg. ls | xargs
. The default limit of xargs
output is ~4096 characters, but can be increased with eg. xargs -s 8192
.
I think it will be easier using syntax-based query:
var entryPoint = (from ep in dbContext.tbl_EntryPoint
join e in dbContext.tbl_Entry on ep.EID equals e.EID
join t in dbContext.tbl_Title on e.TID equals t.TID
where e.OwnerID == user.UID
select new {
UID = e.OwnerID,
TID = e.TID,
Title = t.Title,
EID = e.EID
}).Take(10);
And you should probably add orderby
clause, to make sure Top(10)
returns correct top ten items.
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
The method newLine()
ensures a platform-compatible new line is added (0Dh 0Ah
for DOS, 0Dh
for older Macs, 0Ah
for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.
You can use intent class to send data between Activities. It is basically a message to OS where you describe source and destination of data flow. Like data from A to B activity.
In ACTIVITY A (the source):
Intent intent = new Intent(A.this, B.class);
intent.putExtra("KEY","VALUE");
startActivity(intent);
In Activity B (the destination)->
Intent intent =getIntent();
String data =intent.getString("KEY");
Here you will get data for key "KEY"
FOR BETTER USE ALWAYS KEYS SHOULD BE STORED IN A CLASS FOR SIMPLICITY AND IT WILL HELP IN MINNIMISE THE RISK OF TYPING ERRORS
Like this:
public class Constants{
public static String KEY="KEY"
}
Now In ACTIVITY A:
intent.putExtra(Constants.KEY,"VALUE");
In Activity B:
String data =intent.getString(Constants.KEY);
As a rephrasing of Andrey's answer:
The Boost TypeIndex library can be used to print names of types.
Inside a template, this might read as follows
#include <boost/type_index.hpp>
#include <iostream>
template<typename T>
void printNameOfType() {
std::cout << "Type of T: "
<< boost::typeindex::type_id<T>().pretty_name()
<< std::endl;
}
Here is how you can print all permutations in 10 lines of code:
public class Permute{
static void permute(java.util.List<Integer> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
System.out.println(java.util.Arrays.toString(arr.toArray()));
}
}
public static void main(String[] args){
Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
}
}
You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element. The tricky part is that after recursive call you must swap i-th element with first element back, otherwise you could get repeated values at the first spot. By swapping it back we restore order of elements (basically you do backtracking).
Iterators and Extension to the case of repeated values
The drawback of previous algorithm is that it is recursive, and does not play nicely with iterators. Another issue is that if you allow repeated elements in your input, then it won't work as is.
For example, given input [3,3,4,4] all possible permutations (without repetitions) are
[3, 3, 4, 4]
[3, 4, 3, 4]
[3, 4, 4, 3]
[4, 3, 3, 4]
[4, 3, 4, 3]
[4, 4, 3, 3]
(if you simply apply permute
function from above you will get [3,3,4,4] four times, and this is not what you naturally want to see in this case; and the number of such permutations is 4!/(2!*2!)=6)
It is possible to modify the above algorithm to handle this case, but it won't look nice. Luckily, there is a better algorithm (I found it here) which handles repeated values and is not recursive.
First note, that permutation of array of any objects can be reduced to permutations of integers by enumerating them in any order.
To get permutations of an integer array, you start with an array sorted in ascending order. You 'goal' is to make it descending. To generate next permutation you are trying to find the first index from the bottom where sequence fails to be descending, and improves value in that index while switching order of the rest of the tail from descending to ascending in this case.
Here is the core of the algorithm:
//ind is an array of integers
for(int tail = ind.length - 1;tail > 0;tail--){
if (ind[tail - 1] < ind[tail]){//still increasing
//find last element which does not exceed ind[tail-1]
int s = ind.length - 1;
while(ind[tail-1] >= ind[s])
s--;
swap(ind, tail-1, s);
//reverse order of elements in the tail
for(int i = tail, j = ind.length - 1; i < j; i++, j--){
swap(ind, i, j);
}
break;
}
}
Here is the full code of iterator. Constructor accepts an array of objects, and maps them into an array of integers using HashMap
.
import java.lang.reflect.Array;
import java.util.*;
class Permutations<E> implements Iterator<E[]>{
private E[] arr;
private int[] ind;
private boolean has_next;
public E[] output;//next() returns this array, make it public
Permutations(E[] arr){
this.arr = arr.clone();
ind = new int[arr.length];
//convert an array of any elements into array of integers - first occurrence is used to enumerate
Map<E, Integer> hm = new HashMap<E, Integer>();
for(int i = 0; i < arr.length; i++){
Integer n = hm.get(arr[i]);
if (n == null){
hm.put(arr[i], i);
n = i;
}
ind[i] = n.intValue();
}
Arrays.sort(ind);//start with ascending sequence of integers
//output = new E[arr.length]; <-- cannot do in Java with generics, so use reflection
output = (E[]) Array.newInstance(arr.getClass().getComponentType(), arr.length);
has_next = true;
}
public boolean hasNext() {
return has_next;
}
/**
* Computes next permutations. Same array instance is returned every time!
* @return
*/
public E[] next() {
if (!has_next)
throw new NoSuchElementException();
for(int i = 0; i < ind.length; i++){
output[i] = arr[ind[i]];
}
//get next permutation
has_next = false;
for(int tail = ind.length - 1;tail > 0;tail--){
if (ind[tail - 1] < ind[tail]){//still increasing
//find last element which does not exceed ind[tail-1]
int s = ind.length - 1;
while(ind[tail-1] >= ind[s])
s--;
swap(ind, tail-1, s);
//reverse order of elements in the tail
for(int i = tail, j = ind.length - 1; i < j; i++, j--){
swap(ind, i, j);
}
has_next = true;
break;
}
}
return output;
}
private void swap(int[] arr, int i, int j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public void remove() {
}
}
Usage/test:
TCMath.Permutations<Integer> perm = new TCMath.Permutations<Integer>(new Integer[]{3,3,4,4,4,5,5});
int count = 0;
while(perm.hasNext()){
System.out.println(Arrays.toString(perm.next()));
count++;
}
System.out.println("total: " + count);
Prints out all 7!/(2!*3!*2!)=210
permutations.
Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf
compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook
setting for gs
. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages
but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.
pdftk compress
:
no change in size
bookmarks TOC are gone
gs screen
:
takes a ridiculously long time and 100% CPU
errors:
sfopen: gs_parse_file_name failed. ?
| ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone
gs printer
:
takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone
gs ebook
:
errors:
sfopen: gs_parse_file_name failed.
./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic
| ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone
qpdf --linearize
:
very fast, a few seconds
no size change
bookmarks TOC are gone
pdf2ps
:
took very long time
output_pdf2ps.ps 74.8MB-->331.6MB
ps2pdf
:
pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone
Put this at the top of the file:
var console = {};
console.log = function(){};
For some browsers and minifiers, you may need to apply this onto the window object.
window.console = console;