Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
I find the check-and-invoke code which needs to be littered within all methods related to forms to be way too verbose and unneeded. Here's a simple extension method which lets you do away with it completely:
public static class Extensions
{
public static void Invoke<TControlType>(this TControlType control, Action<TControlType> del)
where TControlType : Control
{
if (control.InvokeRequired)
control.Invoke(new Action(() => del(control)));
else
del(control);
}
}
And then you can simply do this:
textbox1.Invoke(t => t.Text = "A");
No more messing around - simple.
The OutputPath property is not set for this project
The error shown in visual studio for the project (Let's say A) does not have issues. When I looked at the output window for the build line by line for each project, I saw that it was complaining about another project (B) that had been referred as assembly in project A. Project B added into the solution. But it had not been referred in the project A as project reference instead as assembly reference from different location. That location contains the assembly which compiled for Platform AnyCpu. Then I removed the assembly reference from the project A and added project B as a reference. It started compiling.
Not sure though how this fix worked.
What __init__ and self do in Python?
A brief illustrative example
In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__
function:
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = MyClass()
print(a.i)
print(MyClass.i)
Output:
345
123
How to downgrade to older version of Gradle
I did following steps to downgrade Gradle back to the original version:
- I deleted content of '.gradle/caches' folder in user home directory (windows).
- I deleted content of '.gradle' folder in my project root.
- I checked that Gradle version is properly set in 'Project' option of 'Project Structure' in Android Studio.
- I selected 'Use default gradle wrapper' option in 'Settings' in Android Studio, just search for gradle key word to find it.
Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.
Java way to check if a string is palindrome
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}
C++ error: "Array must be initialized with a brace enclosed initializer"
You cannot initialize an array to '0' like that
int cipher[Array_size][Array_size]=0;
You can either initialize all the values in the array as you declare it like this:
// When using different values
int a[3] = {10,20,30};
// When using the same value for all members
int a[3] = {0};
// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };
Or you need to initialize the values after declaration. If you want to initialize all values to 0 for example, you could do something like:
for (int i = 0; i < Array_size; i++ ) {
a[i] = 0;
}
Disable-web-security in Chrome 48+
From Chorme v81 the params --user-data-dir=
requires an actual parameter, whereas in the past it didn't.
Something like this works fine for me
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="\tmp\chrome_test"
Java - Convert image to Base64
To begin with, this line of code:
while ((bytesRead = fis.read(byteArray)) != -1)
is equivalent to
while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)
So it's writing into the byteArray from offset 0, rather than from where you wrote to before.
You need something like this:
int offset = 0;
int bytesRead = 0;
while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
offset += bytesRead;
}
After you have read the data (bytes) in then, you can convert it to Base64.
There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.
I would ditch the byte array and go with something like this:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);
Or condense it further as Thilo has with FileUtils.
How to save a plot into a PDF file without a large margin around
It seems to me that all approaches (file exchange solutions unconsidered) here are lacking the essential step, or finally leading to it via some blurry workarounds.
The figure size needs to equal the paper size and the white margins are gone.
A = hgload('myFigure.fig');
% set desired output size
set(A, 'Units','centimeters')
height = 15;
width = 19;
% the last two parameters of 'Position' define the figure size
set(A, 'Position',[25 5 width height],...
'PaperSize',[width height],...
'PaperPositionMode','auto',...
'InvertHardcopy', 'off',...
'Renderer','painters'... %recommended if there are no alphamaps
);
saveas(A,'printout','pdf')
Will give you a pdf output as your figure appears, in exactly the size you want. If you want to get it even tighter you can combine this solution with the answer of b3.
How to ignore a property in class if null, using json.net
Here's an option that's similar, but provides another choice:
public class DefaultJsonSerializer : JsonSerializerSettings
{
public DefaultJsonSerializer()
{
NullValueHandling = NullValueHandling.Ignore;
}
}
Then, I use it like this:
JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());
The difference here is that:
- Reduces repeated code by instantiating and configuring
JsonSerializerSettings
each place it's used.
- Saves time in configuring every property of every object to be serialized.
- Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object.
- My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes.
- Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization.
How to export data to CSV in PowerShell?
This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.
$results = @()
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation
If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.
This is why I create a new object first.
Try the following:
write-output "test" | convertto-csv -NoTypeInformation
This will give you:
"Length"
"4"
If you use the Get-Member on Write-Output as follows:
write-output "test" | Get-Member -MemberType Property
You will see that it has one property - 'length':
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property System.Int32 Length {get;}
This is why Length will be written to the csv file.
Update: Appending a CSV
Not the most efficient way if the file gets large...
$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
$results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path $csvFileName -NoTypeInformation
How to get option text value using AngularJS?
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>
AngularJS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
taken from AngularJS docs
Understanding the Rails Authenticity Token
Methods Where authenticity_token
is required
authenticity_token
is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.
Why It is Required
It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with authenticity_token
stored in session. If authenticity_token
is same then process is continue otherwise it does not perform actions.
How can I find the current OS in Python?
import os
print os.name
This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method.
How to declare a local variable in Razor?
I think you were pretty close, try this:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
</div>
}
Calling class staticmethod within the class body?
If the "core problem" is assigning class variables using functions, an alternative is to use a metaclass (it's kind of "annoying" and "magical" and I agree that the static method should be callable inside the class, but unfortunately it isn't). This way, we can refactor the behavior into a standalone function and don't clutter the class.
class KlassMetaClass(type(object)):
@staticmethod
def _stat_func():
return 42
def __new__(cls, clsname, bases, attrs):
# Call the __new__ method from the Object metaclass
super_new = super().__new__(cls, clsname, bases, attrs)
# Modify class variable "_ANS"
super_new._ANS = cls._stat_func()
return super_new
class Klass(object, metaclass=KlassMetaClass):
"""
Class that will have class variables set pseudo-dynamically by the metaclass
"""
pass
print(Klass._ANS) # prints 42
Using this alternative "in the real world" may be problematic. I had to use it to override class variables in Django classes, but in other circumstances maybe it's better to go with one of the alternatives from the other answers.
Check file size before upload
Client side Upload Canceling
On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE
, can be tampered with so always use server side validation.
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
Server Side Upload Canceling
On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize
. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE
has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.
PHP Validation
On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.php
<?php
if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
PowerShell script to return members of multiple security groups
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
Getting list of tables, and fields in each, in a database
This will return the database name, table name, column name and the datatype of the column specified by a database parameter:
declare @database nvarchar(25)
set @database = ''
SELECT cu.table_catalog,cu.VIEW_SCHEMA, cu.VIEW_NAME, cu.TABLE_NAME,
cu.COLUMN_NAME,c.DATA_TYPE,c.character_maximum_length
from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE as cu
JOIN INFORMATION_SCHEMA.COLUMNS as c
on cu.TABLE_SCHEMA = c.TABLE_SCHEMA and c.TABLE_CATALOG =
cu.TABLE_CATALOG
and c.TABLE_NAME = cu.TABLE_NAME
and c.COLUMN_NAME = cu.COLUMN_NAME
where cu.TABLE_CATALOG = @database
order by cu.view_name,c.COLUMN_NAME
403 Forbidden error when making an ajax Post request in Django framework
this works for me
template.html
$.ajax({
url: "{% url 'XXXXXX' %}",
type: 'POST',
data: {modifica: jsonText, "csrfmiddlewaretoken" : "{{csrf_token}}"},
traditional: true,
dataType: 'html',
success: function(result){
window.location.href = "{% url 'XXX' %}";
}
});
view.py
def aggiornaAttivitaAssegnate(request):
if request.is_ajax():
richiesta = json.loads(request.POST.get('modifica'))
The relationship could not be changed because one or more of the foreign-key properties is non-nullable
This is a very big problem. What actually happens in your code is this:
- You load
Parent
from the database and get an attached entity
- You replace its child collection with new collection of detached children
- You save changes but during this operation all children are considered as added becasue EF didn't know about them till this time. So EF tries to set null to foreign key of old children and insert all new children => duplicate rows.
Now the solution really depends on what you want to do and how would you like to do it?
If you are using ASP.NET MVC you can try to use UpdateModel or TryUpdateModel.
If you want just update existing children manually, you can simply do something like:
foreach (var child in modifiedParent.ChildItems)
{
context.Childs.Attach(child);
context.Entry(child).State = EntityState.Modified;
}
context.SaveChanges();
Attaching is actually not needed (setting the state to Modified
will also attach the entity) but I like it because it makes the process more obvious.
If you want to modify existing, delete existing and insert new childs you must do something like:
var parent = context.Parents.GetById(1); // Make sure that childs are loaded as well
foreach(var child in modifiedParent.ChildItems)
{
var attachedChild = FindChild(parent, child.Id);
if (attachedChild != null)
{
// Existing child - apply new values
context.Entry(attachedChild).CurrentValues.SetValues(child);
}
else
{
// New child
// Don't insert original object. It will attach whole detached graph
parent.ChildItems.Add(child.Clone());
}
}
// Now you must delete all entities present in parent.ChildItems but missing
// in modifiedParent.ChildItems
// ToList should make copy of the collection because we can't modify collection
// iterated by foreach
foreach(var child in parent.ChildItems.ToList())
{
var detachedChild = FindChild(modifiedParent, child.Id);
if (detachedChild == null)
{
parent.ChildItems.Remove(child);
context.Childs.Remove(child);
}
}
context.SaveChanges();
Practical uses for the "internal" keyword in C#
There are cases when it makes sense to make members of classes internal
. One example could be if you want to control how the classes are instantiated; let's say you provide some sort of factory for creating instances of the class. You can make the constructor internal
, so that the factory (that resides in the same assembly) can create instances of the class, but code outside of that assembly can't.
However, I can't see any point with making classes or members internal
without specific reasons, just as little as it makes sense to make them public
, or private
without specific reasons.
Difference between "include" and "require" in php
Use include
if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.
Using require
means your script will halt if it can't load the specified file, and throw a Fatal error.
How to redirect 'print' output to a file using python?
The most obvious way to do this would be to print to a file object:
with open('out.txt', 'w') as f:
print >> f, 'Filename:', filename # Python 2.x
print('Filename:', filename, file=f) # Python 3.x
However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:
import sys
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
for i in range(2):
print('i = ', i)
sys.stdout = orig_stdout
f.close()
Since Python 3.4 there's a simple context manager available to do this in the standard library:
from contextlib import redirect_stdout
with open('out.txt', 'w') as f:
with redirect_stdout(f):
print('data')
Redirecting externally from the shell itself is another option, and often preferable:
./script.py > out.txt
Other questions:
What is the first filename in your script? I don't see it initialized.
My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.
Also, use os.path.join and os.path.basename to manipulate paths and filenames.
How can I write text on a HTML5 canvas element?
It is really easy to write text on a canvas. It was not clear if you want someone to enter text in the HTML page and then have that text appear on the canvas, or if you were going to use JavaScript to write the information to the screen.
The following code will write some text in different fonts and formats to your canvas. You can modify this as you wish to test other aspects of writing onto a canvas.
<canvas id="YourCanvasNameHere" width="500" height="500">Canvas not supported</canvas>
var c = document.getElementById('YourCanvasNameHere');
var context = c.getContext('2d'); //returns drawing functions to allow the user to draw on the canvas with graphic tools.
You can either place the canvas ID tag in the HTML and then reference the name or you can create the canvas in the JavaScript code. I think that for the most part I see the <canvas>
tag in the HTML code and on occasion see it created dynamically in the JavaScript code itself.
Code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = 'bold 10pt Calibri';
context.fillText('Hello World!', 150, 100);
context.font = 'italic 40pt Times Roman';
context.fillStyle = 'blue';
context.fillText('Hello World!', 200, 150);
context.font = '60pt Calibri';
context.lineWidth = 4;
context.strokeStyle = 'blue';
context.strokeText('Hello World!', 70, 70);
Get Max value from List<myType>
Okay, so if you don't have LINQ, you could hard-code it:
public int FindMaxAge(List<MyType> list)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxAge = int.MinValue;
foreach (MyType type in list)
{
if (type.Age > maxAge)
{
maxAge = type.Age;
}
}
return maxAge;
}
Or you could write a more general version, reusable across lots of list types:
public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxValue = int.MinValue;
foreach (T item in list)
{
int value = projection(item);
if (value > maxValue)
{
maxValue = value;
}
}
return maxValue;
}
You can use this with:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
Or you could use LINQBridge :)
In each case, you can return the if block with a simple call to Math.Max
if you want. For example:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
Convert DataTable to CSV stream
If you wish to stream the CSV out to the user without creating a file then I found the following to be the simplest method. You can use any extension/method to create the ToCsv() function (which returns a string based on the given DataTable).
var report = myDataTable.ToCsv();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(report);
Response.Buffer = true;
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=report.csv");
Response.ContentType = "text/csv";
Response.BinaryWrite(bytes);
Response.End();
Change route params without reloading in Angular 2
I use this way to get it:
const queryParamsObj = {foo: 1, bar: 2, andThis: 'text'};
this.location.replaceState(
this.router.createUrlTree(
[this.locationStrategy.path().split('?')[0]], // Get uri
{queryParams: queryParamsObj} // Pass all parameters inside queryParamsObj
).toString()
);
-- EDIT --
I think that I should add some more informations for this.
If you use this.location.replaceState()
router of your application is not updated, so if you use router information later it's not equal for this in your browser. For example if you use localizeService
to change language, after switch language your application back to last URL where you was before change it with this.location.replaceState()
.
If you don't want this behaviour you can chose different method for update URL, like:
this.router.navigate(
[this.locationStrategy.path().split('?')[0]],
{queryParams: queryParamsObj}
);
In this option your browser also doesn't refresh but your URL
change is also injected into Router
of your application, so when you switch language you don't have problem like in this.location.replaceState()
.
Of course you can choose method for your needs. The first is more lighter because you don't engage your application more than change URL
in browser.
How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?
I tried opening my Credential Manager but could not find any credentials in there that has any relation to my TFS account.
So what I did instead I logout of my hotmail account in Internet Explorer and then clear all my Internet Explorer cookies and stored password as detailed in this blog: Changing TFS credentials in Visual Studio 2012
After clearing out the cookies and password, restart IE and then relogin to your hotmail (or windows live account).
Then start Visual Studio and try to reconnect to TFS, you should be prompted for a credential now.
Note: A reader said that you do not have to clear out all IE cookies, just these 3 cookies, but I didn't test this.
cookie:@login.live.com/
cookie:@visualstudio.com/
cookie:@tfs.app.visualstudio.com/
Java 8 Stream API to find Unique Object matching a property value
Instead of using a collector try using findFirst
or findAny
.
Optional<Person> matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findFirst();
This returns an Optional
since the list might not contain that object.
If you're sure that the list always contains that person you can call:
Person person = matchingObject.get();
Be careful though! get
throws NoSuchElementException
if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent
or better, use ifPresent
, map
, orElse
or any of the other alternatives found in the Optional
class).
If you're okay with a null
reference if there is no such person, then:
Person person = matchingObject.orElse(null);
If possible, I would try to avoid going with the null
reference route though. Other alternatives methods in the Optional class (ifPresent
, map
etc) can solve many use cases. Where I have found myself using orElse(null)
is only when I have existing code that was designed to accept null
references in some cases.
Optionals have other useful methods as well. Take a look at Optional javadoc.
What is an uber jar?
A self-contained, executable Java archive. In the case of WildFly Swarm uberjars, it is a single .jar file containing your application, the portions of WildFly required to support it, an internal Maven repository of dependencies, plus a shim to bootstrap it all. see this
Android: I am unable to have ViewPager WRAP_CONTENT
This ViewPager only resizes to the current visible children (not the biggest of its actual children)
The idea from https://stackoverflow.com/a/56325869/4718406
public class DynamicHeightViewPager extends ViewPager {
public DynamicHeightViewPager (Context context) {
super(context);
initPageChangeListener();
}
public DynamicHeightViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
initPageChangeListener();
}
private void initPageChangeListener() {
addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
requestLayout();
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//View child = getChildAt(getCurrentItem());
View child = getCurrentView(this);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
View getCurrentView(ViewPager viewPager) {
try {
final int currentItem = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams)
child.getLayoutParams();
Field f = layoutParams.getClass().getDeclaredField("position");
//NoSuchFieldException
f.setAccessible(true);
int position = (Integer) f.get(layoutParams); //IllegalAccessException
if (!layoutParams.isDecor && currentItem == position) {
return child;
}
}
} catch (NoSuchFieldException e) {
e.fillInStackTrace();
} catch (IllegalArgumentException e) {
e.fillInStackTrace();
} catch (IllegalAccessException e) {
e.fillInStackTrace();
}
return null;
}
}
How do you return a JSON object from a Java Servlet
I used Jackson to convert Java Object to JSON string and send as follows.
PrintWriter out = response.getWriter();
ObjectMapper objectMapper= new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(MyObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonString);
out.flush();
Application Installation Failed in Android Studio
I had the same issue in Android studio 2.3 when I tried to test the app using Xiaomi's Mi5 and Mi4 phones. Disabling instant run didn't help me. So here is what I did.
Turn Off MIUI optimization in the Developer Options in the phone.
Then the device will be rebooted and then you'll be able to test the app over the phone.
Using this method you can still use instant run option in android studio. So this will fix your problem at least temporary. Hope that we'll be able to use MIUI optimization in the near future updates :)
PyLint "Unable to import" error - how to set PYTHONPATH?
First, go to your VS Code then press "ctrl + shift + p"
Then search settings.json
Then paste the below code inside the settings.jason.I hope the problem will be solved.
{
"python.pythonPath": "venv/bin/python",
"python.linting.pylintPath": "venv/bin/pylint"
}
What is the naming convention in Python for variable and function names?
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething()
than SomeClass.do_something()
. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
Difference between single and double quotes in Bash
The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a
as well as an indexed array arr
.
If we set
a=apple # a simple variable
arr=(apple) # an indexed array with a single element
and then echo
the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.
# |
Expression |
Result |
Comments |
1 |
"$a" |
apple |
variables are expanded inside "" |
2 |
'$a' |
$a |
variables are not expanded inside '' |
3 |
"'$a'" |
'apple' |
'' has no special meaning inside "" |
4 |
'"$a"' |
"$a" |
"" is treated literally inside '' |
5 |
'\'' |
invalid |
can not escape a ' within '' ; use "'" or $'\'' (ANSI-C quoting) |
6 |
"red$arocks" |
red |
$arocks does not expand $a ; use ${a}rocks to preserve $a |
7 |
"redapple$" |
redapple$ |
$ followed by no variable name evaluates to $ |
8 |
'\"' |
\" |
\ has no special meaning inside '' |
9 |
"\'" |
\' |
\' is interpreted inside "" but has no significance for ' |
10 |
"\"" |
" |
\" is interpreted inside "" |
11 |
"*" |
* |
glob does not work inside "" or '' |
12 |
"\t\n" |
\t\n |
\t and \n have no special meaning inside "" or '' ; use ANSI-C quoting |
13 |
"`echo hi`" |
hi |
`` and $() are evaluated inside "" (backquotes are retained in actual output) |
14 |
'`echo hi`' |
echo hi |
`` and $() are not evaluated inside '' (backquotes are retained in actual output) |
15 |
'${arr[0]}' |
${arr[0]} |
array access not possible inside '' |
16 |
"${arr[0]}" |
apple |
array access works inside "" |
17 |
$'$a\'' |
$a' |
single quotes can be escaped inside ANSI-C quoting |
18 |
"$'\t'" |
$'\t' |
ANSI-C quoting is not interpreted inside "" |
19 |
'!cmd' |
!cmd |
history expansion character '!' is ignored inside '' |
20 |
"!cmd" |
cmd args |
expands to the most recent command matching "cmd" |
21 |
$'!cmd' |
!cmd |
history expansion character '!' is ignored inside ANSI-C quotes |
See also:
How do I set GIT_SSL_NO_VERIFY for specific repos only?
On Linux, if you call this inside the git repository folder:
git config http.sslVerify false
this will add sslVerify = false
in the [http]
section of the config
file in the .git
folder, which can also be the solution, if you want to add this manually with nano .git/config
:
...
[http]
sslVerify = false
Jquery Validate custom error message location
What you should use is the errorLabelContainer
_x000D_
_x000D_
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorElement : 'div',_x000D_
errorLabelContainer: '.errorTxt'_x000D_
});_x000D_
});
_x000D_
.errorTxt{_x000D_
border: 1px solid red;_x000D_
min-height: 20px;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" />_x000D_
<input type="text" name="second" />_x000D_
<div class="errorTxt"></div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_
If you want to retain your structure then
_x000D_
_x000D_
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorPlacement: function(error, element) {_x000D_
var placement = $(element).data('error');_x000D_
if (placement) {_x000D_
$(placement).append(error)_x000D_
} else {_x000D_
error.insertAfter(element);_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
#errNm1 {_x000D_
border: 1px solid red;_x000D_
}_x000D_
#errNm2 {_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" data-error="#errNm1" />_x000D_
<input type="text" name="second" data-error="#errNm2" />_x000D_
<div class="errorTxt">_x000D_
<span id="errNm2"></span>_x000D_
<span id="errNm1"></span>_x000D_
</div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_
Iterating over a 2 dimensional python list
This is the correct way.
>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
for j in range(len(x[i])):
print(x[i][j])
0,0
0,1
1,0
1,1
2,0
2,1
>>>
Rotating a point about another point (2D)
This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.
https://dotnetfiddle.net/btmjlG
using System;
public class Program
{
public static void Main()
{
var angle = 180 * Math.PI/180;
Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
}
static Point rotate_point(double cx, double cy, double angle, Point p)
{
double s = Math.Sin(angle);
double c = Math.Cos(angle);
// translate point back to origin:
p.X -= cx;
p.Y -= cy;
// rotate point
double Xnew = p.X * c - p.Y * s;
double Ynew = p.X * s + p.Y * c;
// translate point back:
p.X = Xnew + cx;
p.Y = Ynew + cy;
return p;
}
class Point
{
public double X;
public double Y;
public string Print(){
return $"{X},{Y}";
}
}
}
Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...
How do I make a Docker container start automatically on system boot?
If you want the container to be started even if no user has performed a login (like the VirtualBox VM that I only start and don't want to login each time). Here are the steps I performed to for Ubuntu 16.04 LTS. As an example, I installed a oracle db container:
$ docker pull alexeiled/docker-oracle-xe-11g
$ docker run -d --name=MYPROJECT_oracle_db --shm-size=2g -p 1521:1521 -p 8080:8080 alexeiled/docker-oracle-xe-11g
$ vim /etc/systemd/system/docker-MYPROJECT-oracle_db.service
and add the following content:
[Unit]
Description=Redis container
Requires=docker.service
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker start -a MYPROJECT_oracle_db
ExecStop=/usr/bin/docker stop -t 2 MYPROJECT_oracle_db
[Install]
WantedBy=default.target
and enable the service at startup
sudo systemctl enable docker-MYPROJECT-oracle_db.service
For more informations https://docs.docker.com/engine/admin/host_integration/
How to split a delimited string in Ruby and convert it to an array?
For String Integer
without space as String
arr = "12345"
arr.split('')
output: ["1","2","3","4","5"]
For String Integer
with space as String
arr = "1 2 3 4 5"
arr.split(' ')
output: ["1","2","3","4","5"]
For String Integer
without space as Integer
arr = "12345"
arr.split('').map(&:to_i)
output: [1,2,3,4,5]
For String
arr = "abc"
arr.split('')
output: ["a","b","c"]
Explanation:
arr
-> string which you're going to perform any action.
split()
-> is an method, which split the input and store it as array.
''
or ' '
or ','
-> is an value, which is needed to be removed from given string.
How to check for null in Twig?
//test if varibale exist
{% if var is defined %}
//todo
{% endif %}
//test if variable is not null
{% if var is not null %}
//todo
{% endif %}
How to use executables from a package installed locally in node_modules?
If you want to keep npm, then npx should do what you need.
If switching to yarn (a npm replacement by facebook) is an option for you, then you can call:
yarn yourCmd
scripts inside the package.json will take precedence, if none is found it will look inside the ./node_modules/.bin/
folder.
It also outputs what it ran:
$ yarn tsc
yarn tsc v0.27.5
$ "/home/philipp/rate-pipeline/node_modules/.bin/tsc"
So you don't have to setup scripts for each command in your package.json
.
If you had a script defined at .scripts
inside your package.json
:
"tsc": "tsc" // each command defined in the scripts will be executed from `./node_modules/.bin/` first
yarn tsc
would be equivalent to yarn run tsc
or npm run tsc
:
yarn tsc
yarn tsc v0.27.5
$ tsc
Python Selenium Chrome Webdriver
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
Reference: https://pypi.org/project/chromedriver-binary/
How do I center align horizontal <UL> menu?
This works for me. If I haven't misconstrued your question, you might give it a try.
_x000D_
_x000D_
div#centerDiv {_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
border: 1px solid red;_x000D_
}_x000D_
ul.centerUL {_x000D_
margin: 2px auto;_x000D_
line-height: 1.4;_x000D_
padding-left: 0;_x000D_
}_x000D_
.centerUL li {_x000D_
display: inline;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="centerDiv">_x000D_
<ul class="centerUL">_x000D_
<li><a href="http://www.amazon.com">Amazon 1</a> </li>_x000D_
<li><a href="http://www.amazon.com">Amazon 2</a> </li>_x000D_
<li><a href="http://www.amazon.com">Amazon 3</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How do you clone a Git repository into a specific folder?
Option A:
git clone [email protected]:whatever folder-name
Ergo, for right here
use:
git clone [email protected]:whatever .
Option B:
Move the .git
folder, too. Note that the .git
folder is hidden in most graphical file explorers, so be sure to show hidden files.
mv /where/it/is/right/now/* /where/I/want/it/
mv /where/it/is/right/now/.* /where/I/want/it/
The first line grabs all normal files, the second line grabs dot-files. It is also possibe to do it in one line by enabling dotglob (i.e. shopt -s dotglob
) but that is probably a bad solution if you are asking the question this answer answers.
Better yet:
Keep your working copy somewhere else, and create a symbolic link. Like this:
ln -s /where/it/is/right/now /the/path/I/want/to/use
For your case this would be something like:
ln -sfn /opt/projectA/prod/public /httpdocs/public
Which easily could be changed to test if you wanted it, i.e.:
ln -sfn /opt/projectA/test/public /httpdocs/public
without moving files around. Added -fn
in case someone is copying these lines (-f
is force, -n
avoid some often unwanted interactions with already and non-existing links).
If you just want it to work, use Option A, if someone else is going to look at what you have done, use Option C.
python: How do I know what type of exception occurred?
Most answers point to except (…) as (…):
syntax (rightly so) but at the same time nobody wants to talk about an elephant in the room, where the elephant is sys.exc_info()
function.
From the documentation of sys module (emphasis mine):
This function returns a tuple of three values that give information
about the exception that is currently being handled.
(…)
If no exception is being handled anywhere on the stack, a tuple
containing three None values is returned. Otherwise, the values
returned are (type, value, traceback). Their meaning is: type gets the
type of the exception being handled (a subclass of BaseException);
value gets the exception instance (an instance of the exception type);
traceback gets a traceback object (see the Reference Manual) which
encapsulates the call stack at the point where the exception
originally occurred.
I think the sys.exc_info()
could be treated as the most direct answer to the original question of How do I know what type of exception occurred?
Should I Dispose() DataSet and DataTable?
I call dispose anytime an object implements IDisposeable. It's there for a reason.
DataSets can be huge memory hogs. The sooner they can be marked for clean up, the better.
update
It's been 5 years since I answered this question. I still agree with my answer. If there is a dispose method, it should be called when you are done with the object. The IDispose interface was implemented for a reason.
Javascript set img src
You need to set
document["pic1"].src = searchPic.src;
The searchPic itself is your Image(), you need to read the src that you set.
What does a just-in-time (JIT) compiler do?
Just In Time compiler also known as JIT compiler is used for
performance improvement in Java. It is enabled by default. It is
compilation done at execution time rather earlier.
Java has popularized the use of JIT compiler by including it in
JVM.
how to add script src inside a View when using Layout
If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
var divLength = $('div').length;
alert(divLength);
});
</script>
Parsing XML with namespace in Python via 'ElementTree'
I've been using similar code to this and have found it's always worth reading the documentation... as usual!
findall() will only find elements which are direct children of the current tag. So, not really ALL.
It might be worth your while trying to get your code working with the following, especially if you're dealing with big and complex xml files so that that sub-sub-elements (etc.) are also included.
If you know yourself where elements are in your xml, then I suppose it'll be fine! Just thought this was worth remembering.
root.iter()
ref: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements
"Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:"
Stop jQuery .load response from being cached
You have to use a more complex function like $.ajax()
if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
Center div on the middle of screen
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
Spring Test & Security: How to mock authentication?
Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
mockMvc.perform(get("/someApi"))
.andExpect(status().isOk());
}
Remember to add the following dependency to your project
'org.springframework.security:spring-security-test:4.2.3.RELEASE'
SQL Stored Procedure set variables using SELECT
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)
I had the same issue on Mac OS X (installed with homebrew), and the .npmrc is not the only place node stored config variables. There is a glocal npmrc config file in /usr/local/etc that you have to edit using this command:
sudo nano npmrc
Remove the ca=
line, or whatever the config setting was that broke your install, save that file, and try npm again, and you should see it working.
Get url parameters from a string in .NET
You can use the following workaround for it to work with the first parameter too:
var param1 =
HttpUtility.ParseQueryString(url.Substring(
new []{0, url.IndexOf('?')}.Max()
)).Get("param1");
Send PHP variable to javascript function
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
Add "Appendix" before "A" in thesis TOC
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
unique object identifier in javascript
If you came here because you deal with class instances like me you can use static vars/methods to reference instances by a custom unique id:
_x000D_
_x000D_
class Person {
constructor( name ) {
this.name = name;
this.id = Person.ix++;
Person.stack[ this.id ] = this;
}
}
Person.ix = 0;
Person.stack = {};
Person.byId = id => Person.stack[ id ];
let store = {};
store[ new Person( "joe" ).id ] = true;
store[ new Person( "tim" ).id ] = true;
for( let id in store ) {
console.log( Person.byId( id ).name );
}
_x000D_
_x000D_
_x000D_
convert xml to java object using jaxb (unmarshal)
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
jquery if div id has children
This snippet will determine if the element has children using the :parent
selector:
if ($('#myfav').is(':parent')) {
// do something
}
Note that :parent
also considers an element with one or more text nodes to be a parent.
Thus the div
elements in <div>some text</div>
and <div><span>some text</span></div>
will each be considered a parent but <div></div>
is not a parent.
Convert spark DataFrame column to python list
I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv'])
is the fastest method. I'm very surprised.
I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.
Here's the benchmarking results (runtimes in seconds):
+-------------------------------------------------------------+---------+-------------+
| Code | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect() | 0.4 | 55.3 |
| list(df.select('col_name').toPandas()['col_name']) | 0.4 | 17.5 |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()| 0.9 | 69 |
| [row[0] for row in df.select('col_name').collect()] | 1.0 | OOM |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] | 1.2 | * |
+-------------------------------------------------------------+---------+-------------+
* cancelled after 800 seconds
Golden rules to follow when collecting data on the driver node:
- Try to solve the problem with other approaches. Collecting data to the driver node is expensive, doesn't harness the power of the Spark cluster, and should be avoided whenever possible.
- Collect as few rows as possible. Aggregate, deduplicate, filter, and prune columns before collecting the data. Send as little data to the driver node as you can.
toPandas
was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.
See here for more details / benchmarking results.
How do you reinstall an app's dependencies using npm?
For Windows you can use
(if exist node_modules rmdir node_modules /q /s) && npm install
which removes node_modules
directory and performs npm install
then. Removal before install assures that all packages are reinstalled.
PostgreSQL psql terminal command
These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.
Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):
psql -h host -p 5900 -U username database
\pset format aligned
Atom menu is missing. How do I re-enable
Get cursor on top, where white header with file name, then press Alt.
To set top menu by default always visible.
You needed in top menu selected:
FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false)
Save it.
Bootstrap 3 Gutter Size
I don't think Bass's answer is correct. Why touch the row margins? They have a negative margin to offset the column padding for the columns on the edge of the row. Messing with this will break any nested rows.
The answer is simple, just make the container padding equal to the gutter size:
e.g for default bootstrap:
.container {
padding-left:30px;
padding-right:30px;
}
http://jsfiddle.net/3wBE3/61/
How to show all rows by default in JQuery DataTable
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
Variables declared outside function
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
Code for printf function in C
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
See here.
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
PHP Get name of current directory
getcwd();
or
dirname(__FILE__);
or (PHP5)
basename(__DIR__)
http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
You can use basename()
to get the trailing part of the path :)
In your case, I'd say you are most likely looking to use getcwd()
, dirname(__FILE__)
is more useful when you have a file that needs to include another library and is included in another library.
Eg:
main.php
libs/common.php
libs/images/editor.php
In your common.php
you need to use functions in editor.php
, so you use
common.php
:
require_once dirname(__FILE__) . '/images/editor.php';
main.php
:
require_once libs/common.php
That way when common.php is require'd
in main.php
, the call of require_once
in common.php
will correctly includes editor.php
in images/editor.php
instead of trying to look in current directory where main.php
is run.
What does \d+ mean in regular expression terms?
\d
is a digit (a character in the range 0-9), and +
means 1 or more times. So, \d+
is 1 or more digits.
This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.
Hibernate error: ids for this class must be manually assigned before calling save():
For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that
private String U_id;
will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue
annotation or by assigning a value manually.
In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id
, e.g.
public Role (String U_id) { ... }
This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.
Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role
using the default constructor, just declare it as private
.
Creating a PDF from a RDLC Report in the Background
private void PDFExport(LocalReport report)
{
string[] streamids;
string minetype;
string encod;
string fextension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
out warnings);
using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
{
fs.Write(rpbybe , 0, rpbybe .Length);
}
}
How to create a button programmatically?
Swift 3
let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.setTitle("Button", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
self.view.addSubview(btn)
func clickMe(sender:UIButton!) {
print("Button Clicked")
}
Output
Are types like uint32, int32, uint64, int64 defined in any stdlib header?
The C99 stdint.h
defines these:
int8_t
int16_t
int32_t
uint8_t
uint16_t
uint32_t
And, if the architecture supports them:
There are various other integer typedefs in stdint.h
as well.
If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.
The uint32
and uint64
(i.e. without the _t
suffix) are probably application specific.
Windows 7 SDK installation failure
All of these (and other) solutions have failed completely for me so I figured out another.
You need the offline installation package (mine was x64), and you need to manually install only the samples. Opening the ISO-file with, for example, 7-Zip from location Setup\WinSDKSamples_amd64
and running WinSDKSamples_amd64.msi
did this for me.
Then you just use the normal setup file to REPAIR the installation and choose whatever components you wish.
Media query to detect if device is touchscreen
I would suggest using modernizr and using its media query features.
if (Modernizr.touch){
// bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
// bind to normal click, mousemove, etc
}
However, using CSS, there are pseudo class like, for example in Firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browser.
For Apple devices, you can simple use:
if(window.TouchEvent) {
//.....
}
Especially for Ipad:
if(window.Touch) {
//....
}
But, these do not work on Android.
Modernizr gives feature detection abilities, and detecting features is
a good way to code, rather than coding on basis of browsers.
Styling Touch Elements
Modernizer adds classes to the HTML tag for this exact purpose. In this case, touch
and no-touch
so you can style your touch related aspects by prefixing your selectors with .touch. e.g. .touch .your-container
. Credits: Ben Swinburne
How to convert a single char into an int
Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)
(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)
How to use XMLReader in PHP?
It all depends on how big the unit of work, but I guess you're trying to treat each <product/>
nodes in succession.
For that, the simplest way would be to use XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use. For instance:
$z = new XMLReader;
$z->open('data.xml');
$doc = new DOMDocument;
// move to the first <product /> node
while ($z->read() && $z->name !== 'product');
// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
// either one should work
//$node = new SimpleXMLElement($z->readOuterXML());
$node = simplexml_import_dom($doc->importNode($z->expand(), true));
// now you can use $node without going insane about parsing
var_dump($node->element_1);
// go to next <product />
$z->next('product');
}
Quick overview of pros and cons of different approaches:
XMLReader only
Pros: fast, uses little memory
Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain
XMLReader + SimpleXML
Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.
Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.
XMLReader + DOM
Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom()
but it doesn't seem to work in that case
Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.
My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.
WAMP 403 Forbidden message on Windows 7
hi there are 2 solutions :
change the port 80 to 81 in the text file (httpd.conf)
and click 127.0.0.1:81
change setting the network
go to control panel--network and internet--network and sharing center
click-->local area connection
select-->propertis
check true in the -allow other .....
and --- allo other .....
Listing information about all database files in SQL Server
I am using script to get empty space in each file:
Create Table ##temp
(
DatabaseName sysname,
Name sysname,
physical_name nvarchar(500),
size decimal (18,2),
FreeSpace decimal (18,2)
)
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (DatabaseName, Name, physical_name, Size, FreeSpace)
Select DB_NAME() AS [DatabaseName], Name, physical_name,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) as nvarchar) Size,
Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) -
Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2)) as nvarchar) As FreeSpace
From sys.database_files
'
Select * From ##temp
drop table ##temp
Size is expressed in KB.
Array Size (Length) in C#
What has been missed so far is what I suddenly was irritated about:
How do I know the amount of items inside the array? Is .Length
equal .Count
of a List?
The answer is: the amount of items of type X which have been put into an array of type X created with new X[number]
you have to carry yourself!
Eg. using a counter: int countItemsInArray = 0
and countItemsInArray++
for every assignment to your array.
(The array just created with new X[number]
has all space for number
items (references) of type X already allocated, you can assign to any place inside as your first assignment, for example (if number
= 100 and the variable name = a
) a[50] = new X();
.
I don't know whether C# specifies the initial value of each place inside an array upon creation, if it doesn't or the initial value you cannot compare to (because it might be a value you yourself have put into the array), you would have to track which places inside the array you already assigned to too if you don't assign sequentially starting from 0
(in which case all places smaller than countItemsInArray
would be assigned to).)
In your question size of an array (length / number of items) depending on whether / is meant to stand for "alternative" or "divide by" the latter still has to be covered (the "number of items" I just gave as "amount of items" and others gave .Length
which corresponds to the value of number
in my code above):
C# has a sizeof
operator (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof). It's safe to use for built-in types (such as int) (and only operates on types (not variables)). Thus the size of an array b
of type int
in bytes would be b.Length * sizeof(int)
.
(Due to all space of an array already being allocated on creation, like mentioned above, and sizeof
only working on types, no code like sizeof(variable)/sizeof(type)
would work or yield the amount of items without tracking.)
Find nearest value in numpy array
IF your array is sorted and is very large, this is a much faster solution:
def find_nearest(array,value):
idx = np.searchsorted(array, value, side="left")
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return array[idx-1]
else:
return array[idx]
This scales to very large arrays. You can easily modify the above to sort in the method if you can't assume that the array is already sorted. It’s overkill for small arrays, but once they get large this is much faster.
How to change the minSdkVersion of a project?
Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.
Also look for your project's build.gradle file and update the min sdk version.
How to force Eclipse to ask for default workspace?
I had the same issue (in Eclipse Juno), but I just wanted to change the default workspace to the one I'm using. There is a setting in:
ECLIPSE_DIRECTORY/configuration/config.ini
that is causing a specific workspace to be loaded without prompting for a workspace. If you just want to change the default workspace, you can just modify the value or add it if it doesn't exist:
[email protected]/some_workspace
or
osgi.instance.area.default=/some/absolute/path/some_workspace
python numpy/scipy curve fitting
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
Git Push ERROR: Repository not found
If your repo was working normally before, and suddenly this error pops up, most likely the reason would be that your git is authenticated as some other user, that does not have access to the repository. So, in order to push, all you need to do is, specify your correct username and password in your git command. So, a push command for a github repo would look like:
git push https://youruser:[email protected]/user/reponame.git
username and password
needs to be url-escaped, so an @ should be replaced by %40, and so on.
Undo a git stash
This will also restore the staging directory:
git stash apply --index
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How do I activate a virtualenv inside PyCharm's terminal?
Solution for WSL (Ubuntu on Windows)
If you're using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.
Use a .pycharmrc
file like described in Peter Gibson's answer; Add the .pycharmrc
file to your home directory with following content:
source ~/.bashrc
source ~/path_to_virtualenv/bin/activate
In Pycharm File > Settings > Tools > Terminal add the following 'Shell path':
"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"
Project specific virtualenv
The path to your virtualenv in .pycharmrc
does not have to be absolute. You can set a project specific virtualenv by setting a relative path from your project directory.
My virtualenv is always located in a 'venv' folder under my project directory, so my .pycharmrc
file looks like this:
source ~/.bashrc
source ~/pycharmvenv/bin/activate #absolute path
source ./venv/bin/activate #relative path
BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter
Add the following to your .pycharmrc
file:
if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
sudo service ssh start
fi
This checks if a ssh tunnel is already opened, and opens one otherwise.
In File -> Settings -> Project -> Project Interpreter in Pycharm, add a new remote interpreter with following configuration:
+--------------------------+---------------------------------+-------+----+
| Name: | <Interpreter name> | | |
| Select | 'SSH Credentials' | | |
| Host: | 127.0.0.1 | Port: | 22 |
| User: | <Linux username> | | |
| Auth type: | 'Password' | | |
| Password: | <Linux password> | | |
| Python interpreter path: | <Linux path to your virtualenv> | | |
| Python helpers path: | <Set automatically> | | |
+--------------------------+---------------------------------+-------+----+
Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.
warning: the last update in Windows automatically starts a SshBroker and SshProxy service on startup. These block the ssh tunnel from linux to windows. You can stop these services in Task Manager -> Services, after which everything will work again.
How can I upgrade NumPy?
If you are stuck with a machine where you don't have root access, then it is better to deal with a custom Python installation.
The Anaconda installation worked like a charm:
After installation,
[bash]$ /xxx/devTools/python/anaconda/bin/pip list --format=columns |
grep numpy
numpy 1.13.3 numpydoc
0.7.0
Why is AJAX returning HTTP status code 0?
For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.
Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.
Javascript to stop HTML5 video playback on modal window close
For anyone struggling with this issue with videos embedded using the <object>
tag, the function you want is Quicktime's element.Stop();
For example, to stop any and all playing movies, use:
var videos = $("object");
for (var i=0; i < videos.length; i++)
{
if (videos[i].Stop) { videos[i].Stop(); }
}
Note the non-standard capital "S" on Stop();
Unable to convert MySQL date/time value to System.DateTime
Pull the datetime value down as a string and do a DateTime.ParseExact(value, "ddd MMM dd hh:mm:ss yyyy", culture, styles);
You would just need to set the date format up for the date you are returning from the database. Most likely it's yyyy-MM-dd HH:mm:ss
. At least is is for me.
Check here more info on the DateTime.ParseExact
Using custom fonts using CSS?
Generically, you can use a custom font using @font-face
in your CSS. Here's a very basic example:
@font-face {
font-family: 'YourFontName'; /*a name to be used later*/
src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}
Then, trivially, to use the font on a specific element:
.classname {
font-family: 'YourFontName';
}
(.classname
is your selector).
Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.
You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face
rules, so you don't have to write your own).
while also preventing people from having free access to download the font, if possible
Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.
I hope that helped!
How can I alter a primary key constraint using SQL syntax?
Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create.
If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there.
You have to make sure you have enough space for this.
Find Item in ObservableCollection without using a loop
You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.
Regular expression to match balanced parentheses
Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.
Lua
Use %b()
(%b{}
/ %b[]
for curly braces / square brackets):
for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end
(see demo)
Raku (former Perl6):
Non-overlapping multiple balanced parentheses matches:
my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)
Overlapping multiple balanced parentheses matches:
say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)
See demo.
Python re
non-regex solution
See poke's answer for How to get an expression between balanced parentheses.
Java customizable non-regex solution
Here is a customizable solution allowing single character literal delimiters in Java:
public static List<String> getBalancedSubstrings(String s, Character markStart,
Character markEnd, Boolean includeMarkers)
{
List<String> subTreeList = new ArrayList<String>();
int level = 0;
int lastOpenDelimiter = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == markStart) {
level++;
if (level == 1) {
lastOpenDelimiter = (includeMarkers ? i : i + 1);
}
}
else if (c == markEnd) {
if (level == 1) {
subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
}
if (level > 0) level--;
}
}
return subTreeList;
}
}
Sample usage:
String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]
How to assign name for a screen?
To create a new screen with the name foo
, use
screen -S foo
Then to reattach it, run
screen -r foo # or use -x, as in
screen -x foo # for "Multi display mode" (see the man page)
Multiple Inheritance in C#
In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.
Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.
Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.
Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.
Regular expression for address field validation
Here is the approach I have taken to finding addresses using regular expressions:
A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.
Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.
import re
strings = [
'701 FIFTH AVE',
'2157 Henderson Highway',
'Attn: Patent Docketing',
'HOLLYWOOD, FL 33022-2480',
'1940 DUKE STREET',
'111 MONUMENT CIRCLE, SUITE 3700',
'c/o Armstrong Teasdale LLP',
'1 Almaden Boulevard',
'999 Peachtree Street NE',
'P.O. BOX 2903',
'2040 MAIN STREET',
'300 North Meridian Street',
'465 Columbus Avenue',
'1441 SEAMIST DR.',
'2000 PENNSYLVANIA AVENUE, N.W.',
'465 Columbus Avenue',
'28 STATE STREET',
'P.O, Drawer 800889.',
'2200 CLARENDON BLVD.',
'840 NORTH PLANKINTON AVENUE',
'1025 Connecticut Avenue, NW',
'340 Commercial Street',
'799 Ninth Street, NW',
'11318 Lazarro Ln',
'P.O, Box 65745',
'c/o Ballard Spahr LLP',
'8210 SOUTHPARK TERRACE',
'1130 Connecticut Ave., NW, Suite 420',
'465 Columbus Avenue',
"BANNER & WITCOFF , LTD",
"CHIP LAW GROUP",
"HAMMER & ASSOCIATES, P.C.",
"MH2 TECHNOLOGY LAW GROUP, LLP",
]
patterns = [
"c\/o [\w ]{2,}",
"C\/O [\w ]{2,}",
"P.O\. [\w ]{2,}",
"P.O\, [\w ]{2,}",
"[\w\.]{2,5} BOX [\d]{2,8}",
"^[#\d]{1,7} [\w ]{2,}",
"[A-Z]{2,2} [\d]{5,5}",
"Attn: [\w]{2,}",
"ATTN: [\w]{2,}",
"Attention: [\w]{2,}",
"ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
pat_no = 1
for pattern in patterns:
match = re.search(pattern, string.strip())
if match:
print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
found_count += 1
pat_no += 1
print("-- Total: " + str(total_count) + " Found: " + str(found_count))
Java - escape string to prevent SQL injection
You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.
public class SQLInjectionEscaper {
public static String escapeString(String x, boolean escapeDoubleQuotes) {
StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);
int stringLength = x.length();
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
sBuilder.append('\\');
sBuilder.append('0');
break;
case '\n': /* Must be escaped for logs */
sBuilder.append('\\');
sBuilder.append('n');
break;
case '\r':
sBuilder.append('\\');
sBuilder.append('r');
break;
case '\\':
sBuilder.append('\\');
sBuilder.append('\\');
break;
case '\'':
sBuilder.append('\\');
sBuilder.append('\'');
break;
case '"': /* Better safe than sorry */
if (escapeDoubleQuotes) {
sBuilder.append('\\');
}
sBuilder.append('"');
break;
case '\032': /* This gives problems on Win32 */
sBuilder.append('\\');
sBuilder.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
// fall through
default:
sBuilder.append(c);
}
}
return sBuilder.toString();
}
}
HTML5 placeholder css padding
I had similar issue, my problem was with the side padding, and the solution was with, text-indent, I wasn't realize that text indent effect the placeholder side position.
input{
text-indent: 10px;
}
Pass variables to AngularJS controller, best practice?
I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.
The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.
I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.
My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.
class Basket extends Array
constructor: ->
add: (item) ->
@push(item)
remove: (item) ->
index = @indexOf(item)
@.splice(index, 1)
contains: (item) ->
@indexOf(item) isnt -1
indexOf: (item) ->
indexOf = -1
@.forEach (stored_item, index) ->
if (item.id is stored_item.id)
indexOf = index
return indexOf
Then you initialize this in your controller and create a function for that action:
$scope.basket = new Basket()
$scope.addItemToBasket = (item) ->
$scope.basket.add(item)
Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:
li ng-repeat="item in items"
a href="#" ng-click="addItemToBasket(item)"
Adobe Acrobat Pro make all pages the same dimension
The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.
An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.
BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.
Hope this helps :)
Any way to break if statement in PHP?
The simple answer is that no, there isn't a way to break from an if
statement without completely stopping the execution (via exit
). Other solutions won't work for me because I can't change the structure of the if
statement, since I'm injecting code into a plugin, like so:
if ( condition ) {
// Code and variables I want to use
// Code I have control over
// Code I don't want to run
}
// More code I want to use
Group by month and year in MySQL
I prefer
SELECT
MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
trading_summary t
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime);
Detect if the device is iPhone X
All the answers that are using the height
are only half part of the story for one reason. If you're going to check like that when device orientation is landscapeLeft
or landscapeRight
the check will fail, because the height
is swapped out with the width
.
That's why my solution looks like this in Swift 4.0:
extension UIScreen {
///
static var isPhoneX: Bool {
let screenSize = UIScreen.main.bounds.size
let width = screenSize.width
let height = screenSize.height
return min(width, height) == 375 && max(width, height) == 812
}
}
How to create full compressed tar file using Python?
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
tar.add(name)
tar.close()
If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".
How to set bootstrap navbar active class with Angular JS?
This is a simple solution
<ul class="nav navbar-nav navbar-right navbar-default menu">
<li ng-class="menuIndice == 1 ? 'active':''">
<a ng-click="menuIndice = 1" href="#/item1">item1</a>
</li>
<li ng-class="menuIndice == 2 ? 'active':''">
<a ng-click="menuIndice = 2" href="#/item2">item2</a>
</li>
<li ng-class="menuIndice == 3 ? 'active':''">
<a ng-click="menuIndice = 3" href="#/item3">item3</a>
</li>
</ul>
How to trigger click event on href element
I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:
$('#elementid').mousedown();
Resize Cross Domain Iframe Height
If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe
container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>
How to pass multiple parameters to a get method in ASP.NET Core
Simplest way,
Controller:
[HttpGet("empId={empId}&startDate={startDate}&endDate={endDate}")]
public IEnumerable<Validate> Get(int empId, string startDate, string endDate){}
Postman Request:
{router}/empId=1&startDate=2020-20-20&endDate=2020-20-20
Learning point: Request exact pattern will be accepted by the Controller.
2D cross-platform game engine for Android and iOS?
LibGDX is one of the best engines I've ever used, works on almost all platforms, and performs twice as fast as cocos2d-x in most tests I've done. You can use any JVM language you like. Here's a 13 part tutorial in Java, and here's a bunch using jruby. There's a good skeletal animation tool that works with it here, and it has baked in support for tiled TMX maps as well. The ui framework is awesome, and it has a scene graph and actor style API similar to cocos2d scenes, sprites and actions. The community is awesome, updates are frequent, and the documentation is good. Don't let the java part scare you, it's fast, and you can use jruby or scala or whatever you like. I highly recommend it for 2d or 3d work, it supports both.
Read file As String
With files we know the size in advance, so just read it all at once!
String result;
File file = ...;
long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
result = "";
Log.w(TAG, "File is empty or huge: " + file);
} else {
try (FileReader in = new FileReader(file)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
}
result = new String(content, 0, numRead);
}
catch (Exception ex) {
Log.e(TAG, "Failure reading " + this.file, ex);
result = "";
}
}
How to set ANDROID_HOME path in ubuntu?
If you run android with sudo it will install sdk in /root/Android/Sdk
so check if that is the case.
And if you are using dont run cordova with sudo it will look sdk in root also may be.
Above code for setting path is works fine.
Python Math - TypeError: 'NoneType' object is not subscriptable
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
How to mock static methods in c# using MOQ framework?
Another option to transform the static method into a static Func or Action. For instance.
Original code:
class Math
{
public static int Add(int x, int y)
{
return x + y;
}
You want to "mock" the Add method, but you can't. Change the above code to this:
public static Func<int, int, int> Add = (x, y) =>
{
return x + y;
};
Existing client code doesn't have to change (maybe recompile), but source stays the same.
Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:
[TestMethod]
public static void MyTest()
{
Math.Add = (x, y) =>
{
return 11;
};
Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.
This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.
[edit]
I suggest that you add the following Cleanup code to your Unit Test class:
[TestCleanup]
public void Cleanup()
{
typeof(Math).TypeInitializer.Invoke(null, null);
}
Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.
Where is the default log location for SharePoint/MOSS?
SharePoint uses a lot of different logging mechanisms. Most importantly you can configure the location of the logs through Central Admin. To give you an understanding of the logs involved, here is a quote from http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/
All file based logs can be read by
text editors and can be parsed by
using popular log parsing tools (Log
Parser 2.2 from Microsoft or Funnel
Web). It will also be a good idea to
read the IIS Logs which are generally
saved at (System
Drive):\WINDOWS\system32\LogFiles
a) Diagnostics Logs
· Event Throttling Logs –
These end up going to the Windows
Event Log and can be viewed in the
Event Viewer. They show Errors and
Warnings.
· Trace Logs – These show
detailed line by line tracing
infomration emitted during a web
request or service execution. They end
up being stored at a known location on
the front-end server. Default
Location: (System Drive):\Program
Files\Common Files\Microsoft
Shared\Web Server Extensions\12\LOGS\
b) Audit Logs - They end up in
the associated Content Database tables
and can be viewed at Site Collection
Level as well as Site Level using the
web browser. WSS 3.0 and MOSS 2007 use
different pages to show Audit Log
Reports.
c) Usage Logs – They get stored
locally on the front-end servers and
get processed both locally and at farm
level via SSP (this is based on the
setup as I understand the results from
the local processing are merged by
SSP) and can be viewed at both the
Site Level and Site Collection Level.
Default Location: (System
Drive):\Program Files\Common
Files\Microsoft Shared\Web Server
Extensions\12\Logs
d) Search\Query Logs – These are
saved in the associated SSP database
but can be viewed at SSP level via the
Web Browser and in MOSS at Site
Collection Level by going to the
settings page.
e) Information Management Logs –
Stored in the associated Content
Database and can be can be viewed at
the Site Collection Level.
f) Content and Structure Logs –
This option is only available after
one enables the publication feature.
This store is saved in the Content
Database associated with the Site
Collection and can be viewed at Site
Collection level by going to the
settings page.
Returning value from called function in a shell script
I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
# Syntax _w (wrapReturn)
# arg1 : method to wrap
# arg2 : variable to set
_w(){
eval $1
read $2 <<EOF
$?
EOF
eval $2=\$$2
}
as in (yep, the example is somewhat silly, it's just an.. example)
getDay(){
d=`date '+%d'`
[ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
return $d
}
dayzToSalary(){
daysLeft=0
if [ $1 -lt 26 ]; then
daysLeft=`expr 25 - $1`
else
lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
rest=`expr $lastDayInMonth - 25`
daysLeft=`expr 25 + $rest`
fi
echo "Mate, it's another $daysLeft days.."
}
# main
_w getDay DAY # call getDay, save the result in the DAY variable
dayzToSalary $DAY
Google Chrome Full Black Screen
i have resolved this by following steps.
1) Go to customise icon in the top right corner chrome.
2) click on
more tools option.
3) Click task manager.
4) Kill/end process GPU process
This has resolved my issue of black screen in chrome.
Why are only a few video games written in Java?
List of game engines on Wikipedia lists many game engines along with the programming language that they are written in.
There are several Java game engines listed.
Clicking some of the links will lead you to examples of games and demos written in Java. Here's a couple:
For certain games and situations, Java's trade-offs might be acceptable.
VBA Object doesn't support this property or method
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
Combining two Series into a DataFrame in pandas
Pandas will automatically align these passed in series and create the joint index
They happen to be the same here. reset_index
moves the index to a column.
In [2]: s1 = Series(randn(5),index=[1,2,4,5,6])
In [4]: s2 = Series(randn(5),index=[1,2,4,5,6])
In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
Out[8]:
index s1 s2
0 1 -0.176143 0.128635
1 2 -1.286470 0.908497
2 4 -0.995881 0.528050
3 5 0.402241 0.458870
4 6 0.380457 0.072251
How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
For those using a fresh install of Ubuntu, or another Linux distro,
make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.
At Terminal, type:
sudo apt-get install build-essential
It should be enough to compile and run your apps.
Of course, you can also perform full g++ install, using:
sudo apt-get install g++
Getting results between two dates in PostgreSQL
just had the same question, and answered this way, if this could help.
select *
from table
where start_date between '2012-01-01' and '2012-04-13'
or end_date between '2012-01-01' and '2012-04-13'
adding 1 day to a DATETIME format value
If you want to do this in PHP:
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
If you want to add the date in MySQL:
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
Can I write or modify data on an RFID tag?
I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number.
Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).
I'd recomment that you look at the OpenPCD platform if you are into development.
This is also of interest regarding the cryptographic functions in some RFID cards.
How to make a script wait for a pressed key?
I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:
import msvcrt
c = msvcrt.getch()
print 'you entered', c
mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:
import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()
Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.
iPad browser WIDTH & HEIGHT standard
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
Iterating Over Dictionary Key Values Corresponding to List in Python
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__
you can do simplify things a bit.
Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?
In my case I had a multi module project just like you. I had to change a group Id of one of the external libraries my project was depending on as shown below.
From:
<dependencyManagement>
<dependency>
<groupId>org.thirdparty</groupId>
<artifactId>calculation-api</artifactId>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependencyManagement>
To:
<dependencyManagement>
<dependency>
<groupId>org.thirdparty.module</groupId>
<artifactId>calculation-api</artifactId>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependencyManagement>
Pay attention to the <groupId> section. It turned out that I was forgetting to modifiy the corresponding section of the submodules that define this dependency in their pom files.
It drove me very crazy because the module was available locally.
How can I make visible an invisible control with jquery? (hide and show not work)
You can't do this with jQuery, visible="false"
in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;"
so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.
If you remove the visible
attribute and add the style
attribute you can then use jQuery to show it, like this:
$("#elementID").show();
Old Answer (before patrick's catch)
To change visibility
, you need to use .css()
, like this:
$("#elem").css('visibility', 'visible');
Unless you need to have the element occupy page space though, use display: none;
instead of visibility: hidden;
in your CSS, then just do:
$("#elem").show();
The .show()
and .hide()
functions deal with display
instead of visibility
, like most of the jQuery functions :)
Why does git perform fast-forward merges by default?
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?
Because your update
uses PUT method, {entryId: $scope.entryId}
is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'}
when you define your update
, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '@entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
Why use argparse rather than optparse?
At first I was as reluctant as @fmark to switch from optparse to argparse, because:
- I thought the difference was not that huge.
- Quite some VPS still provides Python 2.6 by default.
Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html
And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)
Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.
find . -type f -exec chmod 644 {} ;
Piping to xargs is a dirty way of doing that which can be done inside of find.
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;
You can be even more controlling with other options, such as:
find . -type d -user harry -exec chown daisy {} \;
You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:
- If you are root it will succeed.
- If you are in root (/) you are going to have a bad day.
- Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.
How to copy file from HDFS to the local file system
If your source "file" is split up among multiple files (maybe as the result of map-reduce) that live in the same directory tree, you can copy that to a local file with:
hadoop fs -getmerge /hdfs/source/dir_root/ local/destination
Adjust UILabel height depending on the text
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;