Reading file input from a multipart/form-data POST
How about some Regex?
I wrote this for a text a file, but I believe this could work for you
(In case your text file contains line starting exactly with the "matched" ones below - simply adapt your Regex)
private static List<string> fileUploadRequestParser(Stream stream)
{
//-----------------------------111111111111111
//Content-Disposition: form-data; name="file"; filename="data.txt"
//Content-Type: text/plain
//...
//...
//-----------------------------111111111111111
//Content-Disposition: form-data; name="submit"
//Submit
//-----------------------------111111111111111--
List<String> lstLines = new List<string>();
TextReader textReader = new StreamReader(stream);
string sLine = textReader.ReadLine();
Regex regex = new Regex("(^-+)|(^content-)|(^$)|(^submit)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
while (sLine != null)
{
if (!regex.Match(sLine).Success)
{
lstLines.Add(sLine);
}
sLine = textReader.ReadLine();
}
return lstLines;
}
Strip all non-numeric characters from string in JavaScript
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
Displaying one div on top of another
Have the style for the parent div and the child divs' set as following. It worked for my case, hope it helps you as well..
<div id="parentDiv">
<div id="backdrop"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
in your JS:
document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any
or in your CSS as in this working example:::
_x000D_
_x000D_
#parentDiv{_x000D_
background: yellow;_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
position: relative;_x000D_
}_x000D_
#backdrop{_x000D_
background: red;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
position: absolute;_x000D_
}_x000D_
#curtain{_x000D_
background: green;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
position: absolute;_x000D_
z-index: 2;_x000D_
margin: 100px 0px 150px 100px;_x000D_
}
_x000D_
<div id="parentDiv"><h2>_x000D_
THIS IS PARENT DIV_x000D_
</h2>_x000D_
<div id="backdrop"><h4>_x000D_
THIS IS BACKDROP DIV_x000D_
</h4></div>_x000D_
<div id="curtain"><h6>_x000D_
THIS IS CURTAIN DIV_x000D_
</h6></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Android : change button text and background color
Here is an example of a drawable that will be white by default, black when pressed:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid
android:color="#1E669B"/>
<stroke
android:width="2dp"
android:color="#1B5E91"/>
<corners
android:radius="6dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
<item>
<shape>
<gradient
android:angle="270"
android:endColor="#1E669B"
android:startColor="#1E669B"/>
<stroke
android:width="4dp"
android:color="#1B5E91"/>
<corners
android:radius="7dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
</selector>
How can I avoid running ActiveRecord callbacks?
Use update_column
(Rails >= v3.1) or update_columns
(Rails >= 4.0) to skip callbacks and validations. Also with these methods, updated_at
is not updated.
#Rails >= v3.1 only
@person.update_column(:some_attribute, 'value')
#Rails >= v4.0 only
@person.update_columns(attributes)
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
#2: Skipping callbacks that also works while creating an object
class Person < ActiveRecord::Base
attr_accessor :skip_some_callbacks
before_validation :do_something
after_validation :do_something_else
skip_callback :validation, :before, :do_something, if: :skip_some_callbacks
skip_callback :validation, :after, :do_something_else, if: :skip_some_callbacks
end
person = Person.new(person_params)
person.skip_some_callbacks = true
person.save
UPDATE (2020)
Apparently Rails has always supported :if
and :unless
options, so above code can be simplified as:
class Person < ActiveRecord::Base
attr_accessor :skip_some_callbacks
before_validation :do_something, unless: :skip_some_callbacks
after_validation :do_something_else, unless: :skip_some_callbacks
end
person = Person.new(person_params)
person.skip_some_callbacks = true
person.save
Using Excel VBA to export data to MS Access table
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative
Just in case some is looking for the same in MULTI-CLASS Example
def perf_measure(y_actual, y_pred):
class_id = set(y_actual).union(set(y_pred))
TP = []
FP = []
TN = []
FN = []
for index ,_id in enumerate(class_id):
TP.append(0)
FP.append(0)
TN.append(0)
FN.append(0)
for i in range(len(y_pred)):
if y_actual[i] == y_pred[i] == _id:
TP[index] += 1
if y_pred[i] == _id and y_actual[i] != y_pred[i]:
FP[index] += 1
if y_actual[i] == y_pred[i] != _id:
TN[index] += 1
if y_pred[i] != _id and y_actual[i] != y_pred[i]:
FN[index] += 1
return class_id,TP, FP, TN, FN
Most efficient way to concatenate strings in JavaScript?
I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:
For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.
is wrong, because it's based on a flawed test. That test never actually appends into the DOM.
This fixed test shows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.
(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)
Only detect click event on pseudo-element
No,but you can do like this
In html file add this section
<div class="arrow">
</div>
In css you can do like this
p div.arrow {
content: '';
position: absolute;
left:100%;
width: 10px;
height: 100%;
background-color: red;
}
Hope it will help you
How to compress a String in Java?
If the passwords are more or less "random" you are out of luck, you will not be able to get a significant reduction in size.
But: Why do you need to compress the passwords? Maybe what you need is not a compression, but some sort of hash value? If you just need to check if a name matches a given password, you don't need do save the password, but can save the hash of a password. To check if a typed in password matches a given name, you can build the hash value the same way and compare it to the saved hash. As a hash (Object.hashCode()) is an int you will be able to store all 20 password-hashes in 80 bytes).
How to set delay in vbscript
A lot of the answers here assume that you're running your VBScript in the Windows Scripting Host (usually wscript.exe
or cscript.exe
). If you're getting errors like 'Variable is undefined: "WScript"' then you're probably not.
The WScript object is only available if you're running under the Windows Scripting Host, if you're running under another script host, such as Internet Explorer's (and you might be without realising it if you're in something like an HTA) it's not automatically available.
Microsoft's Hey, Scripting Guy! Blog has an article that goes into just this topic How Can I Temporarily Pause a Script in an HTA? in which they use a VBScript setTimeout
to create a timer to simulate a Sleep without needing to use CPU hogging loops, etc.
The code used is this:
<script language = "VBScript">
Dim dtmStartTime
Sub Test
dtmStartTime = Now
idTimer = window.setTimeout("PausedSection", 5000, "VBScript")
End Sub
Sub PausedSection
Msgbox dtmStartTime & vbCrLf & Now
window.clearTimeout(idTimer)
End Sub
</script>
<body>
<input id=runbutton type="button" value="Run Button" onClick="Test">
</body>
See the linked blog post for the full explanation, but essentially when the button is clicked it creates a timer that fires 5,000 milliseconds from now, and when it fires runs the VBScript sub-routine called "PausedSection" which clears the timer, and runs whatever code you want it to.
Android SDK installation doesn't find JDK
I add the following in the users Environment Variable( Windows 10)
JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11
JRE_HOME=C:/Program Files/Java/jre8
Path=%JAVA_HOME%;C:...
And then cancel the current installation of Android Studio and start again. It worked fine this time for me. No JDK error.
Move view with keyboard using Swift
its 100% Perfect Answer For all Guy's Update Tableview Height when open Keyboard
For Swift4.2
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(RecipeVC.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RecipeVC.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.tbl.contentInset
contentInset.bottom = keyboardFrame.size.height
self.tbl.contentInset = contentInset
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if ((notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
let contentInset:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.tbl.contentInset = contentInset
}
}
Swift3.2
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(RecipeVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RecipeVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
//self.view.frame.origin.y -= keyboardSize.height
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.tbl.contentInset
contentInset.bottom = keyboardFrame.size.height
self.tbl.contentInset = contentInset
}
}
func keyboardWillHide(notification: NSNotification) {
if ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
let contentInset:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.tbl.contentInset = contentInset
}
}
Reverse colormap in matplotlib
In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors
. And the module matplotlib.colors
provides a function ListedColormap()
to generate a color map from a list. So you can reverse any color map by doing
colormap_r = ListedColormap(colormap.colors[::-1])
Add CSS box shadow around the whole DIV
Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle
Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline
, but it can be fine-tuned significantly more: fiddle
You missed the last and most relevant property of box-shadow
, which is spread-distance
. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle
The full property list is:
box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?
But even better, read through the spec.
What is correct content-type for excel files?
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
how to use List<WebElement> webdriver
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
eval command in Bash and its typical uses
I've recently had to use eval
to force multiple brace expansions to be evaluated in the order I needed. Bash does multiple brace expansions from left to right, so
xargs -I_ cat _/{11..15}/{8..5}.jpg
expands to
xargs -I_ cat _/11/8.jpg _/11/7.jpg _/11/6.jpg _/11/5.jpg _/12/8.jpg _/12/7.jpg _/12/6.jpg _/12/5.jpg _/13/8.jpg _/13/7.jpg _/13/6.jpg _/13/5.jpg _/14/8.jpg _/14/7.jpg _/14/6.jpg _/14/5.jpg _/15/8.jpg _/15/7.jpg _/15/6.jpg _/15/5.jpg
but I needed the second brace expansion done first, yielding
xargs -I_ cat _/11/8.jpg _/12/8.jpg _/13/8.jpg _/14/8.jpg _/15/8.jpg _/11/7.jpg _/12/7.jpg _/13/7.jpg _/14/7.jpg _/15/7.jpg _/11/6.jpg _/12/6.jpg _/13/6.jpg _/14/6.jpg _/15/6.jpg _/11/5.jpg _/12/5.jpg _/13/5.jpg _/14/5.jpg _/15/5.jpg
The best I could come up with to do that was
xargs -I_ cat $(eval echo _/'{11..15}'/{8..5}.jpg)
This works because the single quotes protect the first set of braces from expansion during the parsing of the eval
command line, leaving them to be expanded by the subshell invoked by eval
.
There may be some cunning scheme involving nested brace expansions that allows this to happen in one step, but if there is I'm too old and stupid to see it.
Class has no objects member
UPDATE FOR VS CODE 1.40.0
After doing:
$ pip install pylint-django
Follow this link: https://code.visualstudio.com/docs/python/linting#_default-pylint-rules
Notice that the way to make pylint
have into account pylint-django
is by specifying:
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
in the settings.json
of VS Code.
But after that, you will notice a lot of new linting errors. Then, read what it said here:
These arguments are passed whenever the python.linting.pylintUseMinimalCheckers
is set to true
(the default). If you specify a value in pylintArgs
or use a Pylint configuration file (see the next section), then pylintUseMinimalCheckers
is implicitly set to false.
What I have done is creating a .pylintrc
file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):
load-plugins=pylint_django
disable=all
enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode
Now pylint
works as expected.
Find which version of package is installed with pip
As of pip 1.3, there is a pip show
command.
$ pip show Jinja2
---
Name: Jinja2
Version: 2.7.3
Location: /path/to/virtualenv/lib/python2.7/site-packages
Requires: markupsafe
In older versions, pip freeze
and grep
should do the job nicely.
$ pip freeze | grep Jinja2
Jinja2==2.7.3
Determining the version of Java SDK on the Mac
Open a terminal and type: java -version
, or javac -version
.
If you have all the latest updates for Snow Leopard, you should be running JDK 1.6.0_20 at this moment (the same as Oracle's current JDK version).
Calling a parent window function from an iframe
I recently had to find out why this didn't work too.
The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="parent.abc();" href="#">Click Me</a>
</iframe>
</body>
Hope this helps anyone that stumbles upon this issue again.
WPF chart controls
Visifire supports wide range of 2D and 3D charts with zooming and panning functionality.
Full Disclosure: I have been involved in the development of Visifire.
Call PHP function from jQuery?
Thanks all. I took bits of each of your solutions and made my own.
The final working solution is:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
success: function(data) {
$('#twitter-loader').remove();
$('#twitter-container').html(data);
}
});
});
</script>
Defining static const integer members in class definition
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr038.htm
Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).
Any idea as to what's going on?
std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.
Here's chapter/verse:
9.4.2/4 - If a static
data member is of const
integral or const
enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
See Chu's answer for a possible workaround.
Using Jquery Ajax to retrieve data from Mysql
Please make sure your $row[1] , $row[2]
contains correct value, we do assume here that 1 = Name , and 2 here is your Address field
?
Assuming you have correctly fetched your records from your Records.php, You can do something like this:
$(document).ready(function()
{
$('#getRecords').click(function()
{
var response = '';
$.ajax({ type: 'POST',
url: "Records.php",
async: false,
success : function(text){
$('#table1').html(text);
}
});
});
}
In your HTML
<table id="table1">
//Let jQuery AJAX Change This Text
</table>
<button id='getRecords'>Get Records</button>
A little note:
Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions
are no longer encouraged..
Double array initialization in Java
double m[][]
declares an array of arrays, so called multidimensional array.
m[0]
points to an array in the size of four, containing 0*0,1*0,2*0,3*0.
Simple math shows the values are actually 0,0,0,0.
Second line is also array in the size of four, containing 0,1,2,3.
And so on...
I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.
What is the difference between & and && in Java?
&& is a short circuit operator whereas & is a AND operator.
Try this.
String s = null;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
500 Internal Server Error for php file not for html
I was having this problem because I was trying to connect to MySQL but I didn't have the required package. I figured it out because of @Amadan's comment to check the error log. In my case, I was having the error: Call to undefined function mysql_connect()
If your PHP file has any code to connect with a My-SQL db then you might need to install php5-mysql
first. I was getting this error because I hadn't installed it. All my file permissions were good. In Ubuntu, you can install it by the following command:
sudo apt-get install php5-mysql
How to insert 1000 rows at a time
I create a student
table with three column id, student,age
. show you this example
declare @id int
select @id = 1
while @id >=1 and @id <= 1000
begin
insert into student values(@id, 'jack' + convert(varchar(5), @id), 12)
select @id = @id + 1
end
this is the result about the example
How to determine one year from now in Javascript
As setYear()
is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date
object - just wrap it with another new Date(...)
Ternary operator ?: vs if...else
Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.
Defining arrays in Google Scripts
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
Deprecated Java HttpClient - How hard can it be?
It got deprecated in version 4.3-alpha1
which you use because of the LATEST
version specification. If you take a look at the javadoc of the class, it tells you what to use instead: HttpClientBuilder
.
In the latest stable version (4.2.3
) the DefaultHttpClient
is not deprecated yet.
Why does DEBUG=False setting make my django Static Files Access fail?
Support for string view arguments to url() is deprecated and will be removed in Django 1.10
My solution is just small correction to Conrado solution above.
from django.conf import settings
import os
from django.views.static import serve as staticserve
if settings.DEBUG404:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', staticserve,
{'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
)
How to copy file from one location to another location?
Use the New Java File classes in Java >=7.
Create the below method and import the necessary libs.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Use the created method as below within main:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.
Credits - @Scott: Standard concise way to copy a file in Java?
How to print color in console using System.out.println?
Using color function to print text with colors
Code:
enum Color {
RED("\033[0;31m"), // RED
GREEN("\033[0;32m"), // GREEN
YELLOW("\033[0;33m"), // YELLOW
BLUE("\033[0;34m"), // BLUE
MAGENTA("\033[0;35m"), // MAGENTA
CYAN("\033[0;36m"), // CYAN
private final String code
Color(String code) {
this.code = code;
}
@Override
String toString() {
return code
}
}
def color = { color, txt ->
def RESET_COLOR = "\033[0m"
return "${color}${txt}${RESET_COLOR}"
}
Usage:
test {
println color(Color.CYAN, 'testing')
}
MySQL: Error dropping database (errno 13; errno 17; errno 39)
Quick Fix
If you just want to drop the database no matter what (but please first read the whole post: the error was given for a reason, and it might be important to know what the reason was!), you can:
- find the datadir with the command
SHOW VARIABLES WHERE Variable_name LIKE '%datadir%';
- stop the MySQL server (e.g.
service mysql stop
or rcmysqld stop
or similar on Linux, NET STOP <name of MYSQL service, often MYSQL57 or similar>
or through SERVICES.MSC
on Windows)
- go to the datadir (this is where you should investigate; see below)
- remove the directory with the same name as the database
- start MySQL server again and connect to it
- execute a DROP DATABASE
- that's it!
Reasons for Errno 13
MySQL has no write permission on the parent directory in which the mydb
folder resides.
Check it with
ls -la /path/to/data/dir/ # see below on how to discover data dir
ls -la /path/to/data/dir/mydb
On Linux, this can also happen if you mix and match MySQL and AppArmor/SELinux packages. What happens is that AppArmor expects mysqld to have its data in /path/to/data/dir
, and allows full R/W there, but MySQLd is from a different distribution or build, and it actually stores its data elsewhere (e.g.: /var/lib/mysql5/data/**
as opposed to /var/lib/mysql/**
). So what you see is that the directory has correct permissions and ownership and yet it still gives Errno 13 because apparmor/selinux won't allow access to it.
To verify, check the system log for security violations, manually inspect apparmor/selinux configuration, and/or impersonate the mysql user and try going to the base var directory, then cd incrementally until you're in the target directory, and run something like touch aardvark && rm aardvark
. If permissions and ownership match, and yet the above yields an access error, chances are that it's a security framework issue.
"EASY FIX" considered harmful
I have happened upon an "easy fix" suggested on a "experts forum"
(not Stack Overflow, thank goodness), the same "fix" I sometimes
find for Web and FTP problems -- chown 777
. PLEASE NEVER DO
THAT. For those who don't already know, 777 (or 775, or 666) isn't a
magic number that somehow MySQL programmers forgot to apply
themselves, or don't want you to know. Each digit has a
meaning, and 777 means "I hereby consent to everyone doing whatever they want with my
stuff, up to and including executing it as if it were a binary or shell
script". By doing this (and chances are you won't be allowed to do
this on a sanely configured system),
- you risk several security conscious programs to refuse to function anymore (e.g. if you do that to your SSH keys, goodbye SSH
connections; etc.) since they realize they're now in a insecure context.
- you allow literally everyone with any level of access whatsoever to the system to read and write your data, whether MySQL allows it or
not, unbeknownst to MySQL itself - i.e. it becomes possible to
silently corrupt whole databases.
- the above might sometimes be done, in exceedingly dire straits, by desperate and knowledgeable people, to gain access again to an otherwise
inaccessible screwed MySQL installation (i.e. even
mysqladmin
no longer grants
local access), and will be immediately undone as soon as
things get back to normal - it's not a permanent change, not even
then. And it's not a fix to "one weird trick to be able to drop my DB".
(needless to say, it's almost never the real fix to any Web or FTP problems either. The fix to "Of late, the wife's keys fail to open the front door and she can't enter our home" is 'check the keys or have the lock repaired or replaced'; the admittedly much quicker chown 777
is "Just leave the front door wide open! Easy peasy! What's the worst that might happen?")
Reasons for Errno 39
This code means "directory not empty". The directory contains some hidden files MySQL knows nothing about. For non-hidden files, see Errno 17. The solution is the same.
Reasons for Errno 17
This code means "file exists". The directory contains some MySQL file that MySQL doesn't feel about deleting. Such files could have been created by a SELECT ... INTO OUTFILE "filename";
command where filename
had no path. In this case, the MySQL process creates them in its current working directory, which (tested on MySQL 5.6 on OpenSuSE 12.3) is the data directory of the database, e.g. /var/lib/mysql/data/nameofdatabase
.
Reproducibility:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1676
Server version: 5.6.12-log openSUSE package
[ snip ]
mysql> CREATE DATABASE pippo;
Query OK, 1 row affected (0.00 sec)
mysql> USE pippo;
Database changed
mysql> SELECT version() INTO OUTFILE 'test';
Query OK, 1 row affected (0.00 sec)
mysql> DROP DATABASE pippo;
ERROR 1010 (HY000): Error dropping database (can't rmdir './pippo/', errno: 17)
-- now from another console I delete the "test" file, without closing this connection
-- and just retry. Now it works.
mysql> DROP DATABASE pippo;
Query OK, 0 rows affected (0.00 sec)
Move the file(s) outside (or delete if not needed) and retry. Also, determine why they were created in the first place - it could point to a bug in some application. Or worse: see below...
UPDATE: Error 17 as exploit flag
This happened on a Linux system with Wordpress installed. Unfortunately the customer was under time constraints and I could neither image the disk or do a real forensics round - I reinstalled the whole machine and Wordpress got updated in the process, so I can only say that I'm almost certain they did it through this plugin.
Symptoms: the mysql
data directory contained three files with extension PHP. Wait, what?!? -- and inside the files there was a bulk of base64 code which was passed to base64_decode
, gzuncompress
and [eval()][2]
. Aha. Of course these were only the first attempts, the unsuccessful ones. The site had been well and truly pwn3d.
So if you find a file in your mysql data dir that's causing an Error 17, check it with file
utility or scan it with an antivirus. Or visually inspect its contents. Do not assume it's there for some innocuous mistake.
(Needless to say, to visually inspect the file, never double click it).
The victim in this case (he had some friend "do the maintenance") would never have guessed he'd been hacked until a maintenance/update/whatever script ran a DROP DATABASE
(do not ask me why - I'm not sure even I want to know) and got an error. From the CPU load and the syslog messages, I'm fairly positive that the host had become a spam farm.
Yet another Error 17
If you rsync
or copy between two MySQL installations of the same version but different platform or file systems such as Linux or Windows (which is discouraged, and risky, but many do it nonetheless), and specifically with different case sensitivity settings, you can accidentally end up with two versions of the same file (either data, index, or metadata); say Customers.myi
and Customer.MYI
. MySQL uses one of them and knows nothing about the other (which could be out of date and lead to a disastrous sync). When dropping the database, which also happens in many a mysqldump ... | ... mysql
backup schemes, the DROP
will fail because that extra file (or those extra files) exists. If this happens, you should be able to recognize the obsolete file(s) that need manual deletion from the file time, or from the fact that their case scheme is different from the majority of the other tables.
Finding the data-dir
In general, you can find the data directory by inspecting the my.cnf
file (/etc/my.cnf
, /etc/sysconfig/my.cnf
, /etc/mysql/my.cnf
on Linux; my.ini
in the MySQL program files directory in Windows), under the [mysqld]
heading, as datadir
.
Alternatively you can ask it to MySQL itself:
mysql> SHOW VARIABLES WHERE Variable_name LIKE '%datadir%';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
1 row in set (0.00 sec)
Datetime format Issue: String was not recognized as a valid DateTime
This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.
So first split it by slash
var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2]
var properFormat = month + "/" +day +"/" + year;
Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.
Type datetime for input parameter in procedure
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
How can I de-install a Perl module installed via `cpan`?
As a general rule, there is not a specific 'uninstall' mechanism that comes with CPAN modules. But you might try make uninstall
in the original directory the module unpacked into (this is often under /root/.cpan
or ~/.cpan
), as some packages do contain this directive in their install script. (However, since you've installed modules into a local (non-root) library directory, you also have the option of blowing away this entire directory and reinstalling everything else that you want to keep.)
A lot of the time you can simply get away with removing the A/B.pm
file (for the A::B
module) from your perllib -- that will at least render the module unusable. Most modules also contain a list of files to be installed (called a "manifest"), so if you can find that, you'll know which files you can delete.
However, none of these approaches will address any modules that were installed as dependencies. There's no good (automated) way of knowing if something else is dependent on that module, so you'll have to uninstall it manually as well once you're sure.
The difficulty in uninstalling modules is one reason why many Perl developers are moving towards using a revision control system to keep track of installations -- e.g. see the article by brian d foy as a supplement to his upcoming book that discusses using git for package management.
Copy file or directories recursively in Python
Unix cp
doesn't 'support both directories and files':
betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).
To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.
There is some disconnect here though - cp -r
when passed a filename as the source will happily copy just the single file; copytree won't.
Fatal error: Call to a member function fetch_assoc() on a non-object
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result)
to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
Automated testing for REST Api
At my work we have recently put together a couple of test suites written in Java to test some RESTful APIs we built. Our Services could invoke other RESTful APIs they depend on. We split it into two suites.
- Suite 1 - Testing each service in isolation
- Mock any peer services the API depends on using restito. Other alternatives include rest-driver, wiremock and betamax.
- Tests the service we are testing and the mocks all run in a single JVM
- Launches the service in Jetty
I would definitely recommend doing this. It has worked really well for us. The main advantages are:
- Peer services are mocked, so you needn't perform any complicated data setup. Before each test you simply use restito to define how you want peer services to behave, just like you would with classes in unit tests with Mockito.
- You can ask the mocked peer services if they were called. You can't do these asserts as easily with real peer services.
- The suite is super fast as mocked services serve pre-canned in-memory responses. So we can get good coverage without the suite taking an age to run.
- The suite is reliable and repeatable as its isolated in it's own JVM, so no need to worry about other suites/people mucking about with an shared environment at the same time the suite is running and causing tests to fail.
- Suite 2 - Full End to End
- Suite runs against a full environment deployed across several machines
- API deployed on Tomcat in environment
- Peer services are real 'as live' full deployments
This suite requires us to do data set up in peer services which means tests generally take more time to write. As much as possible we use REST clients to do data set up in peer services.
Tests in this suite usually take longer to write, so we put most of our coverage in Suite 1. That being said there is still clear value in this suite as our mocks in Suite 1 may not be behaving quite like the real services.
Fatal error: Class 'SoapClient' not found
To install SOAP in PHP-7 run following in your Ubuntu terminal:
sudo apt-get install php7.0-soap
To install SOAP in PHP-7.1 run following in your Ubuntu terminal:
sudo apt-get install php7.1-soap
To install SOAP in PHP-7.2 run following in your Ubuntu terminal:
sudo apt-get install php7.2-soap
To install SOAP in PHP-7.3 run following in your Ubuntu terminal:
sudo apt-get install php7.3-soap
How to redirect single url in nginx?
If you need to duplicate more than a few redirects, you might consider using a map:
# map is outside of server block
map $uri $redirect_uri {
~^/issue1/?$ http://example.com/shop/issues/custom_isse_name1;
~^/issue2/?$ http://example.com/shop/issues/custom_isse_name2;
~^/issue3/?$ http://example.com/shop/issues/custom_isse_name3;
# ... or put these in an included file
}
location / {
try_files $uri $uri/ @redirect-map;
}
location @redirect-map {
if ($redirect_uri) { # redirect if the variable is defined
return 301 $redirect_uri;
}
}
Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded
As "there are tens of thousands of cells in the page" binding the click-event to every single cell will cause a terrible performance problem. There's a better way to do this, that is binding a click event to the body & then finding out if the cell element was the target of the click. Like this:
$('body').click(function(e){
var Elem = e.target;
if (Elem.nodeName=='td'){
//.... your business goes here....
// remember to replace $(this) with $(Elem)
}
})
This method will not only do your task with native "td" tag but also with later appended "td". I think you'll be interested in this article about event binding & delegate
Or you can simply use the ".on()" method of jQuery with the same effect:
$('body').on('click', 'td', function(){
...
});
How can I put the current running linux process in background?
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.
bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
Custom method names in ASP.NET Web API
In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute()
call to edit at will.
The ConfigureServices()
method invoked by the Startup.cs
file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc()
later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc()
method implementation within the framework source code:
public static IApplicationBuilder UseMvc(
[NotNull] this IApplicationBuilder app,
[NotNull] Action<IRouteBuilder> configureRoutes)
{
// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
var routes = new RouteBuilder
{
DefaultHandler = new MvcRouteHandler(),
ServiceProvider = app.ApplicationServices
};
configureRoutes(routes);
// Adding the attribute route comes after running the user-code because
// we want to respect any changes to the DefaultHandler.
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
routes.DefaultHandler,
app.ApplicationServices));
return app.UseRouter(routes.Build());
}
The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.
The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).
Convention-Based
In your Startup.cs class, replace this:
app.UseMvc();
with this:
app.UseMvc(routes =>
{
// Route Sample A
routes.MapRoute(
name: "RouteSampleA",
template: "MyOwnGet",
defaults: new { controller = "Items", action = "Get" }
);
// Route Sample B
routes.MapRoute(
name: "RouteSampleB",
template: "MyOwnPost",
defaults: new { controller = "Items", action = "Post" }
);
});
Attribute-Based
A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller
class and/or the Action
methods with the appropriate RouteAttribute
and/or HttpGet
/ HttpPost
template parameters, such as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace MyNamespace.Controllers
{
[Route("api/[controller]")]
public class ItemsController : Controller
{
// GET: api/items
[HttpGet()]
public IEnumerable<string> Get()
{
return GetLatestItems();
}
// GET: api/items/5
[HttpGet("{num}")]
public IEnumerable<string> Get(int num)
{
return GetLatestItems(5);
}
// GET: api/items/GetLatestItems
[HttpGet("GetLatestItems")]
public IEnumerable<string> GetLatestItems()
{
return GetLatestItems(5);
}
// GET api/items/GetLatestItems/5
[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
return new string[] { "test", "test2" };
}
// POST: /api/items/PostSomething
[HttpPost("PostSomething")]
public IActionResult Post([FromBody]string someData)
{
return Content("OK, got it!");
}
}
}
This controller will handle the following requests:
[GET] api/items
[GET] api/items/5
[GET] api/items/GetLatestItems
[GET] api/items/GetLatestItems/5
[POST] api/items/PostSomething
Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc()
.
For more info, you can also read the following post on my blog.
Calling a function every 60 seconds
here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
find vs find_by vs where
The answers given so far are all OK.
However, one interesting difference is that Model.find
searches by id; if found, it returns a Model
object (just a single record) but throws an ActiveRecord::RecordNotFound
otherwise.
Model.find_by
is very similar to Model.find
and lets you search any column or group of columns in your database but it returns nil
if no record matches the search.
Model.where
on the other hand returns a Model::ActiveRecord_Relation
object which is just like an array containing all the records that match the search. If no record was found, it returns an empty Model::ActiveRecord_Relation
object.
I hope these would help you in deciding which to use at any point in time.
ERROR: Error 1005: Can't create table (errno: 121)
I searched quickly for you, and it brought me here. I quote:
You will get this message if you're trying to add a constraint with a
name that's already used somewhere else
To check constraints use the following SQL query:
SELECT
constraint_name,
table_name
FROM
information_schema.table_constraints
WHERE
constraint_type = 'FOREIGN KEY'
AND table_schema = DATABASE()
ORDER BY
constraint_name;
Look for more information there, or try to see where the error occurs. Looks like a problem with a foreign key to me.
How To Set Text In An EditText
You can set android:text="your text"
;
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/intro_name"/>
ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have
the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
Android WebView not loading an HTTPS URL
To solve Google security, do this:
Lines to the top:
import android.webkit.SslErrorHandler;
import android.net.http.SslError;
Code:
class SSLTolerentWebViewClient extends WebViewClient {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (error.toString() == "piglet")
handler.cancel();
else
handler.proceed(); // Ignore SSL certificate errors
}
}
CSS strikethrough different color from text?
If you do not care about internet explorer\edge, then simplest way to achieve different color for strike-through would be to use CSS property:
text-decoration-color in conjunction with text-decoration:line-through;
.yourClass {
text-decoration: line-through !important;
text-decoration-color: red !important;
}
-- Does not work with Edge\Internet Explorer
Mixed mode assembly is built against version ‘v2.0.50727' of the runtime
Please add attribute useLegacyV2RuntimeActivationPolicy="true" in your applications app.config file.
Old Value
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
New Value
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
It will solve your problem.
Array of char* should end at '\0' or "\0"?
I would end it with NULL
. Why? Because you can't do either of these:
array[index] == '\0'
array[index] == "\0"
The first one is comparing a char *
to a char
, which is not what you want. You would have to do this:
array[index][0] == '\0'
The second one doesn't even work. You're comparing a char *
to a char *
, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use ==
to compare two strings, you have to use the strcmp()
function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:
array[index] == NULL
Works just fine and conveys your point.
How to make responsive table
Basically
A responsive table is simply a 100% width table.
You can just set up your table with this CSS:
.table { width: 100%; }
Demo here
You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child
, etc):
@media screen and (max-width: 320px) {
.hide { display: none; }
}
HTML
<td class="hide">Not important</td>
More advanced solutions
If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:
List of IP Space used by Facebook
The list from 2020-05-23 is:
31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22
The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:
whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
Java - Check Not Null/Empty else assign default value
This is the best solution IMHO. It covers BOTH null
and empty
scenario, as is easy to understand when reading the code. All you need to know is that .getProperty
returns a null
when system prop is not set:
String DEFAULT_XYZ = System.getProperty("user.home") + "/xyz";
String PROP = Optional.ofNullable(System.getProperty("XYZ"))
.filter(s -> !s.isEmpty())
.orElse(DEFAULT_XYZ);
What does 'super' do in Python?
Many great answers, but for visual learners:
Firstly lets explore with arguments to super, and then without.
Imagine theres an instance jack
created from the class Jack
, who has the inheritance chain as shown in green in the picture. Calling:
super(Jack, jack).method(...)
will use the MRO (Method Resolution Order) of jack
(its inheritance tree in a certain order), and will start searching from Jack
. Why can one provide a parent class? Well if we start searching from the instance jack
, it would find the instance method, the whole point is to find its parents method.
If one does not supply arguments to super, its like the first argument passed in is the class of self
, and the second argument passed in is self
. These are auto-calculated for you in Python3.
However say we dont want to use Jack
's method, instead of passing in Jack
, we could of passed in Jen
to start searching upwards for the method from Jen
.
It searches one layer at a time (width not depth), e.g. if Adam
and Sue
both have the required method, the one from Sue
will be found first.
If Cain
and Sue
both had the required method, Cain
's method would be called first.
This corresponds in code to:
Class Jen(Cain, Sue):
MRO is from left to right.
How to input a regex in string.replace?
The easiest way
import re
txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. and there are many other lines in the txt files with<[3> such tags </[3>'
out = re.sub("(<[^>]+>)", '', txt)
print out
How to fix "unable to write 'random state' " in openssl
The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:
set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024
More explanations:
OpenSSL on Windows tries to save the 'random state' file in the following order:
- Path taken from RANDFILE environment variable
- If HOME environment variable is set then : ${HOME}\.rnd
- C:\.rnd
I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.
iPhone UIView Animation Best Practice
From the UIView reference's section about the beginAnimations:context:
method:
Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.
Eg of Block-based Animation based on Tom's Comment
[UIView transitionWithView:mysuperview
duration:0.75
options:UIViewAnimationTransitionFlipFromRight
animations:^{
[myview removeFromSuperview];
}
completion:nil];
How to show Snackbar when Activity starts?
Just point to any View
inside the Activity's
XML. You can give an id to the root viewGroup, for example, and use:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "This is main activity", Snackbar.LENGTH_LONG)
.setAction("CLOSE", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
})
.setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
.show();
//Other stuff in OnCreate();
}
Check if string contains a value in array
This was a lot easier to do if all you want to do is find a string in an array.
$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}
How do I force files to open in the browser instead of downloading (PDF)?
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
Setting PHPMyAdmin Language
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
Is there a way to iterate over a range of integers?
While I commiserate with your concern about lacking this language feature, you're probably just going to want to use a normal for
loop. And you'll probably be more okay with that than you think as you write more Go code.
I wrote this iter package — which is backed by a simple, idiomatic for
loop that returns values over a chan int
— in an attempt to improve on the design found in https://github.com/bradfitz/iter, which has been pointed out to have caching and performance issues, as well as a clever, but strange and unintuitive implementation. My own version operates the same way:
package main
import (
"fmt"
"github.com/drgrib/iter"
)
func main() {
for i := range iter.N(10) {
fmt.Println(i)
}
}
However, benchmarking revealed that the use of a channel was a very expensive option. The comparison of the 3 methods, which can be run from iter_test.go
in my package using
go test -bench=. -run=.
quantifies just how poor its performance is
BenchmarkForMany-4 5000 329956 ns/op 0 B/op 0 allocs/op
BenchmarkDrgribIterMany-4 5 229904527 ns/op 195 B/op 1 allocs/op
BenchmarkBradfitzIterMany-4 5000 337952 ns/op 0 B/op 0 allocs/op
BenchmarkFor10-4 500000000 3.27 ns/op 0 B/op 0 allocs/op
BenchmarkDrgribIter10-4 500000 2907 ns/op 96 B/op 1 allocs/op
BenchmarkBradfitzIter10-4 100000000 12.1 ns/op 0 B/op 0 allocs/op
In the process, this benchmark also shows how the bradfitz
solution underperforms in comparison to the built-in for
clause for a loop size of 10
.
In short, there appears to be no way discovered so far to duplicate the performance of the built-in for
clause while providing a simple syntax for [0,n)
like the one found in Python and Ruby.
Which is a shame because it would probably be easy for the Go team to add a simple rule to the compiler to change a line like
for i := range 10 {
fmt.Println(i)
}
to the same machine code as for i := 0; i < 10; i++
.
However, to be fair, after writing my own iter.N
(but before benchmarking it), I went back through a recently written program to see all the places I could use it. There actually weren't many. There was only one spot, in a non-vital section of my code, where I could get by without the more complete, default for
clause.
So while it may look like this is a huge disappointment for the language in principle, you may find — like I did — that you actually don't really need it in practice. Like Rob Pike is known to say for generics, you might not actually miss this feature as much as you think you will.
Setting the number of map tasks and reduce tasks
The number of map tasks for a given job is driven by the number of input splits and not by the mapred.map.tasks parameter. For each input split a map task is spawned. So, over the lifetime of a mapreduce job the number of map tasks is equal to the number of input splits. mapred.map.tasks is just a hint to the InputFormat for the number of maps.
In your example Hadoop has determined there are 24 input splits and will spawn 24 map tasks in total. But, you can control how many map tasks can be executed in parallel by each of the task tracker.
Also, removing a space after -D might solve the problem for reduce.
For more information on the number of map and reduce tasks, please look at the below url
https://cwiki.apache.org/confluence/display/HADOOP2/HowManyMapsAndReduces
How to use OKHTTP to make a post request?
OkHttp POST
request with token in header
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("search", "a")
.addFormDataPart("model", "1")
.addFormDataPart("in", "1")
.addFormDataPart("id", "1")
.build();
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("https://somedomain.com/api")
.post(requestBody)
.addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("response", myResponse);
progress.hide();
}
});
}
}
});
How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.
Try this:
location / {
root /path/to/root;
expires 30d;
access_log off;
}
location ~* ^.*\.php$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php
should be forwared to Apache if only a corresponding .php
file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.
Google maps Places API V3 autocomplete - select first option on enter
/// <reference types="@types/googlemaps" />
import {ChangeDetectorRef, Component, ElementRef, EventEmitter, Inject, Input, NgZone, OnInit, Output, ViewChild} from '@angular/core';
import {MapsAPILoader, MouseEvent} from '@agm/core';
import { Address } from 'src/@core/interfaces/address.model';
import { NotificationService } from 'src/@core/services/notification.service';
// import {} from 'googlemaps';
declare var google: any;
// @ts-ignore
@Component({
selector: 'app-search-address',
templateUrl: './search-address.component.html',
styleUrls: ['./search-address.component.scss']
})
export class SearchAddressComponent implements OnInit {
@Input('label') label: string;
@Input('addressObj') addressObj: Address = {};
zoom: number;
isSnazzyInfoWindowOpened = false;
private geoCoder;
// @ts-ignore
@Output() onAddressSelected = new EventEmitter<any>();
@Input('defaultAddress') defaultAddress = '';
@ViewChild('search', {static: true})
public searchElementRef: ElementRef = null;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
private notify: NotificationService,
@Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef
) { }
ngOnInit() {
// console.log('addressObj# ', this.addressObj);
if (this.defaultAddress !== '') {
this.searchElementRef.nativeElement.value = this.defaultAddress;
}
// load Places Autocomplete
this.mapsAPILoader.load().then(() => {
if (this.addressObj.address) {
this.setZoom();
} else {
this.setCurrentLocation();
}
this.geoCoder = new google.maps.Geocoder;
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ['address']
});
autocomplete.setTypes(['(cities)']);
autocomplete.setComponentRestrictions({'country': 'in'});
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
// get the place result
const place: google.maps.places.PlaceResult = autocomplete.getPlace();
// verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// set latitude, longitude and zoom
this.addressObj.latitude = place.geometry.location.lat();
this.addressObj.longitude = place.geometry.location.lng();
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
this.zoom = 12;
});
});
});
}
setZoom() {
this.zoom = 8;
}
// Get Current Location Coordinates
private setCurrentLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.addressObj.latitude = position.coords.latitude;
this.addressObj.longitude = position.coords.longitude;
this.zoom = 8;
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
});
}
}
markerDragEnd($event: MouseEvent) {
this.addressObj.latitude = $event.coords.lat;
this.addressObj.longitude = $event.coords.lng;
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
}
getAddress(latitude, longitude) {
this.addressObj.latitude = latitude;
this.addressObj.longitude = longitude;
this.geoCoder.geocode({ location: { lat: latitude, lng: longitude } }, (results, status) => {
if (status === 'OK') {
if (results[0]) {
console.log('results ', results);
this.zoom = 12;
this.addressObj.address = results[0].formatted_address;
this.showSnazzyInfoWindow();
this.addressObj.placeId = results[0].place_id;
for(let i = 0; i < results[0].address_components.length; i++) {
if (results[0].address_components[i].types[0] == 'locality') {
this.addressObj.city = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'administrative_area_level_1') {
this.addressObj.region = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'country') {
this.addressObj.country = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'postal_code') {
this.addressObj.zip = results[0].address_components[i].long_name;
}
}
this.transmitData();
} else {
this.notify.showMessage('No results found', 3000, 'OK');
}
} else {
this.notify.showMessage('Google maps location failed due to: ' + status, 3000, 'OK');
}
});
}
transmitData() {
// console.log(this.addressObj);
this.onAddressSelected.emit(this.addressObj);
}
toggleSnazzyInfoWindow() {
this.isSnazzyInfoWindowOpened = !this.isSnazzyInfoWindowOpened;
}
showSnazzyInfoWindow() {
this.isSnazzyInfoWindowOpened = true;
}
}
<mat-form-field class="full-width pt-2 flex-auto w-full">
<input matInput [(ngModel)]="addressObj.address" type="text" (keydown.enter)="$event.preventDefault()" placeholder="{{label ? label : 'Location'}}" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>
</mat-form-field>
<agm-map
[latitude]="addressObj.latitude"
[longitude]="addressObj.longitude"
[zoom]="zoom">
<agm-marker
[latitude]="addressObj.latitude"
[longitude]="addressObj.longitude"
[markerDraggable]="true"
(dragEnd)="markerDragEnd($event)">
</agm-marker>
</agm-map>
Android Calling JavaScript functions in WebView
Here is an example to load js script from the asset on WebView
.
Put script to a file will help reading easier
I load the script in onPageFinished
because I need to access some DOM element inside the script (to able to access it should be loaded or it will be null). Depend on the purpose of the script, we may load it earlier
assets/myjsfile.js
document.getElementById("abc").innerText = "def"
document.getElementById("abc").onclick = function() {
document.getElementById("abc").innerText = "abc"
}
WebViewActivity
webView.settings.javaScriptEnabled = true
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
val script = readTextFromAsset("myjsfile.js")
view.loadUrl("javascript: $script")
}
}
fun readTextFromAsset(context: Context, fileName: String): String {
return context.assets.open(fileName).bufferedReader().use { it.readText()
}
Javascript - Open a given URL in a new tab by clicking a button
USE this code
function openBackWindow(url,popName){
var popupWindow = window.open(url,popName,'scrollbars=1,height=650,width=1050');
if($.browser.msie){
popupWindow.blur();
window.focus();
}else{
blurPopunder();
}
};
function blurPopunder() {
var winBlankPopup = window.open("about:blank");
if (winBlankPopup) {
winBlankPopup.focus();
winBlankPopup.close()
}
};
IT works fine in Mozilla,IE and chrome on and less than 22 version; but doesn't work in Opera and Safari.
How do I get the value of a textbox using jQuery?
Possible Duplicate:
Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:
For radio button:
var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();
For textbox:
var txt=$('input:text[name=DrugDurationLength]').val();
Set type for function parameters?
Explanation
I'm not sure if my answer is direct answer to original question, but as I suppose a lot of people come here to just find a way to tell their IDEs to understand types, I'll share what I found.
If you want to tell VSCode to understand your types, do as follows. Please pay attention that js
runtime and NodeJS
does not care about these types at all.
Solution
1- Create a file with .d.ts
ending: e.g: index.d.ts
. You can create this file in another folder. for example: types/index.d.ts
2- Suppose we want to have a function called view
. Add these lines to index.d.ts
:
/**
* Use express res.render function to render view file inside layout file.
*
* @param {string} view The path of the view file, relative to view root dir.
* @param {object} options The options to send to view file for ejs to use when rendering.
* @returns {Express.Response.render} .
*/
view(view: string, options?: object): Express.Response.render;
3- Create a jsconfig.json
file in you project's root. (It seems that just creating this file is enough for VSCode to search for your types).
A bit more
Now suppose we want to add this type to another library types. (As my own situation). We can use some ts
keywords. And as long as VSCode understands ts
we have no problem with it.
For example if you want to add this view
function to response from expressjs, change index.d.ts
file as follows:
export declare global {
namespace Express {
interface Response {
/**
* Use express res.render function to render view file inside layout file.
*
* @param {string} view The path of the view file, relative to view root dir.
* @param {object} options The options to send to view file for ejs to use when rendering.
* @returns {Express.Response.render} .
*/
view(view: string, options?: object): Express.Response.render;
}
}
}
Result
jquery - Click event not working for dynamically created button
the simple and easy way to do that is use on event:
$('body').on('click','#element',function(){
//somthing
});
but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html.
Write some html in you file for example:
<div id='div1'></div>
Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:
var dynamicDiv = jQuery('#div1').clone(true);
Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element
Bootstrap 4 align navbar items to the right
In my case, I wanted just one set of navigation buttons / options and found that this will work:
<div class="collapse navbar-collapse justify-content-end" id="navbarCollapse">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Sign Out</a>
</li>
</ul>
</div>
So, you will add justify-content-end
to the div and omit mr-auto
on the list.
Here is a working example.
How to make pylab.savefig() save image for 'maximized' window instead of default size
I did the same search time ago, it seems that he exact solution depends on the backend.
I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python
I adjusted the code and ended up with the function below.
It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.
Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.
def maximize(backend=None,fullscreen=False):
"""Maximize window independently on backend.
Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
if backend is None:
backend=matplotlib.get_backend()
mng = plt.get_current_fig_manager()
if fullscreen:
mng.full_screen_toggle()
else:
if backend == 'wxAgg':
mng.frame.Maximize(True)
elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
mng.window.showMaximized()
elif backend == 'TkAgg':
mng.window.state('zoomed') #works fine on Windows!
else:
print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
plt.show()
plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)
Xcode stops working after set "xcode-select -switch"
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
Uninstalling Android ADT
i got the same problem after clicking update plugins,
i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..
How do you clear the SQL Server transaction log?
It happened with me where the database log file was of 28 GBs.
What can you do to reduce this?
Actually, log files are those file data which the SQL server keeps when an transaction has taken place. For a transaction to process SQL server allocates pages for the same. But after the completion of the transaction, these are not released suddenly hoping that there may be a transaction coming like the same one. This holds up the space.
Step 1:
First Run this command in the database query explored
checkpoint
Step 2:
Right click on the database
Task> Back up
Select back up type as Transaction Log
Add a destination address and file name to keep the backup data (.bak)
Repeat this step again and at this time give another file name
Step 3:
Now go to the database
Right-click on the database
Tasks> Shrinks> Files
Choose File type as Log
Shrink action as release unused space
Step 4:
Check your log file
normally in SQL 2014 this can be found at
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL2014EXPRESS\MSSQL\DATA
In my case, its reduced from 28 GB to 1 MB
How to get file_get_contents() to work with HTTPS?
HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen
in php.ini is set to true.
Bootstrap 3 Gutter Size
I tried several of the options here. For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.
Here is what worked for me.
.col-sm-12 {
margin-bottom: 2em;
}
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="col-sm-12">
</div>
</div>
<div class="col-sm-6">
<div class="col-sm-12">
</div>
</div>
</div>
</div>
Referencing value in a closed Excel workbook using INDIRECT?
If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.
Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String
Set WS = GetObject(address).Worksheets
GETSHEETNAME = WS(SheetNumber).Name
End Function
This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).
Cut Corners using CSS
You can use clip-path
, as Stewartside and Sviatoslav Oleksiv mentioned. To make things easy, I created a sass mixin:
@mixin cut-corners ($left-top, $right-top: 0px, $right-bottom: 0px, $left-bottom: 0px) {
clip-path: polygon($left-top 0%, calc(100% - #{$right-top}) 0%, 100% $right-top, 100% calc(100% - #{$right-bottom}), calc(100% - #{$right-bottom}) 100%, $left-bottom 100%, 0% calc(100% - #{$left-bottom}), 0% $left-top);
}
.cut-corners {
@include cut-corners(10px, 0, 25px, 50px);
}
How to connect to a secure website using SSL in Java with a pkcs12 file?
I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct.
What you are actually describing is how you insert server certificates into the systems default truststore:
$JAVA_HOME/jre/lib/security/cacerts, password: changeit)
This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.
You actually never use your own truststore that you defined here:
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
Load view from an external xib file in storyboard
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Code
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
- Create a custom UIView class in a .swift file to control your xib. i.e.
MyCustomClass.swift
- Create a .xib file and style it as you want. i.e.
MyCustomClass.xib
- Set the
File's Owner
of the .xib file to be your custom class (MyCustomClass
)
- GOTCHA: leave the
class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
- Hook up your outlets as you normally would using the
Assistant Editor
.
- NOTE: If you look at the
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery.
- Make sure your custom class has @IBDesignable before the class statement.
- Make your custom class conform to the
NibLoadable
protocol referenced below.
- NOTE: If your custom class
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.
- Implement
required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.
- Add a UIView to your desired storyboard and set the class to be your custom class name (i.e.
MyCustomClass
).
- Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.
Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self)
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
How to use WinForms progress bar?
Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 100000; j++)
{
Calculate(j);
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
// TODO: Do something after all calculations
}
Tasks are currently the preferred way to implement what BackgroundWorker
does.
Tasks and Progress
are explained in more detail here:
How to properly compare two Integers in Java?
this method compares two Integer with null check, see tests
public static boolean compare(Integer int1, Integer int2) {
if(int1!=null) {
return int1.equals(int2);
} else {
return int2==null;
}
//inline version:
//return (int1!=null) ? int1.equals(int2) : int2==null;
}
//results:
System.out.println(compare(1,1)); //true
System.out.println(compare(0,1)); //false
System.out.println(compare(1,0)); //false
System.out.println(compare(null,0)); //false
System.out.println(compare(0,null)); //false
System.out.println(compare(null,null)); //true
Changing Underline color
here we can create underline with color in text
_x000D_
_x000D_
<u style="text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_
or
The color of the lines should now be red!
_x000D_
_x000D_
<h1 style=" text-decoration:underline; text-decoration-color: red;">The color of the lines should now be red!</u>
_x000D_
_x000D_
_x000D_
Checking if a field contains a string
How to ignore HTML tags in a RegExp match:
var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';
var rx = '';
searchString.split(' ').forEach(e => {
rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});
rx = new RegExp(rx, 'igm');
console.log(text.match(rx));
This is probably very easy to turn into a MongoDB aggregation filter.
Insert a string at a specific index
Here is a method I wrote that behaves like all other programming languages:
_x000D_
_x000D_
String.prototype.insert = function(index, string) {
if (index > 0) {
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
_x000D_
_x000D_
_x000D_
Reference:
How to access environment variable values?
As for the environment variables:
import os
print os.environ["HOME"]
I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.
Is there a TRY CATCH command in Bash
As everybody says, bash doesn't have a proper language-supported try/catch syntax. You can launch bash with the -e
argument or use set -e
inside the script to abort the entire bash process if any command has a non-zero exit code. (You can also set +e
to temporarily allow failing commands.)
So, one technique to simulate a try/catch block is to launch a sub-process to do the work with -e
enabled. Then in the main process, check the return code of the sub-process.
Bash supports heredoc strings, so you don't have to write two separate files to handle this. In the below example, the TRY heredoc will run in a separate bash instance, with -e
enabled, so the sub-process will crash if any command returns a non-zero exit code. Then, back in the main process, we can check the return code to handle a catch block.
#!/bin/bash
set +e
bash -e <<TRY
echo hello
cd /does/not/exist
echo world
TRY
if [ $? -ne 0 ]; then
echo caught exception
fi
It's not a proper language-supported try/catch block, but it may scratch a similar itch for you.
How to fix committing to the wrong Git branch?
For multiple commits on the wrong branch
If, for you, it is just about 1 commit, then there are plenty of other easier resetting solutions available. For me, I had about 10 commits that I'd accidentally created on master
branch instead of, let's call it target
, and I did not want to lose the commit history.
What you could do, and what saved me was using this answer as a reference, using a 4 step process, which is -
- Create a new temporary branch
temp
from master
- Merge
temp
into the branch originally intended for commits, i.e. target
- Undo commits on
master
- Delete the temporary branch
temp
.
Here are the above steps in details -
Create a new branch from the master
(where I had accidentally committed a lot of changes)
git checkout -b temp
Note: -b
flag is used to create a new branch
Just to verify if we got this right, I'd do a quick git branch
to make sure we are on the temp
branch and a git log
to check if we got the commits right.
Merge the temporary branch into the branch originally intended for the commits, i.e. target
.
First, switch to the original branch i.e. target
(You might need to git fetch
if you haven't)
git checkout target
Note: Not using -b
flag
Now, let's merge the temporary branch into the branch we have currently checkout out target
git merge temp
You might have to take care of some conflicts here, if there are. You can push (I would) or move on to the next steps, after successfully merging.
Undo the accidental commits on master
using this answer as reference, first switch to the master
git checkout master
then undo it all the way back to match the remote using the command below (or to particular commit, using appropriate command, if you want)
git reset --hard origin/master
Again, I'd do a git log
before and after just to make sure that the intended changes took effect.
Erasing the evidence, that is deleting the temporary branch. For this, first you need to checkout the branch that the temp
was merged into, i.e. target
(If you stay on master
and execute the command below, you might get a error: The branch 'temp' is not fully merged
), so let's
git checkout target
and then delete the proof of this mishap
git branch -d temp
There you go.
NameError: uninitialized constant (rails)
Similar with @Michael-Neal.
I had named the controller as singular. app/controllers/product_controller.rb
When I renamed it as plural, error solved. app/controllers/products_controller.rb
Execution failed for task :':app:mergeDebugResources'. Android Studio
By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size for Android Studio processes, such as the core IDE, Gradle daemon, and Kotlin daemon.
If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust the heap sizes for your project manually. To do so, follow these steps:
Click File > Settings from the menu bar (or Android Studio > Preferences on macOS). Click Appearance & Behavior > System Settings > Memory Settings.
For more Info click
https://developer.android.com/studio/intro/studio-config
How to save an image to localStorage and display it on the next page?
document.getElementById('file').addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
// convert file to base64 String
const base64String = reader.result.replace('data:', '').replace(/^.+,/, '');
// store file
localStorage.setItem('wallpaper', base64String);
// display image
document.body.style.background = `url(data:image/png;base64,${base64String})`;
};
reader.readAsDataURL(file);
});
Example CodePen
SQL Plus change current directory
I think that the SQLPATH environment variable is the best way for this - if you have multiple paths, enter them separated by semi-colons (;). Keep in mind that if there are script files named the same in among the directories, the first one encountered (by order the paths are entered) will be executed, the second one will be ignored.
How to remove the underline for anchors(links)?
Best Option for you if you just want to remove the underline from anchor link only-
#content a {
text-decoration-line:none;
}
This will remove the underline.
Further, you can use a similar syntax for manipulating other styles too using-
text-decoration: none;
text-decoration-color: blue;
text-decoration-skip: spaces;
text-decoration-style: dotted;
Hope this helps!
P.S.- This is my first answer ever!
See what's in a stash without applying it
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list,
inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
Simulate limited bandwidth from within Chrome?
I'd recommend Charles Proxy - you can choose to slowdown individual sites, also has a whole bunch of HTTP inspection tools.
Edit:
As of June 2014, Chrome now has the ability to do this natively in DevTools - you'll need Chrome 38 though.
The option is accessible from the Network tab via a drop down at the end of the toolbar.
Inserting a blank table row with a smaller height
I know this question already has an answer, but I found out an even simpler way of doing this.
Just add
<tr height = 20px></tr>
Into the table where you want to have an empty row. It works fine in my program and it's probably the quickest solution possible.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
correct way to define class variables in Python
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
- Elements outside the
__init__
method are static elements; they belong to the class.
- Elements inside the
__init__
method are elements of the object (self
); they don't belong to the class.
You'll see it more clearly with some code:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.
How do you declare string constants in C?
One advantage (albeit very slight) of defining string constants is that you can concatenate them at compile time:
#define HELLO "hello"
#define WORLD "world"
puts( HELLO WORLD );
Not sure that's really an advantage, but it is a technique that cannot be used with const char *
's.
Using HTML5 file uploads with AJAX and jQuery
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
Get remote registry value
Try the Remote Registry Module, the registry provider cannot operate remotely:
Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion
How to use log levels in java
Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):
ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message");
)
WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message");
)
INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message");
)
DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message");
)
The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).
Collections.sort with multiple fields
If you want to sort based on ReportKey first then Student Number then School, you need to compare each String instead of concatenating them. Your method might work if you pad the strings with spaces so that each ReportKey is the same length and so on, but it is not really worth the effort. Instead just change the compare method to compare the ReportKeys, if compareTo returns 0 then try StudentNumber, then School.
How to instantiate, initialize and populate an array in TypeScript?
There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.
Option 1:
class bar {
// Makes a public field called 'length'
constructor(public length: number) { }
}
bars = [ new bar(1) ];
Option 2:
interface bar {
length: number;
}
bars = [ {length: 1} ];
How to drop column with constraint?
The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.
ALTER TABLE MyTable
DROP CONSTRAINT FK_MyColumn
CONSTRAINT DK_MyColumn
-- etc...
COLUMN MyColumn
GO
add scroll bar to table body
you can wrap the content of the <tbody>
in a scrollable <div>
:
html
....
<tbody>
<tr>
<td colspan="2">
<div class="scrollit">
<table>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
...
css
.scrollit {
overflow:scroll;
height:100px;
}
see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/
Error: getaddrinfo ENOTFOUND in nodejs for get call
getaddrinfo ENOTFOUND means client was not able to connect to given address.
Please try specifying host without http:
var optionsget = {
host : 'localhost',
port : 3010,
path : '/quote/random', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
Regarding learning resources, you won't go wrong if you start with http://www.nodebeginner.org/ and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js , but there's many out there.
Searching word in vim?
If you are working in Ubuntu,follow the steps:
- Press
/
and type word to search
- To search in forward press 'SHIFT' key with
*
key
- To search in backward press 'SHIFT' key with
#
key
Convert a float64 to an int in Go
Correct rounding is likely desired.
Therefore math.Round() is your quick(!) friend.
Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = 5.51
var y float64 = 5.50
var z float64 = 5.49
fmt.Println(int(math.Round(x))) // outputs "6"
fmt.Println(int(math.Round(y))) // outputs "6"
fmt.Println(int(math.Round(z))) // outputs "5"
}
math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.
Using SELECT result in another SELECT
You are missing table NewScores
, so it can't be found. Just join this table.
If you really want to avoid joining it directly you can replace NewScores.NetScore
with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}
MySQl Error #1064
Sometimes when your table has a similar name to the database name you should use back tick. so instead of:
INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');
You should have this:
INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');
SQL Query for Logins
EXEC sp_helplogins
You can also pass an "@LoginNamePattern" parameter to get information about a specific login:
EXEC sp_helplogins @LoginNamePattern='fred'
PHP convert XML to JSON
Looks like the $state->name
variable is holding an array. You can use
var_dump($state)
inside the foreach
to test that.
If that's the case, you can change the line inside the foreach
to
$states[]= array('state' => array_shift($state->name));
to correct it.
How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?
As others have pointed out, the only way to change the browser's behavior is to make sure the response either does not contain a 401 status code or if it does, not include the WWW-Authenticate: Basic
header. Since changing the status code is not very semantic and undesirable, a good approach is to remove the WWW-Authenticate
header. If you can't or don't want to modify your web server application, you can always serve or proxy it through Apache (if you are not using Apache already).
Here is a configuration for Apache to rewrite the response to remove the WWW-Authenticate header IFF the request contains contains the header X-Requested-With: XMLHttpRequest
(which is set by default by major Javascript frameworks such as JQuery/AngularJS, etc...) AND the response contains the header WWW-Authenticate: Basic
.
Tested on Apache 2.4 (not sure if it works with 2.2).
This relies on the mod_headers
module being installed.
(On Debian/Ubuntu, sudo a2enmod headers
and restart Apache)
<Location />
# Make sure that if it is an XHR request,
# we don't send back basic authentication header.
# This is to prevent the browser from displaying a basic auth login dialog.
Header unset WWW-Authenticate "expr=req('X-Requested-With') == 'XMLHttpRequest' && resp('WWW-Authenticate') =~ /^Basic/"
</Location>
javascript date + 7 days
Without declaration
To return timestamp
new Date().setDate(new Date().getDate() + 7)
To return date
new Date(new Date().setDate(new Date().getDate() + 7))
How to control the width of select tag?
Add div wrapper
<div id=myForm>
<select name=countries>
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
</div>
and then write CSS
#myForm select {
width:200px; }
#myForm select:focus {
width:auto; }
Hope this will help.
Exporting the values in List to excel
Using ClosedXML library( there is no need to install MS Excel
I just write a simple example to show you how you can name the file, the worksheet and select cells:
var workbook = new XLWorkbook();
workbook.AddWorksheet("sheetName");
var ws = workbook.Worksheet("sheetName");
int row = 1;
foreach (object item in itemList)
{
ws.Cell("A" + row.ToString()).Value = item.ToString();
row++;
}
workbook.SaveAs("yourExcel.xlsx");
If you prefer you can create a System.Data.DataSet or a System.Data.DataTable with all data and then just add it as a workseet with workbook.AddWorksheet(yourDataset)
or workbook.AddWorksheet(yourDataTable)
;
Gunicorn worker timeout error
This worked for me:
gunicorn app:app -b :8080 --timeout 120 --workers=3 --threads=3 --worker-connections=1000
If you have eventlet
add:
--worker-class=eventlet
If you have gevent
add:
--worker-class=gevent
How to take backup of a single table in a MySQL database?
You can either use mysqldump
from the command line:
mysqldump -u username -p password dbname tablename > "path where you want to dump"
You can also use MySQL Workbench:
Go to left > Data Export > Select Schema > Select tables and click on Export