printing out a 2-D array in Matrix format
In java8 fashion:
import java.util.Arrays;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[4][4];
printMatrix(matrix);
}
public static void printMatrix(int[][] matrix) {
Arrays.stream(matrix)
.forEach(
(row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
}
);
}
}
this produces
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]
but since we are here why not make the row layout customisable?
All we need is to pass a lamba to the matrixPrinter method:
import java.util.Arrays;
import java.util.function.Consumer;
public class MatrixPrinter {
public static void main(String[] args) {
final int[][] matrix = new int[3][3];
Consumer<int[]> noDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
System.out.println();
};
Consumer<int[]> pipeDelimiter = (row) -> {
Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
System.out.println("|");
};
Consumer<int[]> likeAList = (row) -> {
System.out.print("[");
Arrays.stream(row)
.forEach((el) -> System.out.print(" " + el + " "));
System.out.println("]");
};
printMatrix(matrix, noDelimiter);
System.out.println();
printMatrix(matrix, pipeDelimiter);
System.out.println();
printMatrix(matrix, likeAList);
}
public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
Arrays.stream(matrix)
.forEach((row) -> rowPrinter.accept(row));
}
}
this is the result :
0 0 0
0 0 0
0 0 0
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
[ 0 0 0 ]
[ 0 0 0 ]
[ 0 0 0 ]
javascript function wait until another function to finish
There are several ways I can think of to do this.
Use a callback:
function FunctInit(someVarible){
//init and fill screen
AndroidCallGetResult(); // Enables Android button.
}
function getResult(){ // Called from Android button only after button is enabled
//return some variables
}
Use a Timeout (this would probably be my preference):
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
if (inited) {
//return some variables
} else {
setTimeout(getResult, 250);
}
}
Wait for the initialization to occur:
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
var a = 1;
do { a=1; }
while(!inited);
//return some variables
}
How to determine the longest increasing subsequence using dynamic programming?
Here is a Scala implementation of the O(n^2) algorithm:
object Solve {
def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
xs.foldLeft(List[(Int, List[T])]()) {
(sofar, x) =>
if (sofar.isEmpty) List((1, List(x)))
else {
val resIfEndsAtCurr = (sofar, xs).zipped map {
(tp, y) =>
val len = tp._1
val seq = tp._2
if (ord.lteq(y, x)) {
(len + 1, x :: seq) // reversely recorded to avoid O(n)
} else {
(1, List(x))
}
}
sofar :+ resIfEndsAtCurr.maxBy(_._1)
}
}.maxBy(_._1)._2.reverse
}
def main(args: Array[String]) = {
println(longestIncrSubseq(List(
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)))
}
}
Finding the number of non-blank columns in an Excel sheet using VBA
Jean-François Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count
or UsedRange.Rows.Count
.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).
How can I convert a Word document to PDF?
Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.
- Download JACOB archive (the latest version is 1.19);
- Add jacob.jar to your project classpath;
- Add jacob-1.19-x32.dll or jacob-1.19-x64.dll (depends on your jdk version) to ...\Java\jdk1.x.x_xxx\jre\bin
Using JACOB API call Office Word to convert doc/docx to pdf.
public void convertDocx2pdf(String docxFilePath) {
File docxFile = new File(docxFilePath);
String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
if (docxFile.exists()) {
if (!docxFile.isDirectory()) {
ActiveXComponent app = null;
long start = System.currentTimeMillis();
try {
ComThread.InitMTA(true);
app = new ActiveXComponent("Word.Application");
Dispatch documents = app.getProperty("Documents").toDispatch();
Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
File target = new File(pdfFile);
if (target.exists()) {
target.delete();
}
Dispatch.call(document, "SaveAs", pdfFile, 17);
Dispatch.call(document, "Close", false);
long end = System.currentTimeMillis();
logger.info("============Convert Finished:" + (end - start) + "ms");
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
throw new RuntimeException("pdf convert failed.");
} finally {
if (app != null) {
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
}
}
}
}
ASP.NET Core Web API Authentication
You can use an ActionFilterAttribute
public class BasicAuthAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected NetworkCredential Nc { get; set; }
public BasicAuthAttribute(string user,string pass)
{
this.Nc = new NetworkCredential(user,pass);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"].ToString();
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring(6)))
.Split(':');
var user = new {Name = cred[0], Pass = cred[1]};
if (user.Name == Nc.UserName && user.Pass == Nc.Password) return;
}
filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
filterContext.Result = new UnauthorizedResult();
}
}
and add the attribute to your controller
[BasicAuth("USR", "MyPassword")]
Matplotlib/pyplot: How to enforce axis range?
I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show
function and savefig
function.
before you plot:
fig = pylab.figure()
ax = fig.gca()
ax.set_autoscale_on(False)
This is to request an ax
which is subplot(1,1,1)
.
During the plot:
ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
After the plot:
To show the image :
fig.show()
To save the figure :
fig.savefig('the name of your figure')
I find out that put axis
at the front of the code won't work even though I have set autoscale_on
to False
.
I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation.
How to inspect FormData?
You have to understand that FormData::entries()
returns an instance of Iterator
.
Take this example form:
<form name="test" id="form-id">
<label for="name">Name</label>
<input name="name" id="name" type="text">
<label for="pass">Password</label>
<input name="pass" id="pass" type="text">
</form>
and this JS-loop:
<script>
var it = new FormData( document.getElementById('form-id') ).entries();
var current = {};
while ( ! current.done ) {
current = it.next();
console.info( current )
}
</script>
intellij incorrectly saying no beans of type found for autowired repository
Sometimes you are required to indicate where @ComponentScan should scan for components. You can do so by passing the packages as parameter of this annotation, e.g:
@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})
However, as already mentioned, @SpringBootApplication annotation replaces @ComponentScan, hence in such cases you must do the same:
@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})
At least in my case, Intellij stopped complaining.
Iterate through 2 dimensional array
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
Add "Appendix" before "A" in thesis TOC
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
How do I use $rootScope in Angular to store variables?
Variables set at the root-scope are available to the controller scope via prototypical inheritance.
Here is a modified version of @Nitish's demo that shows the relationship a bit clearer:
http://jsfiddle.net/TmPk5/6/
Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change
function). Also, the rootScope's value can be updated too (the changeRs
function in myCtrl2
)
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
A component is changing an uncontrolled input of type text to be controlled error in ReactJS
The reason is, in state you defined:
this.state = { fields: {} }
fields as a blank object, so during the first rendering this.state.fields.name
will be undefined
, and the input field will get its value as:
value={undefined}
Because of that, the input field will become uncontrolled.
Once you enter any value in input, fields
in state gets changed to:
this.state = { fields: {name: 'xyz'} }
And at that time the input field gets converted into a controlled component; that's why you are getting the error:
A component is changing an uncontrolled input of type text to be
controlled.
Possible Solutions:
1- Define the fields
in state as:
this.state = { fields: {name: ''} }
2- Or define the value property by using Short-circuit evaluation like this:
value={this.state.fields.name || ''} // (undefined || '') = ''
Use of document.getElementById in JavaScript
Here in your code demo
is id where you want to display your result after click event has occur and just nothing.
You can take anything
<p id="demo">
or
<div id="demo">
It is just node in a document where you just want to display your result.
Import an Excel worksheet into Access using VBA
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
Determine the number of lines within a text file
Reading a file in and by itself takes some time, garbage collecting the result is another problem as you read the whole file just to count the newline character(s),
At some point, someone is going to have to read the characters in the file, regardless if this the framework or if it is your code. This means you have to open the file and read it into memory if the file is large this is going to potentially be a problem as the memory needs to be garbage collected.
Nima Ara made a nice analysis that you might take into consideration
Here is the solution proposed, as it reads 4 characters at a time, counts the line feed character and re-uses the same memory address again for the next character comparison.
private const char CR = '\r';
private const char LF = '\n';
private const char NULL = (char)0;
public static long CountLinesMaybe(Stream stream)
{
Ensure.NotNull(stream, nameof(stream));
var lineCount = 0L;
var byteBuffer = new byte[1024 * 1024];
const int BytesAtTheTime = 4;
var detectedEOL = NULL;
var currentChar = NULL;
int bytesRead;
while ((bytesRead = stream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
var i = 0;
for (; i <= bytesRead - BytesAtTheTime; i += BytesAtTheTime)
{
currentChar = (char)byteBuffer[i];
if (detectedEOL != NULL)
{
if (currentChar == detectedEOL) { lineCount++; }
currentChar = (char)byteBuffer[i + 1];
if (currentChar == detectedEOL) { lineCount++; }
currentChar = (char)byteBuffer[i + 2];
if (currentChar == detectedEOL) { lineCount++; }
currentChar = (char)byteBuffer[i + 3];
if (currentChar == detectedEOL) { lineCount++; }
}
else
{
if (currentChar == LF || currentChar == CR)
{
detectedEOL = currentChar;
lineCount++;
}
i -= BytesAtTheTime - 1;
}
}
for (; i < bytesRead; i++)
{
currentChar = (char)byteBuffer[i];
if (detectedEOL != NULL)
{
if (currentChar == detectedEOL) { lineCount++; }
}
else
{
if (currentChar == LF || currentChar == CR)
{
detectedEOL = currentChar;
lineCount++;
}
}
}
}
if (currentChar != LF && currentChar != CR && currentChar != NULL)
{
lineCount++;
}
return lineCount;
}
Above you can see that a line is read one character at a time as well by the underlying framework as you need to read all characters to see the line feed.
If you profile it as done bay Nima you would see that this is a rather fast and efficient way of doing this.
Check Whether a User Exists
You can also check user by id
command.
id -u name
gives you the id of that user.
if the user doesn't exist, you got command return value ($?
)1
And as other answers pointed out: if all you want is just to check if the user exists, use if
with id
directly, as if
already checks for the exit code. There's no need to fiddle with strings, [
, $?
or $()
:
if id "$1" &>/dev/null; then
echo 'user found'
else
echo 'user not found'
fi
(no need to use -u
as you're discarding the output anyway)
Also, if you turn this snippet into a function or script, I suggest you also set your exit code appropriately:
#!/bin/bash
user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
if user_exists "$1"; code=$?; then # use the function, save the code
echo 'user found'
else
echo 'user not found' >&2 # error messages should go to stderr
fi
exit $code # set the exit code, ultimately the same set by `id`
Angular2 equivalent of $document.ready()
the accepted answer is not correct, and it makes no sens to accept it considering the question
ngAfterViewInit will trigger when the DOM is ready
whine ngOnInit will trigger when the page component is only starting to be created
What's the use of ob_start() in php?
You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start
allows you to keep the content in a server-side buffer until you are ready to display it.
This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).
How do you create nested dict in Python?
UPDATE: For an arbitrary length of a nested dictionary, go to this answer.
Use the defaultdict function from the collections.
High performance: "if key not in dict" is very expensive when the data set is large.
Low maintenance: make the code more readable and can be easily extended.
from collections import defaultdict
target_dict = defaultdict(dict)
target_dict[key1][key2] = val
SSH to Elastic Beanstalk instance
There is a handy 'Connect' option in the 'Instance Actions' menu for the EC2 instance. It will give you the exact SSH command to execute with the correct url for the instance. Jabley's overall instructions are correct.
Check if an element is present in a Bash array
You could do:
if [[ " ${arr[*]} " == *" d "* ]]; then
echo "arr contains d"
fi
This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.
The safest way is to loop over the array until you find the element:
array_contains () {
local seeking=$1; shift
local in=1
for element; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no # no
array_contains "d e" "${arr[@]}" && echo yes || echo no # yes
Here's a "cleaner" version where you just pass the array name, not all its elements
array_contains2 () {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
array_contains2 arr "a b" && echo yes || echo no # no
array_contains2 arr "d e" && echo yes || echo no # yes
For associative arrays, there's a very tidy way to test if the array contains a given key: The -v
operator
$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no
See 6.4 Bash Conditional Expressions in the manual.
Git log to get commits only for a specific branch
I found this approach relatively easy.
Checkout to the branch and than
Run
git rev-list --simplify-by-decoration -2 HEAD
This will provide just two SHAs:
1) last commit of the branch [C1]
2) and commit parent to the first commit of the branch [C2]
Now run
git log --decorate --pretty=oneline --reverse --name-status <C2>..<C1>
Here C1 and C2 are two strings you will get when you run first command. Put these values without <> in second command.
This will give list of history of file changing within the branch.
Left Join without duplicate rows from left table
You can do this using generic SQL with group by
:
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
tbl_Media M
ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;
Or with a correlated subquery:
SELECT C.Content_ID, C.Contt_Title,
(SELECT M.Media_Id
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
ORDER BY M.MEDIA_ID DESC
LIMIT 1
) as Media_Id
FROM tbl_Contents C
ORDER BY C.Content_DatePublished ASC;
Of course, the syntax for limit 1
varies between databases. Could be top
. Or rownum = 1
. Or fetch first 1 rows
. Or something like that.
Null & empty string comparison in Bash
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
WPF: Grid with column/row margin/padding?
You could use something like this:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="4" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
Or if you don't need the TemplateBindings:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="4">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
How to get host name with port from a http or https request
You can use HttpServletRequest.getScheme()
to retrieve either "http" or "https".
Using it along with HttpServletRequest.getServerName()
should be enough to rebuild the portion of the URL you need.
You don't need to explicitly put the port in the URL if you're using the standard ones (80 for http and 443 for https).
Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it's a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:
1) Use HttpServletRequest.getHeader("x-forwarded-proto")
instead; this only works if your load balancer sets the header correctly (Apache should afaik).
2) Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme()
work as expected. Again, this will only work if the load balancer sets the correct headers.
3) If the above don't work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.
How to import load a .sql or .csv file into SQLite?
To go from SCRATCH with SQLite DB to importing the CSV into a table:
- Get SQLite from the website.
- At a command prompt run
sqlite3 <your_db_file_name>
*It will be created as an empty file.
- Make a new table in your new database. The table must match your CSV fields for import.
- You do this by the SQL command:
CREATE TABLE <table_Name> (<field_name1> <Type>, <field_name2> <type>);
Once you have the table created and the columns match your data from the file then you can do the above...
.mode csv <table_name>
.import <filename> <table_name>
change <audio> src with javascript
If you are storing metadata in a tag use data attributes eg.
<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>
Now use the attribute to get the name of the song
var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();
Can I configure a subdomain to point to a specific port on my server
If you want to host multiple websites in a single server in different ports then, method mentioned by MRVDOG won't work. Because browser won't resolve SRV records and will always hit :80
port.
For example if your requirement is:
site1.domain.com maps to domain.com:8080
site2.domain.com maps to domain.com:8081
Because often you want to fully utilize the server space you have bought.
Then you can try the following:
Step 1:
Install proxy server. I will use Nginx here.
apt-get install nginx
Step 2:
Edit /etc/nginx/nginx.conf
file to add the port mappings. To do so, add the following lines:
server {
listen 80;
server_name site1.domain.com;
location / {
proxy_pass http://localhost:8080;
}
}
server {
listen 80;
server_name site2.domain.com;
location / {
proxy_pass http://localhost:8081;
}
}
This does the magic. So the file will end up looking like following:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
server {
listen 80;
server_name site1.domain.com;
location / {
proxy_pass http://localhost:8080;
}
}
server {
listen 80;
server_name site2.domain.com;
location / {
proxy_pass http://localhost:8081;
}
}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
Step 3:
Start nginx:
/etc/init.d/nginx start
.
Whenever you make any changes to configuration, you need to restart nginx:
/etc/init.d/nginx restart
Finally:
Don't forget to add A records in your DNS configuration. All subdomains should point to domain. Like this:
Put your static ip instead of 111.11.111.111
Further details:
Sending email with PHP from an SMTP server
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
n-grams in python, four, five, six grams?
If efficiency is an issue and you have to build multiple different n-grams (up to a hundred as you say), but you want to use pure python I would do:
from itertools import chain
def n_grams(seq, n=1):
"""Returns an itirator over the n-grams given a listTokens"""
shiftToken = lambda i: (el for j,el in enumerate(seq) if j>=i)
shiftedTokens = (shiftToken(i) for i in range(n))
tupleNGrams = zip(*shiftedTokens)
return tupleNGrams # if join in generator : (" ".join(i) for i in tupleNGrams)
def range_ngrams(listTokens, ngramRange=(1,2)):
"""Returns an itirator over all n-grams for n in range(ngramRange) given a listTokens."""
return chain(*(n_grams(listTokens, i) for i in range(*ngramRange)))
Usage :
>>> input_list = input_list = 'test the ngrams generator'.split()
>>> list(range_ngrams(input_list, ngramRange=(1,3)))
[('test',), ('the',), ('ngrams',), ('generator',), ('test', 'the'), ('the', 'ngrams'), ('ngrams', 'generator'), ('test', 'the', 'ngrams'), ('the', 'ngrams', 'generator')]
~Same speed as NLTK:
import nltk
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=5)
# 7.02 ms ± 79 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
n_grams(input_list,n=5)
# 7.01 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=1)
nltk.ngrams(input_list,n=2)
nltk.ngrams(input_list,n=3)
nltk.ngrams(input_list,n=4)
nltk.ngrams(input_list,n=5)
# 7.32 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
range_ngrams(input_list, ngramRange=(1,6))
# 7.13 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Repost from my previous answer.
What is Python used for?
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
- Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
- Python is strongly typed. It means that if
a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.
- Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
- Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
- Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
- The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.
Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
How to strip all non-alphabetic characters from string in SQL Server?
Here is another way to remove non-alphabetic characters using an iTVF
. First, you need a pattern-based string splitter. Here is one taken from Dwain Camp's article:
-- PatternSplitCM will split a string based on a pattern of the form
-- supported by LIKE and PATINDEX
--
-- Created by: Chris Morris 12-Oct-2012
CREATE FUNCTION [dbo].[PatternSplitCM]
(
@List VARCHAR(8000) = NULL
,@Pattern VARCHAR(50)
) RETURNS TABLE WITH SCHEMABINDING
AS
RETURN
WITH numbers AS (
SELECT TOP(ISNULL(DATALENGTH(@List), 0))
n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n)
)
SELECT
ItemNumber = ROW_NUMBER() OVER(ORDER BY MIN(n)),
Item = SUBSTRING(@List,MIN(n),1+MAX(n)-MIN(n)),
[Matched]
FROM (
SELECT n, y.[Matched], Grouper = n - ROW_NUMBER() OVER(ORDER BY y.[Matched],n)
FROM numbers
CROSS APPLY (
SELECT [Matched] = CASE WHEN SUBSTRING(@List,n,1) LIKE @Pattern THEN 1 ELSE 0 END
) y
) d
GROUP BY [Matched], Grouper
Now that you have a pattern-based splitter, you need to split the strings that match the pattern:
[a-z]
and then concatenate them back to get the desired result:
SELECT *
FROM tbl t
CROSS APPLY(
SELECT Item + ''
FROM dbo.PatternSplitCM(t.str, '[a-z]')
WHERE Matched = 1
ORDER BY ItemNumber
FOR XML PATH('')
) x (a)
SAMPLE
Result:
| Id | str | a |
|----|------------------|----------------|
| 1 | test“te d'abc | testtedabc |
| 2 | anr¤a | anra |
| 3 | gs-re-C“te d'ab | gsreCtedab |
| 4 | M‚fe, DF | MfeDF |
| 5 | R™temd | Rtemd |
| 6 | ™jad”ji | jadji |
| 7 | Cje y ret¢n | Cjeyretn |
| 8 | J™kl™balu | Jklbalu |
| 9 | le“ne-iokd | leneiokd |
| 10 | liode-Pyr‚n‚ie | liodePyrnie |
| 11 | V„s G”ta | VsGta |
| 12 | Sƒo Paulo | SoPaulo |
| 13 | vAstra gAtaland | vAstragAtaland |
| 14 | ¥uble / Bio-Bio | ubleBioBio |
| 15 | U“pl™n/ds VAsb-y | UplndsVAsby |
remove inner shadow of text input
All browsers, including Safari (+ mobile):
input[type=text] {
/* Remove */
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* Optional */
border: solid;
box-shadow: none;
/*etc.*/
}
How to execute UNION without sorting? (SQL)
Try this:
SELECT DISTINCT * FROM (
SELECT column1, column2 FROM Table1
UNION ALL
SELECT column1, column2 FROM Table2
UNION ALL
SELECT column1, column2 FROM Table3
) X ORDER BY Column1
How to read a single char from the console in Java (as the user types it)?
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
- On Windows it uses
_kbhit()
and _getwch()
from msvcrt.dll.
- On Unix it uses
tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.
It supports non-blocking input and mixing raw mode and normal line mode input.
How do you create a remote Git branch?
[Quick Answer]
You can do it in 2 steps:
1. Use the checkout
for create the local branch:
git checkout -b yourBranchName
2. Use the push
command to autocreate the branch and send the code to the remote repository:
git push -u origin yourBranchName
There are multiple ways to do this but I think that this way is really simple.
MySQL InnoDB not releasing disk space after deleting data rows from table
Other way to solve the problem of space reclaiming is, Create multiple partitions within table - Range based, Value based partitions and just drop/truncate the partition to reclaim the space, which will release the space used by whole data stored in the particular partition.
There will be some changes needed in table schema when you introduce the partitioning for your table like - Unique Keys, Indexes to include partition column etc.
How do I make WRAP_CONTENT work on a RecyclerView
You must put a FrameLayout as Main view then put inside a RelativeLayout with ScrollView and at least your RecyclerView, it works for me.
The real trick here is the RelativeLayout...
Happy to help.
Bold & Non-Bold Text In A Single UILabel?
Try a category on UILabel:
Here's how it's used:
myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
And here's the category
UILabel+Boldify.h
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
UILabel+Boldify.m
- (void) boldRange: (NSRange) range {
if (![self respondsToSelector:@selector(setAttributedText:)]) {
return;
}
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
self.attributedText = attributedText;
}
- (void) boldSubstring: (NSString*) substring {
NSRange range = [self.text rangeOfString:substring];
[self boldRange:range];
}
Note that this will only work in iOS 6 and later. It will simply be ignored in iOS 5 and earlier.
web-api POST body object always null
FromBody is a strange attribute in that the input POST values need to be in a specific format for the parameter to be non-null, when it is not a primitive type. (student here)
- Try your request with
{"name":"John Doe", "age":18, "country":"United States of America"}
as the json.
- Remove the
[FromBody]
attribute and try the solution. It should work for non-primitive types. (student)
- With the
[FromBody]
attribute, the other option is to send the values in =Value
format, rather than key=value
format. This would mean your key value of student
should be an empty string...
There are also other options to write a custom model binder for the student class and attribute the parameter with your custom binder.
How is the java memory pool divided?
Heap memory
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Here's some documentation on how to use Jconsole.
Java character array initializer
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt()
in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
How to set data attributes in HTML elements
[jQuery] .data() vs .attr() vs .extend()
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I'm correct.
If you'd like to update your data-attributes
with some spread, use --
$('body').attr({ 'data-test': 'text' });
-- otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using --
$.extend( $('body')[0].dataset, { datum: true } );
-- which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
form action with javascript
A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.
The best is to just set form action
to your PHP script; if you need to do anything before submission you can just add to onsubmit
Edit turned out you didn't need any extra function, just a small change here:
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateName(theForm.name);
reason += validatePhone(theForm.phone);
reason += validateEmail(theForm.emaile);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
} else {
simpleCart.checkout();
}
return false;
}
Then in your form:
<form action="#" onsubmit="return validateFormOnSubmit(this);">
Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)
There's no "simple command" to do that. You can write a function, or take your choice of several that are available online in various code repositories. I use this:
function get-loggedonuser ($computername){
#mjolinor 3/17/10
$regexa = '.+Domain="(.+)",Name="(.+)"$'
$regexd = '.+LogonId="(\d+)"$'
$logontype = @{
"0"="Local System"
"2"="Interactive" #(Local logon)
"3"="Network" # (Remote logon)
"4"="Batch" # (Scheduled task)
"5"="Service" # (Service account logon)
"7"="Unlock" #(Screen saver)
"8"="NetworkCleartext" # (Cleartext network logon)
"9"="NewCredentials" #(RunAs using alternate credentials)
"10"="RemoteInteractive" #(RDP\TS\RemoteAssistance)
"11"="CachedInteractive" #(Local w\cached credentials)
}
$logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
$logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)
$session_user = @{}
$logon_users |% {
$_.antecedent -match $regexa > $nul
$username = $matches[1] + "\" + $matches[2]
$_.dependent -match $regexd > $nul
$session = $matches[1]
$session_user[$session] += $username
}
$logon_sessions |%{
$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)
$loggedonuser = New-Object -TypeName psobject
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime
$loggedonuser
}
}
Check if value exists in the array (AngularJS)
You can use indexOf(). Like:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);
The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.
If you want to search from end to start, use the lastIndexOf() method:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.lastIndexOf("brown");
alert(a);
The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.
Returns -1 if the item is not found.
sendmail: how to configure sendmail on ubuntu?
I got the top answer working (can't reply yet) after one small edit
This did not work for me:
FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl
The first single quote for each string should be changed to a backtick (`) like this:
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
After the change I run:
sudo sendmailconfig
And I'm in business :)
Latex - Change margins of only a few pages
I could not find a easy way to set the margin for a single page.
My solution was to use vspace with the number of centimeters of empty space I wanted:
\vspace*{5cm}
I put this command at the beginning of the pages that I wanted to have +5cm of margin.
SQL "select where not in subquery" returns no results
Let's suppose these values for common_id:
Common - 1
Table1 - 2
Table2 - 3, null
We want the row in Common to return, because it doesn't exist in any of the other tables. However, the null throws in a monkey wrench.
With those values, the query is equivalent to:
select *
from Common
where 1 not in (2)
and 1 not in (3, null)
That is equivalent to:
select *
from Common
where not (1=2)
and not (1=3 or 1=null)
This is where the problem starts. When comparing with a null, the answer is unknown. So the query reduces to
select *
from Common
where not (false)
and not (false or unkown)
false or unknown is unknown:
select *
from Common
where true
and not (unknown)
true and not unkown is also unkown:
select *
from Common
where unknown
The where condition does not return records where the result is unkown, so we get no records back.
One way to deal with this is to use the exists operator rather than in. Exists never returns unkown because it operates on rows rather than columns. (A row either exists or it doesn't; none of this null ambiguity at the row level!)
select *
from Common
where not exists (select common_id from Table1 where common_id = Common.common_id)
and not exists (select common_id from Table2 where common_id = Common.common_id)
What is difference between Lightsail and EC2?
Lightsail VPSs are bundles of existing AWS products, offered through a significantly simplified interface. The difference is that Lightsail offers you a limited and fixed menu of options but with much greater ease of use. Other than the narrower scope of Lightsail in order to meet the requirements for simplicity and low cost, the underlying technology is the same.
The pre-defined bundles can be described:
% aws lightsail --region us-east-1 get-bundles
{
"bundles": [
{
"name": "Nano",
"power": 300,
"price": 5.0,
"ramSizeInGb": 0.5,
"diskSizeInGb": 20,
"transferPerMonthInGb": 1000,
"cpuCount": 1,
"instanceType": "t2.nano",
"isActive": true,
"bundleId": "nano_1_0"
},
...
]
}
It's worth reading through the Amazon EC2 T2 Instances documentation, particularly the CPU Credits section which describes the base and burst performance characteristics of the underlying instances.
Importantly, since your Lightsail instances run in VPC, you still have access to the full spectrum of AWS services, e.g. S3, RDS, and so on, as you would from any EC2 instance.
Using the star sign in grep
The dot character means match any character, so .*
means zero or more occurrences of any character. You probably mean to use .*
rather than just *
.
Changing Font Size For UITableView Section Headers
This is my solution with swift 5.
To fully control the header section view, you need to use the tableView(:viewForHeaderInsection::) method in your controller, as the previous post showed. However, there is a further step: to improve performance, apple recommend not generate a new view every time but to re-use the header view, just like reuse table cell. This is by method tableView.dequeueReusableHeaderFooterView(withIdentifier: ). But the problem I had is once you start to use this re-use function, the font won't function as expected. Other things like color, alignment all fine but just font. There are some discussions but I made it work like the following.
The problem is tableView.dequeueReusableHeaderFooterView(withIdentifier:) is not like tableView.dequeneReuseCell(:) which always returns a cell. The former will return a nil if no one available. Even if it returns a reuse header view, it is not your original class type, but a UITableHeaderFooterView. So you need to do the judgement and act according in your own code. Basically, if it is nil, get a brand new header view. If not nil, force to cast so you can control.
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let reuse_header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourHeaderID")
if (reuse_header == nil) {
let new_sec_header = YourTableHeaderViewClass(reuseIdentifier:"yourHeaderID")
new_section_header.label.text="yourHeaderString"
//do whatever to set color. alignment, etc to the label view property
//note: the label property here should be your custom label view. Not the build-in labelView. This way you have total control.
return new_section_header
}
else {
let new_section_header = reuse_section_header as! yourTableHeaderViewClass
new_sec_header.label.text="yourHeaderString"
//do whatever color, alignment, etc to the label property
return new_sec_header}
}
Array[n] vs Array[10] - Initializing array with variable vs real number
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
nodejs npm global config missing on windows
It looks like the files npm
uses to edit its config files are not created on a clean install, as npm
has a default option for each one. This is why you can still get options with npm config get <option>
: having those files only overrides the defaults, it doesn't create the options from scratch.
I had never touched my npm config
stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc
(on a Windows 8.1 machine with Git Bash
), yet I could run npm config get <something>
and, if it was a correct npm
option, it returned a value. When I ran npm config set <option> <value>
, the file ~/.npmrc
seemed to be created automatically, with the option & its value as the only non-commented-out line.
As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc
is deleted, too, and recreated if you set
anything else later.
In your case (assuming it is still the same over a year later), it looks like you never set the proxy
option in npm
. Therefore, as npm
's config
help page says, it is set to whatever your http_proxy
(case-insensitive) environment variable is. This means there is nothing to delete
, unless you want to "delete" your HTTP proxy, although you could set
the option or environment variable to something else and hope neither breaks your set-up somehow.
LINQ: Select where object does not contain items from list
Try this simple LINQ:
//For a file list/array
var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
//simply use Where ! x.Contains
var notContain = files.Where(x => ! x.Contains(@"\$RECYCLE.BIN\")).ToList();
//Or use Except()
var containing = files.Where(x => x.Contains(@"\$RECYCLE.BIN\")).ToList();
notContain = files.Except(containing).ToList();
What is a Subclass
A subclass is something that extends the functionality of your existing class. I.e.
Superclass - describes the catagory of objects:
public abstract class Fruit {
public abstract Color color;
}
Subclass1 - describes attributes of the individual Fruit objects:
public class Apple extends Fruit {
Color color = red;
}
Subclass2 - describes attributes of the individual Fruit objects:
public class Banana extends Fruit {
Color color = yellow;
}
The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.
Does that make sense?
CSS Background image not loading
i can bring a little help here... it seems that when you use say background-image: url("/images/image.jpg"); or background-image: url("images/image.jpg"); or background-image: url("../images/image.jpg"); different browsers appear to see this differently. the first the browser seems to see this as domain.com/images/image.jpg.... the second the browser sees at domain.com/css/images/image.jpg.... and the final the browser sees as domain.com/PathToImageFile/image.jpg... hopes this helps
What are the differences between Abstract Factory and Factory design patterns?
A lot of the previous answers do not provide code comparisons between Abstract Factory and Factory Method pattern. The following is my attempt at explaining it via Java. I hope it helps someone in need of a simple explanation.
As GoF aptly says: Abstract Factory provides an interface for creating families of related or dependent objects without specifying
their concrete classes.
public class Client {
public static void main(String[] args) {
ZooFactory zooFactory = new HerbivoreZooFactory();
Animal animal1 = zooFactory.animal1();
Animal animal2 = zooFactory.animal2();
animal1.sound();
animal2.sound();
System.out.println();
AnimalFactory animalFactory = new CowAnimalFactory();
Animal animal = animalFactory.createAnimal();
animal.sound();
}
}
public interface Animal {
public void sound();
}
public class Cow implements Animal {
@Override
public void sound() {
System.out.println("Cow moos");
}
}
public class Deer implements Animal {
@Override
public void sound() {
System.out.println("Deer grunts");
}
}
public class Hyena implements Animal {
@Override
public void sound() {
System.out.println("Hyena.java");
}
}
public class Lion implements Animal {
@Override
public void sound() {
System.out.println("Lion roars");
}
}
public interface ZooFactory {
Animal animal1();
Animal animal2();
}
public class CarnivoreZooFactory implements ZooFactory {
@Override
public Animal animal1() {
return new Lion();
}
@Override
public Animal animal2() {
return new Hyena();
}
}
public class HerbivoreZooFactory implements ZooFactory {
@Override
public Animal animal1() {
return new Cow();
}
@Override
public Animal animal2() {
return new Deer();
}
}
public interface AnimalFactory {
public Animal createAnimal();
}
public class CowAnimalFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Cow();
}
}
public class DeerAnimalFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Deer();
}
}
public class HyenaAnimalFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Hyena();
}
}
public class LionAnimalFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Lion();
}
}
How to include (source) R script in other scripts
There is no such thing built-in, since R does not track calls to source
and is not able to figure out what was loaded from where (this is not the case when using packages). Yet, you may use same idea as in C .h
files, i.e. wrap the whole in:
if(!exists('util_R')){
util_R<-T
#Code
}
git cherry-pick says "...38c74d is a merge but no -m option was given"
The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.
So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?
You're trying to cherry pick fd9f578
, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m
option. For example, git cherry-pick -m 1 fd9f578
to use parent 1 as the base.
I can't say for sure for your particular situation, but using git merge
instead of git cherry-pick
is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
Custom seekbar (thumb size, color and background)
android:minHeight android:maxHeight is important for that.
<SeekBar
android:id="@+id/pb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="2dp"
android:minHeight="2dp"
android:progressDrawable="@drawable/seekbar_bg"
android:thumb="@drawable/seekbar_thumb"
android:max="100"
android:progress="50"/>
seekbar_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="3dp" />
<solid android:color="#ECF0F1" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="3dp" />
<solid android:color="#C6CACE" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="3dp" />
<solid android:color="#16BC5C" />
</shape>
</clip>
</item>
</layer-list>
seekbar_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#16BC5C" />
<stroke
android:width="1dp"
android:color="#16BC5C" />
<size
android:height="20dp"
android:width="20dp" />
</shape>
How do I set the visibility of a text box in SSRS using an expression?
I tried the example that you have provided and the only difference is that you have True and False values switched as @bdparrish
had pointed out. Here is a working example of making an SSRS Texbox visible or hidden based on the number of rows present in a dataset. This example uses SSRS 2008 R2
.
Step-by-step process: SSRS 2008 R2
In this example, the report has a dataset named Items
and has textbox to show row counts. It also has another textbox which will be visible only if the dataset Items has rows.
Right-click on the textbox that should be visible/hidden based on an expression and select Text Box Properties...
. Refer screenshot #1.
On the Text Box Properties
dialog, click on Visibility
from the left section. Refer screenshot #2.
Select Show or hide based on an epxression
.
Click on the expression button fx
.
Enter the expression =IIf(CountRows("Items") = 0 , True, False)
. Note that this expression is to hide the Textbox (Hidden).
Click OK twice to close the dialogs.
Screenshot #3 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains 3 rows. Screenshot #4 shows the sample report execution against the data.
Screenshot #5 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains no data. Screenshot #6 shows the sample report execution against the data.
Hope that helps.
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
How can I pass a list as a command-line argument with argparse?
If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,
[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]
then you can use the solution proposed by @sam-mason to this question, shown below:
from argparse import ArgumentParser
import json
parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])
which gives:
Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])
IIS7 Permissions Overview - ApplicationPoolIdentity
Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.
In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.
This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.
Credits to this answer: HTTP Error 401.3 - Unauthorized
How to link external javascript file onclick of button
It is totally possible, i did something similar based on the example of Mike Sav. That's the html page and ther shoul be an external test.js file in the same folder
example.html:
<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./test.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
document.getElementById('mylink').click();
}
</script>
</html>
test.js:
alert('hello world')
Can't push to the heroku
If you are using django app to deploy on heroku
make sure to put request library in the requirements.txt file.
Log all requests from the python-requests module
Just improving this answer
This is how it worked for me:
import logging
import sys
import requests
import textwrap
root = logging.getLogger('httplogger')
def logRoundtrip(response, *args, **kwargs):
extra = {'req': response.request, 'res': response}
root.debug('HTTP roundtrip', extra=extra)
class HttpFormatter(logging.Formatter):
def _formatHeaders(self, d):
return '\n'.join(f'{k}: {v}' for k, v in d.items())
def formatMessage(self, record):
result = super().formatMessage(record)
if record.name == 'httplogger':
result += textwrap.dedent('''
---------------- request ----------------
{req.method} {req.url}
{reqhdrs}
{req.body}
---------------- response ----------------
{res.status_code} {res.reason} {res.url}
{reshdrs}
{res.text}
''').format(
req=record.req,
res=record.res,
reqhdrs=self._formatHeaders(record.req.headers),
reshdrs=self._formatHeaders(record.res.headers),
)
return result
formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(logging.DEBUG)
session = requests.Session()
session.hooks['response'].append(logRoundtrip)
session.get('http://httpbin.org')
java howto ArrayList push, pop, shift, and unshift
maybe you want to take a look java.util.Stack
class.
it has push, pop methods. and implemented List interface.
for shift/unshift, you can reference @Jon's answer.
however, something of ArrayList you may want to care about , arrayList is not synchronized. but Stack is. (sub-class of Vector). If you have thread-safe requirement, Stack may be better than ArrayList.
How to serialize object to CSV file?
For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.
EDIT
According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !
By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.
I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.
jQuery form input select by id
You can just target the id directly:
var value = $('#b').val();
If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.
If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:
var value = $('#a #b').val();
Adding ASP.NET MVC5 Identity Authentication to an existing project
This is what I did to integrate Identity with an existing database.
Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.
Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam
Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.
This is the SQL script I ran on my existing database to create necessary tables:
USE ["YourDatabse"]
GO
/****** Object: Table [dbo].[AspNetRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetRoles](
[Id] [nvarchar](128) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserClaims] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserLogins] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserLogins](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUsers] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEndDateUtc] [datetime] NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[AspNetUserClaims] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserLogins] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
GO
Check and solve any remaining errors and you are done. Identity will handle the rest :)
How to write the code for the back button?
In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
"getaddrinfo failed", what does that mean?
Make sure you pass a proxy attribute in your command
forexample - pip install --proxy=http://proxyhost:proxyport pixiedust
Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.
You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings
Uncheck - Use automatic configuration script
Check - Use a proxy server for your LAN. Ensure you have given the right address and port.
Click Ok
Come back to anaconda terminal and you can try install commands
Excel - extracting data based on another list
I have been hasseling with that as other folks have.
I used the criteria;
=countif(matchingList,C2)=0
where matchingList is the list that i am using as a filter.
have a look at this
http://www.youtube.com/watch?v=x47VFMhRLnM&list=PL63A7644FE57C97F4&index=30
The trick i found is that normally you would have the column heading in the criteria matching the data column heading. this will not work for criteria that is a formula.
What I found was if I left the column heading blank for only the criteria that has the countif
formula in the advanced filter works. If I have the column heading i.e. the column heading for column C2 in my formula example then the filter return no output.
Hope this helps
Check whether a path is valid
There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:
private bool IsValidPath(string path)
{
// Check if the path is rooted in a driver
if (path.Length < 3) return false;
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
// Check if such driver exists
IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;
// Check if the rest of the path is valid
string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
InvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
if (path[path.Length - 1] == '.') return false;
return true;
}
This solution does not take relative paths into account.
POST string to ASP.NET Web Api application - returns null
You seem to have used some [Authorize]
attribute on your Web API controller action and I don't see how this is relevant to your question.
So, let's get into practice. Here's a how a trivial Web API controller might look like:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
and a consumer for that matter:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
You will undoubtedly notice the [FromBody]
decoration of the Web API controller attribute as well as the =
prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.
As far as the [Authorize]
attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post
that I wrote on this topic interesting to get you started.
And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.
Default string initialization: NULL or Empty?
I think there's no reason not to use null for an unassigned (or at this place in a program flow not occurring) value.
If you want to distinguish, there's ==null.
If you just want to check for a certain value and don't care whether it's null or something different, String.Equals("XXX",MyStringVar) does just fine.
Converting dict to OrderedDict
You can create the ordered dict from old dict in one line:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())
The default sorting key is by dictionary key, so the new ordered_dict
is sorted by old dict's keys.
How to update/refresh specific item in RecyclerView
In your RecyclerView adapter, you should have an ArrayList and also one method addItemsToList(items)
to add list items to the ArrayList. Then you can add list items by call adapter.addItemsToList(items)
dynamically. After all your list items added to the ArrayList then you can call adapter.notifyDataSetChanged()
to display your list.
You can use the notifyDataSetChanged
in the adapter for the RecyclerView
Installing Numpy on 64bit Windows 7 with Python 2.7.3
Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl
as appropriate).
- Download (by right click and "save target") get-pip to local drive.
At the command prompt, navigate to the directory containing get-pip.py
and run
python get-pip.py
which creates files in C:\Python27\Scripts
, including pip2
, pip2.7
and pip
.
Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl
into the above directory (C:\Python27\Scripts
)
Still at the command prompt, navigate to the above directory and run:
pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"
Differences between C++ string == and compare()?
Suppose consider two string s and t.
Give them some values.
When you compare them using (s==t) it returns a boolean value(true or false , 1 or 0).
But when you compare using s.compare(t) ,the expression returns a value
(i) 0 - if s and t are equal
(ii) <0 - either if the value of the first unmatched character in s is less than that of t or the length of s is less than that of t.
(iii) >0 - either if the value of the first unmatched character in t is less than that of s or the length of t is less than that of s.
CSS3 Transition - Fade out effect
Here is another way to do the same.
fadeIn effect
.visible {
visibility: visible;
opacity: 1;
transition: opacity 2s linear;
}
fadeOut effect
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
UPDATE 1:
I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.
UPDATE 2:
(Added details requested by @big-money)
When showing the element (by switching to the visible class), we want the visibility:visible
to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden
declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.
I know I am too late to answer but posting this answer to save others time. Hope it helps you!!
Finding modified date of a file/folder
If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:
Get-Item c:\folder | Format-List
Or you can access the property directly like so:
Get-Item c:\folder | Foreach {$_.LastWriteTime}
To start to filter folders & files based on last write time you can do this:
Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
Mathematical functions in Swift
To use the math-functions you have to import Cocoa
You can see the other defined mathematical functions in the following way.
Make a Cmd-Click on the function name sqrt
and you enter the file with all other global math functions and constanst.
A small snippet of the file
...
func pow(_: CDouble, _: CDouble) -> CDouble
func sqrtf(_: CFloat) -> CFloat
func sqrt(_: CDouble) -> CDouble
func erff(_: CFloat) -> CFloat
...
var M_LN10: CDouble { get } /* loge(10) */
var M_PI: CDouble { get } /* pi */
var M_PI_2: CDouble { get } /* pi/2 */
var M_SQRT2: CDouble { get } /* sqrt(2) */
...
How do I rename a local Git branch?
Git branch rename can be done by using:
git branch -m oldBranch newBranch
git branch -M oldBranch ExistingBranch
The difference between -m and -M:
-m: if you're trying to rename your branch with an existing branch name using -m.
It will raise an error saying that the branch already exists. You need to give unique name.
But,
-M: this will help you to force rename with a given name, even it is exists. So an existing branch will overwrite entirely with it...
Here is a Git terminal example,
mohideen@dev:~/project/myapp/sunithamakeup$ git branch
master
master0
new_master
test
* test1
mohideen@dev:~/project/myapp/sunithamakeup$ git branch -m test1 test
fatal: A branch named 'test' already exists.
mohideen@dev:~/project/myapp/sunithamakeup$ git branch -M test1 test
mohideen@dev:~/project/myapp/sunithamakeup$ git branch
master
master0
new_master
* test
mohideen@dev:~/project/myapp/sunithamakeup$
How to multi-line "Replace in files..." in Notepad++
This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!
Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.
To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).
javascript node.js next()
It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send
in your each REST block...
So you can do something like this as a simple next()
example:
app.get("/", (req, res, next) => {
console.log("req:", req, "res:", res);
res.send(["data": "whatever"]);
next();
},(req, res) =>
console.log("it's all done!");
);
It's also very useful when you'd like to have a middleware in your app...
To load the middleware function, call app.use(), specifying the
middleware function. For example, the following code loads the
myLogger middleware function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
})
app.listen(3000);
Sorting a Dictionary in place with respect to keys
The correct answer is already stated (just use SortedDictionary).
However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...
Dictionary<string, int> dupcheck = new Dictionary<string, int>();
...some code that fills in "dupcheck", then...
if (dupcheck.Count > 0) {
Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
var keys_sorted = dupcheck.Keys.ToList();
keys_sorted.Sort();
foreach (var k in keys_sorted) {
Console.WriteLine("{0} = {1}", k, dupcheck[k]);
}
}
Don't forget using System.Linq;
for this.
How ViewBag in ASP.NET MVC works
ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class
They allow you to pass data from controller to view.
In controller......
public ActionResult Index()
{
ViewBag.victor = "My name is Victor";
return View();
}
In view
@foreach(string a in ViewBag.victor)
{
.........
}
What I have learnt is that both should have the save dynamic name property ie ViewBag.victor
Calculate Age in MySQL (InnoDb)
This is how to calculate the age in MySQL:
select
date_format(now(), '%Y') - date_format(date_of_birth, '%Y') -
(date_format(now(), '00-%m-%d') < date_format(date_of_birth, '00-%m-%d'))
as age from table
Dynamically fill in form values with jQuery
If you need to hit the database, you need to hit the web server again (for the most part).
What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.
AJAX calls can be made in jquery with the $.ajax() function call, so this will happen
User's browser enters input that fires a trigger that makes an AJAX call
$('input .callAjax').bind('change', function() {
$.ajax({ url: 'script/ajax',
type: json
data: $foo,
success: function(data) {
$('input .targetAjax').val(data.newValue);
});
);
Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.
You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.
The php function json_encode($phpobj); will be useful.
Send multiple checkbox data to PHP via jQuery ajax()
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]']
instead of myCheckboxes.push
Why do I get the "Unhandled exception type IOException"?
I got the Error even though i was catching the exception.
try {
bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
} catch (IOException e) {
Log.e("blabla", "Error", e);
finish();
}
Issue was that the IOException wasn't imported
import java.io.IOException;
Which version of MVC am I using?
I chose System.web.MVC from reference folder and right clicked on it to go property window where I could see version of MVC. This solution works for me. Thanks
Angular ui-grid dynamically calculate height of the grid
I use ui-grid - v3.0.0-rc.20
because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize
module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if
is optional to wait until your data is set before rendering.
_x000D_
_x000D_
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
..._x000D_
_x000D_
$scope.gridData = {_x000D_
rowHeight: 30, // set row height, this is default size_x000D_
..._x000D_
};_x000D_
_x000D_
..._x000D_
_x000D_
$scope.getTableHeight = function() {_x000D_
var rowHeight = 30; // your row height_x000D_
var headerHeight = 30; // your header height_x000D_
return {_x000D_
height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
};_x000D_
};_x000D_
_x000D_
...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
_x000D_
_x000D_
Remove commas from the string using JavaScript
Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format
. This cleans up any bad inputs, if there is one it returns a string of NaN
you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace
.
ParseFloat
converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}
VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323
I recently put all my source on a windows 8 32 box. Had the issues loading mscomctl.ocx
with existing projects.
I created a new project and add the common control (all). save the project and reloaded it no problem.
when you compare the project headers new vs old the old one uses reference=*\blah blah. I found removing this a replacing it with the Object={blah} sorted out the problem.
Delete all rows in table
Truncate table
is faster than delete * from XXX
. Delete
is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.
Move entire line up and down in Vim
In case you want to do this on multiple lines that match a specific search:
- Up:
:g/Your query/ normal ddp
or :g/Your query/ m -1
- Down
:g/Your query/ normal ddp
or :g/Your query/ m +1
Missing visible-** and hidden-** in Bootstrap v4
I do no expect that multiple div's is a good solution.
I also think you can replace .visible-sm-block
with .hidden-xs-down
and .hidden-md-up
(or .hidden-sm-down
and .hidden-lg-up
to act on the same media queries).
hidden-sm-up
compiles into:
.visible-sm-block {
display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
.hidden-sm-down
and .hidden-lg-up
compiles into:
@media (max-width: 768px) {
.hidden-xs-down {
display: none !important;
}
}
@media (min-width: 991px) {
.hidden-lg-up {
display: none !important;
}
}
Both situation should act the same.
You situation become different when you try to replace .visible-sm-block
and .visible-lg-block
. Bootstrap v4 docs tell you:
These classes don’t attempt to accommodate less common cases where an
element’s visibility can’t be expressed as a single contiguous range
of viewport breakpoint sizes; you will instead need to use custom CSS
in such cases.
.visible-sm-and-lg {
display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-and-lg {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-sm-and-lg {
display: block !important;
}
}
How do I share a global variable between c files?
If you want to use global variable i of file1.c in file2.c, then below are the points to remember:
- main function shouldn't be there in file2.c
- now global variable i can be shared with file2.c by two ways:
a) by declaring with extern keyword in file2.c i.e extern int i;
b) by defining the variable i in a header file and including that header file in file2.c.
UIScrollView not scrolling
If none of the other solutions work for you, double check that your scroll view actually is a UIScrollView
in Interface Builder.
At some point in the last few days, my UIScrollView
spontaneously changed type to a UIView
, even though its class said UIScrollView
in the inspector. I'm using Xcode 5.1 (5B130a)
.
You can either create a new scroll view and copy the measurements, settings and constraints from the old view, or you can manually change your view to a UIScrollView
in the xib
file. I did a compare and found the following differences:
Original:
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" directionalLockEnabled="YES" bounces="NO" pagingEnabled="YES" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Wsk-WB-LMH">
...
</scrollView>
After type spontaneously changed:
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" customClass="UIScrollView" id="qRn-TP-cXd">
...
</view>
So I replaced the <view>
line with my original <scrollView>
line.
I also replaced the view's close tag </view>
with </scrollView>
.
Be sure to keep the id the same as the current view, in this case: id="qRn-TP-cXd".
I also had to flush the xib from Xcode's cache by deleting the app's derived data:
Xcode->Window->Organizer->Projects
, choose your project, on the Derived Data line, click Delete...
Or if using a device:
Xcode->Window->Organizer->Device
, choose your device->Applications, choose your app, click (-)
Now clean the project, and remove the app from the simulator/device:
Xcode->Product->Clean
- iOS
Simulator/device->press
and hold the app->click
the (X) to remove it
You should then be able to build and run your app and have scrolling functionality again.
P.S. I didn't have to set the scroll view's content size in viewDidLayoutSubviews
or turn off auto layout, but YMMV.
How to create an empty file with Ansible?
Something like this (using the stat
module first to gather data about it and then filtering using a conditional) should work:
- stat: path=/etc/nologin
register: p
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
when: p.stat.exists is defined and not p.stat.exists
You might alternatively be able to leverage the changed_when
functionality.
converting date time to 24 hour format
I am taking an example of date given below and print two different format of dates according to your requirements.
String date="01/10/2014 05:54:00 PM";
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa",Locale.getDefault());
try {
Log.i("",""+new SimpleDateFormat("ddMMyyyyHHmmss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
Log.i("",""+new SimpleDateFormat("dd/MM/yyyy HH:mm:ss",Locale.getDefault()).format(simpleDateFormat.parse(date)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you still have any query, Please respond. Thanks.
How to turn on line numbers in IDLE?
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is
~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
How to check if X server is running?
1)
# netstat -lp|grep -i x
tcp 0 0 *:x11 *:* LISTEN 2937/X
tcp6 0 0 [::]:x11 [::]:* LISTEN 2937/X
Active UNIX domain sockets (only servers)
unix 2 [ ACC ] STREAM LISTENING 8940 2937/X @/tmp/.X11-unix/X0
unix 2 [ ACC ] STREAM LISTENING 8941 2937/X /tmp/.X11-unix/X0
#
2) nmap
# nmap localhost|grep -i x
6000/tcp open X11
#
Appending pandas dataframes generated in a for loop
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
Formatting text in a TextBlock
You can do this in XAML easily enough:
<TextBlock>
Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>
wget can't download - 404 error
I had the same problem.
Solved using single quotes like this:
$ wget 'http://www.icerts.com/images/logo.jpg'
wget version in use:
$ wget --version
GNU Wget 1.11.4 Red Hat modified
Fastest Convert from Collection to List<T>
managementObjects.Cast<ManagementBaseObject>().ToList();
is a good choice.
You could improve performance by pre-initialising the list capacity:
public static class Helpers
{
public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
{
var output = new List<T>(other.Count);
output.AddRange(other.Cast<T>());
return output;
}
}
Simple C example of doing an HTTP POST and consuming the response
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
Android check internet connection
After "return" statement, you can't write any code(excluding try-finally block).
Move your new activity codes before the "return" statements.
Why does .json() return a promise?
This difference is due to the behavior of Promises more than fetch()
specifically.
When a .then()
callback returns an additional Promise
, the next .then()
callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post
is provided by the Promise returned from response.json()
.
When you return a plain Object
, though, .then()
considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post
in this case is simply the Object
you created, which holds a Promise
in its data
property. The wait for that promise to be fulfilled is still incomplete.
How to use subList()
To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:
dataList.subList(30, 35);
A guaranteed safe way to do this is:
dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );
Setting a PHP $_SESSION['var'] using jQuery
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});
PHP (backend.php):
<?php
// do any authentication first, then add POST variable to session
$_SESSION['imgsrc'] = $_POST['img'];
?>
Object creation on the stack/heap?
Object* o;
o = new Object();
Object* o = new Object();
Both these statement creates the object in the heap memory since you are creating the object using "new".
To be able to make the object creation happen in the stack, you need to follow this:
Object o;
Object *p = &o;
Automating the InvokeRequired code pattern
Lee's approach can be simplified further
public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
// See Update 2 for edits Mike de Klerk suggests to insert here.
if (control.InvokeRequired) {
control.Invoke(action);
} else {
action();
}
}
And can be called like this
richEditControl1.InvokeIfRequired(() =>
{
// Do anything you want with the control here
richEditControl1.RtfText = value;
RtfHelpers.AddMissingStyles(richEditControl1);
});
There is no need to pass the control as parameter to the delegate. C# automatically creates a closure.
UPDATE:
According to several other posters Control
can be generalized as ISynchronizeInvoke
:
public static void InvokeIfRequired(this ISynchronizeInvoke obj,
MethodInvoker action)
{
if (obj.InvokeRequired) {
var args = new object[0];
obj.Invoke(action, args);
} else {
action();
}
}
DonBoitnott pointed out that unlike Control
the ISynchronizeInvoke
interface requires an object array for the Invoke
method as parameter list for the action
.
UPDATE 2
Edits suggested by Mike de Klerk (see comment in 1st code snippet for insert point):
// When the form, thus the control, isn't visible yet, InvokeRequired returns false,
// resulting still in a cross-thread exception.
while (!control.Visible)
{
System.Threading.Thread.Sleep(50);
}
See ToolmakerSteve's comment below for concerns about this suggestion.
How to check if an array is empty?
Your test:
if (numberSet.length < 2) {
return 0;
}
should be done before you allocate an array of that length in the below statement:
int[] differenceArray = new int[numberSet.length-1];
else you are already creating an array of size -1
, when the numberSet.length = 0
. That is quite odd. So, move your if statement
as the first statement in your method.
Android; Check if file exists without creating a new one
The methods
in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file
system to verify that a particular Path exists
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
ImportError: No Module named simplejson
For anyone coming across this years later:
TL;DR check your pip version (2 vs 3)
I had this same issue and it was not fixed by running pip install simplejson
despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.
> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)
Installing with the correct version of pip is as easy as using pip2
:
> pip2 install simplejson
and then python 2 can import simplejson
fine.
Concatenate columns in Apache Spark DataFrame
concat(*cols)
v1.5 and higher
Concatenates multiple input columns together into a single column. The function works with strings, binary and compatible array columns.
Eg: new_df = df.select(concat(df.a, df.b, df.c))
concat_ws(sep, *cols)
v1.5 and higher
Similar to concat
but uses the specified separator.
Eg: new_df = df.select(concat_ws('-', df.col1, df.col2))
map_concat(*cols)
v2.4 and higher
Used to concat maps, returns the union of all the given maps.
Eg: new_df = df.select(map_concat("map1", "map2"))
Using string concat operator (||
):
v2.3 and higher
Eg: df = spark.sql("select col_a || col_b || col_c as abc from table_x")
Reference: Spark sql doc
Hide console window from Process.Start C#
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
Django Cookies, how can I set them?
Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).
Setting a cookie:
def view(request):
response = HttpResponse('blah')
response.set_cookie('cookie_name', 'cookie_value')
Retrieving a cookie:
def view(request):
value = request.COOKIES.get('cookie_name')
if value is None:
# Cookie is not set
# OR
try:
value = request.COOKIES['cookie_name']
except KeyError:
# Cookie is not set
How do you push just a single Git branch (and no other branches)?
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
Why is __dirname not defined in node REPL?
If you got node __dirname not defined
with node --experimental-modules
, you can do :
const __dirname = path.dirname(import.meta.url)
.replace(/^file:\/\/\//, '') // can be usefull
Because othe example, work only with current/pwd directory not other directory.
Python string class like StringBuilder in C#?
Relying on compiler optimizations is fragile. The benchmarks linked in the accepted answer and numbers given by Antoine-tran are not to be trusted. Andrew Hare makes the mistake of including a call to repr
in his methods. That slows all the methods equally but obscures the real penalty in constructing the string.
Use join
. It's very fast and more robust.
$ ipython3
Python 3.5.1 (default, Mar 2 2016, 03:38:02)
IPython 4.1.2 -- An enhanced Interactive Python.
In [1]: values = [str(num) for num in range(int(1e3))]
In [2]: %%timeit
...: ''.join(values)
...:
100000 loops, best of 3: 7.37 µs per loop
In [3]: %%timeit
...: result = ''
...: for value in values:
...: result += value
...:
10000 loops, best of 3: 82.8 µs per loop
In [4]: import io
In [5]: %%timeit
...: writer = io.StringIO()
...: for value in values:
...: writer.write(value)
...: writer.getvalue()
...:
10000 loops, best of 3: 81.8 µs per loop
Functions are not valid as a React child. This may happen if you return a Component instead of from render
You are using it as a regular component, but it's actually a function that returns a component.
Try doing something like this:
const NewComponent = NewHOC(Movie)
And you will use it like this:
<NewComponent someProp="someValue" />
Here is a running example:
_x000D_
_x000D_
const NewHOC = (PassedComponent) => {
return class extends React.Component {
render() {
return (
<div>
<PassedComponent {...this.props} />
</div>
)
}
}
}
const Movie = ({name}) => <div>{name}</div>
const NewComponent = NewHOC(Movie);
function App() {
return (
<div>
<NewComponent name="Kill Bill" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
_x000D_
_x000D_
_x000D_
So basically NewHOC
is just a function that accepts a component and returns a new component that renders the component passed in. We usually use this pattern to enhance components and share logic or data.
You can read about HOCS in the docs and I also recommend reading about the difference between react elements and components
I wrote an article about the different ways and patterns of sharing logic in react.
Using arrays or std::vectors in C++, what's the performance gap?
If you're using vectors to represent multi-dimensional behavior, there is a performance hit.
Do 2d+ vectors cause a performance hit?
The gist is that there's a small amount of overhead with each sub-vector having size information, and there will not necessarily be serialization of data (as there is with multi-dimensional c arrays). This lack of serialization can offer greater than micro optimization opportunities. If you're doing multi-dimensional arrays, it may be best to just extend std::vector and roll your own get/set/resize bits function.
How do I use boolean variables in Perl?
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string 0
is false. Everything else is true.
Therefore, the following values are false:
- The empty string
- Numerical value zero
- An undefined value
- An object with an overloaded boolean operator that evaluates one of the above.
- A magical variable that evaluates to one of the above on fetch.
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
- Without a warning:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
- With a warning:
- Any string for which
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)
Div height 100% and expands to fit content
Ok, I tried something like this:
body (normal)
#MainDiv {
/* where all the content goes */
display: table;
overflow-y: auto;
}
It's not the exact way to write it, but if you make the main div display as a table, it expands and then I implemented scroll bars.