Split string with JavaScript
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
Why is setTimeout(fn, 0) sometimes useful?
In the question, there existed a race condition between:
- The browser's attempt to initialize the drop-down list, ready to have its selected index updated, and
- Your code to set the selected index
Your code was consistently winning this race and attempting to set drop-down selection before the browser was ready, meaning that the bug would appear.
This race existed because JavaScript has a single thread of execution that is shared with page rendering. In effect, running JavaScript blocks the updating of the DOM.
Your workaround was:
setTimeout(callback, 0)
Invoking setTimeout
with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.
The OP's solution, therefore was to delay by about 10ms, the setting of the selected index. This gave the browser an opportunity to initialize the DOM, fixing the bug.
Every version of Internet Explorer exhibited quirky behaviors and this kind of workaround was necessary at times. Alternatively it might have been a genuine bug in the OP's codebase.
See Philip Roberts talk "What the heck is the event loop?" for more thorough explanation.
How to get the current directory in a C program?
Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory()
function:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
These answers apply to both C and C++ code.
Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.
"Bitmap too large to be uploaded into a texture"
Instead of spending hours upon hours trying to write/debug all this downsampling code manually, why not use Picasso
? It was made for dealing with bitmaps
of all types and/or sizes.
I have used this single line of code to remove my "bitmap too large...." problem:
Picasso.load(resourceId).fit().centerCrop().into(imageView);
Load RSA public key from file
Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.
Create a PemFile class that encapsulates file handling:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class PemFile {
private PemObject pemObject;
public PemFile(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
Then instantiate private and public keys as usual:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main {
protected final static Logger LOGGER = Logger.getLogger(Main.class);
public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";
public static void main(String[] args) throws FileNotFoundException,
IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
LOGGER.info("BouncyCastle provider added.");
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
+ "id_rsa");
LOGGER.info(String.format("Instantiated private key: %s", priv));
PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
+ "id_rsa.pub");
LOGGER.info(String.format("Instantiated public key: %s", pub));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
private static PublicKey generatePublicKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return factory.generatePublic(pubKeySpec);
}
}
Hope this helps.
How to set Angular 4 background image?
You can use ngStyle
to set background for a div
<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>
or you can also use built in background style:
<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>
How do I restart a program based on user input?
I create this program:
import pygame, sys, time, random, easygui
skier_images = ["skier_down.png", "skier_right1.png",
"skier_right2.png", "skier_left2.png",
"skier_left1.png"]
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0
def turn(self, direction):
self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed
def move(self,speed):
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self,image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
def scroll(self, t_ptr):
self.rect.centery = self.location[1] - t_ptr
def create_map(start, end):
obstacles = pygame.sprite.Group()
gates = pygame.sprite.Group()
locations = []
for i in range(10):
row = random.randint(start, end)
col = random.randint(0, 9)
location = [col * 64 + 20, row * 64 + 20]
if not (location in locations) :
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles
def animate():
screen.fill([255,255,255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10,10])
pygame.display.flip()
def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0: obstacles.add(ob)
for ob in map1: obstacles.add(ob)
return obstacles
pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)
a = True
while a:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1]
if map_position >= 640 and activeMap == 0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1] - 1280
map_position = map_position - 1280
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0, map1)
for obstacle in obstacles:
obstacle.scroll(map_position)
hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit[0].type == "tree" and not hit[0].passed:
skier.image = pygame.image.load("skier_crash.png")
easygui.msgbox(msg="OOPS!!!")
choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
if choice == "Yes":
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
elif choice == "No":
a = False
quit()
elif hit[0].type == "flag" and not hit[0].passed:
points += 10
obstacles.remove(hit[0])
score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
animate()
Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit
Draw line in UIView
Swift 3 and Swift 4
This is how you can draw a gray line at the end of your view (same idea as b123400's answer)
class CustomView: UIView {
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
How to write a confusion matrix in Python?
Scikit-Learn provides a confusion_matrix
function
from sklearn.metrics import confusion_matrix
y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
confusion_matrix(y_actu, y_pred)
which output a Numpy array
array([[3, 0, 0],
[0, 1, 2],
[2, 1, 3]])
But you can also create a confusion matrix using Pandas:
import pandas as pd
y_actu = pd.Series([2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2], name='Actual')
y_pred = pd.Series([0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2], name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred)
You will get a (nicely labeled) Pandas DataFrame:
Predicted 0 1 2
Actual
0 3 0 0
1 0 1 2
2 2 1 3
If you add margins=True
like
df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)
you will get also sum for each row and column:
Predicted 0 1 2 All
Actual
0 3 0 0 3
1 0 1 2 3
2 2 1 3 6
All 5 2 5 12
You can also get a normalized confusion matrix using:
df_conf_norm = df_confusion / df_confusion.sum(axis=1)
Predicted 0 1 2
Actual
0 1.000000 0.000000 0.000000
1 0.000000 0.333333 0.333333
2 0.666667 0.333333 0.500000
You can plot this confusion_matrix using
import matplotlib.pyplot as plt
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
plt.matshow(df_confusion, cmap=cmap) # imshow
#plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(df_confusion.columns))
plt.xticks(tick_marks, df_confusion.columns, rotation=45)
plt.yticks(tick_marks, df_confusion.index)
#plt.tight_layout()
plt.ylabel(df_confusion.index.name)
plt.xlabel(df_confusion.columns.name)
plot_confusion_matrix(df_confusion)
Or plot normalized confusion matrix using:
plot_confusion_matrix(df_conf_norm)
You might also be interested by this project https://github.com/pandas-ml/pandas-ml and its Pip package https://pypi.python.org/pypi/pandas_ml
With this package confusion matrix can be pretty-printed, plot.
You can binarize a confusion matrix, get class statistics such as TP, TN, FP, FN, ACC, TPR, FPR, FNR, TNR (SPC), LR+, LR-, DOR, PPV, FDR, FOR, NPV and some overall statistics
In [1]: from pandas_ml import ConfusionMatrix
In [2]: y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
In [3]: y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
In [4]: cm = ConfusionMatrix(y_actu, y_pred)
In [5]: cm.print_stats()
Confusion Matrix:
Predicted 0 1 2 __all__
Actual
0 3 0 0 3
1 0 1 2 3
2 2 1 3 6
__all__ 5 2 5 12
Overall Statistics:
Accuracy: 0.583333333333
95% CI: (0.27666968568210581, 0.84834777019156982)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.189264302376
Kappa: 0.354838709677
Mcnemar's Test P-Value: ToDo
Class Statistics:
Classes 0 1 2
Population 12 12 12
P: Condition positive 3 3 6
N: Condition negative 9 9 6
Test outcome positive 5 2 5
Test outcome negative 7 10 7
TP: True Positive 3 1 3
TN: True Negative 7 8 4
FP: False Positive 2 1 2
FN: False Negative 0 2 3
TPR: (Sensitivity, hit rate, recall) 1 0.3333333 0.5
TNR=SPC: (Specificity) 0.7777778 0.8888889 0.6666667
PPV: Pos Pred Value (Precision) 0.6 0.5 0.6
NPV: Neg Pred Value 1 0.8 0.5714286
FPR: False-out 0.2222222 0.1111111 0.3333333
FDR: False Discovery Rate 0.4 0.5 0.4
FNR: Miss Rate 0 0.6666667 0.5
ACC: Accuracy 0.8333333 0.75 0.5833333
F1 score 0.75 0.4 0.5454545
MCC: Matthews correlation coefficient 0.6831301 0.2581989 0.1690309
Informedness 0.7777778 0.2222222 0.1666667
Markedness 0.6 0.3 0.1714286
Prevalence 0.25 0.25 0.5
LR+: Positive likelihood ratio 4.5 3 1.5
LR-: Negative likelihood ratio 0 0.75 0.75
DOR: Diagnostic odds ratio inf 4 2
FOR: False omission rate 0 0.2 0.4285714
I noticed that a new Python library about Confusion Matrix named PyCM is out: maybe you can have a look.
What is SuppressWarnings ("unchecked") in Java?
@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5.
@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element.
For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.
You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.
Read more: https://javarevisited.blogspot.com/2015/09/what-is-suppresswarnings-annotation-in-java-unchecked-raw-serial.html#ixzz5rqQaOLUa
How to transform numpy.matrix or array to scipy sparse matrix
In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse
The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:
- Block Sparse Row matrix
- A sparse matrix in COOrdinate format.
- Compressed Sparse Column matrix
- Compressed Sparse Row matrix
- Sparse matrix with DIAgonal storage
- Dictionary Of Keys based sparse matrix.
- Row-based list of lists sparse matrix
- This class provides a base class for all sparse matrices.
CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.
Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:
import sys # Return the size of an object in bytes
import numpy as np # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix
create a 2-D Numpy matrix
A = np.array([[1, 0, 0, 0, 0, 0],\
[0, 0, 2, 0, 0, 1],\
[0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))
Print the matrix & other details:
Dense matrix representation:
[[1 0 0 0 0 0]
[0 0 2 0 0 1]
[0 0 0 2 0 0]]
Memory utilised (bytes): 184
Type of the object <class 'numpy.ndarray'>
Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:
S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>
Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:
S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>
As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.
For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/
How to stick a footer to bottom in css?
I think a lot of folks are looking for a footer on the bottom that scrolls instead of being fixed, called a sticky footer. Fixed footers will cover body content when the height is too short. You have to set the html, body, and page container to a height of 100%, set your footer to absolute position bottom. Your page content container needs a relative position for this to work. Your footer has a negative margin equal to height of footer minus bottom margin of page content. See the example page I posted.
Example with notes: http://markbokil.com/code/bottomfooter/
Creating files and directories via Python
import os
os.mkdir('directory name') #### this command for creating directory
os.mknod('file name') #### this for creating files
os.system('touch filename') ###this is another method for creating file by using unix commands in os modules
Is it possible to do a sparse checkout without checking out the whole repository first?
I found the answer I was looking for from the one-liner posted earlier by pavek (thanks!) so I wanted to provide a complete answer in a single reply that works on Linux (GIT 1.7.1):
1--> mkdir myrepo
2--> cd myrepo
3--> git init
4--> git config core.sparseCheckout true
5--> echo 'path/to/subdir/' > .git/info/sparse-checkout
6--> git remote add -f origin ssh://...
7--> git pull origin master
I changed the order of the commands a bit but that does not seem to have any impact. The key is the presence of the trailing slash "/" at the end of the path in step 5.
How can one grab a stack trace in C?
For Windows, CaptureStackBackTrace()
is also an option, which requires less preparation code on the user's end than StackWalk64()
does. (Also, for a similar scenario I had, CaptureStackBackTrace()
ended up working better (more reliably) than StackWalk64()
.)
Enter export password to generate a P12 certificate
OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.
You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword
to pass the password YourPassword
from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.
error: passing xxx as 'this' argument of xxx discards qualifiers
Let's me give a more detail example. As to the below struct:
struct Count{
uint32_t c;
Count(uint32_t i=0):c(i){}
uint32_t getCount(){
return c;
}
uint32_t add(const Count& count){
uint32_t total = c + count.getCount();
return total;
}
};
As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object
. In the method add
count
is declared as const object, but the method getCount
is not const method, so count.getCount()
may change the members in count
.
Compile error as below(core message in my compiler):
error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]
To solve the above problem, you can:
- change the method
uint32_t getCount(){...}
to uint32_t getCount() const {...}
. So count.getCount()
won't change the members in count
.
or
- change
uint32_t add(const Count& count){...}
to uint32_t add(Count& count){...}
. So count
don't care about changing members in it.
As to you problem, objects in the std::set are stored as const StudentT, but the method getId
and getName
are not const, so you give the above error.
You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.
How do I get the current username in Windows PowerShell?
In my case, I needed to retrieve the username to enable the script to change the path, ie. c:\users\%username%\
. I needed to start the script by changing the path to the users desktop. I was able to do this, with help from above and elsewhere, by using the get-location applet.
You may have another, or even better way to do it, but this worked for me:
$Path = Get-Location
Set-Location $Path\Desktop
How to make an element in XML schema optional?
Set the minOccurs
attribute to 0
in the schema like so:
<?xml version="1.0"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="request">
<xs:complexType>
<xs:sequence>
<xs:element name="amenity">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element> </xs:schema>
WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?
In addition to the main answer: if you have more than one service on the same server that uses websockets, you might want to do this to separate them, by using a custom path (*):
Node server:
var io = require('socket.io')({ path: '/ws_website1'}).listen(server);
Client HTML:
<script src="/ws_website1/socket.io.js"></script>
...
<script>
var socket = io('', { path: '/ws_website1' });
...
Apache config:
RewriteEngine On
RewriteRule ^/website1(.*)$ http://localhost:3001$1 [P,L]
RewriteCond %{REQUEST_URI} ^/ws_website1 [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule ^(.*)$ ws://localhost:3001$1 [P,L]
RewriteCond %{REQUEST_URI} ^/ws_website1 [NC]
RewriteRule ^(.*)$ http://localhost:3001$1 [P,L]
(*) Note: using the default RewriteCond %{REQUEST_URI} ^/socket.io
would not be specific to a website, and websockets requests would be mixed up between different websites!
AppStore - App status is ready for sale, but not in app store
I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.
For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.
The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.
After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.
Then, I unchecked the countries the App is available on and checked them all again and hit Save.
The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.
I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).
Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
Expired certificate was the cause of our "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated".
keytool -list -v -keystore filetruststore.ts
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: somealias
Creation date: Jul 26, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Unknown, OU=SomeOU, O="Some Company, Inc.", L=SomeCity, ST=GA, C=US
Issuer: CN=Unknown, OU=SomeOU, O=Some Company, Inc.", L=SomeCity, ST=GA, C=US
Serial number: 5011a47b
Valid from: Thu Jul 26 16:11:39 EDT 2012 until: Wed Oct 24 16:11:39 EDT 2012
html form - make inputs appear on the same line
Try just putting a div around the first and last name inputs/labels like this:
<div class="name">
<label for="First_Name">First Name:</label>
<input name="first_name" id="First_Name" type="text" />
<label for="Name">Last Name:</label>
<input name="last_name" id="Last_Name" type="text" />
</div>
Look at the fiddle here: http://jsfiddle.net/XAkXg/
Text editor to open big (giant, huge, large) text files
Tips and tricks
less
Why are you using editors to just look at a (large) file?
Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.
There is a Win32 port of GNU less. See the "less" section of the answer above.
Perl
Perl is good for quick scripts, and its ..
(range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.
For example:
$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less
This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.
Another example:
$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less
This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...
logparser
This is another useful tool you can use. To quote the Wikipedia article:
logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.
Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.
Example usage:
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"
The relativity of sizes
100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.
And more...
Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...
postgresql: INSERT INTO ... (SELECT * ...)
As Henrik wrote you can use dblink to connect remote database and fetch result. For example:
psql dbtest
CREATE TABLE tblB (id serial, time integer);
INSERT INTO tblB (time) VALUES (5000), (2000);
psql postgres
CREATE TABLE tblA (id serial, time integer);
INSERT INTO tblA
SELECT id, time
FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
AS t(id integer, time integer)
WHERE time > 1000;
TABLE tblA;
id | time
----+------
1 | 5000
2 | 2000
(2 rows)
PostgreSQL has record pseudo-type (only for function's argument or result type), which allows you query data from another (unknown) table.
Edit:
You can make it as prepared statement if you want and it works as well:
PREPARE migrate_data (integer) AS
INSERT INTO tblA
SELECT id, time
FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
AS t(id integer, time integer)
WHERE time > $1;
EXECUTE migrate_data(1000);
-- DEALLOCATE migrate_data;
Edit (yeah, another):
I just saw your revised question (closed as duplicate, or just very similar to this).
If my understanding is correct (postgres has tbla and dbtest has tblb and you want remote insert with local select, not remote select with local insert as above):
psql dbtest
SELECT dblink_exec
(
'dbname=postgres',
'INSERT INTO tbla
SELECT id, time
FROM dblink
(
''dbname=dbtest'',
''SELECT id, time FROM tblb''
)
AS t(id integer, time integer)
WHERE time > 1000;'
);
I don't like that nested dblink, but AFAIK I can't reference to tblB in dblink_exec body. Use LIMIT to specify top 20 rows, but I think you need to sort them using ORDER BY clause first.
How to round up value C# to the nearest integer?
The .NET framework uses banker's rounding in Math.Round
by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0
Combine several images horizontally with Python
Based on DTing's answer I created a function that is easier to use:
from PIL import Image
def append_images(images, direction='horizontal',
bg_color=(255,255,255), aligment='center'):
"""
Appends images in horizontal/vertical direction.
Args:
images: List of PIL images
direction: direction of concatenation, 'horizontal' or 'vertical'
bg_color: Background color (default: white)
aligment: alignment mode if images need padding;
'left', 'right', 'top', 'bottom', or 'center'
Returns:
Concatenated image as a new PIL image object.
"""
widths, heights = zip(*(i.size for i in images))
if direction=='horizontal':
new_width = sum(widths)
new_height = max(heights)
else:
new_width = max(widths)
new_height = sum(heights)
new_im = Image.new('RGB', (new_width, new_height), color=bg_color)
offset = 0
for im in images:
if direction=='horizontal':
y = 0
if aligment == 'center':
y = int((new_height - im.size[1])/2)
elif aligment == 'bottom':
y = new_height - im.size[1]
new_im.paste(im, (offset, y))
offset += im.size[0]
else:
x = 0
if aligment == 'center':
x = int((new_width - im.size[0])/2)
elif aligment == 'right':
x = new_width - im.size[0]
new_im.paste(im, (x, offset))
offset += im.size[1]
return new_im
It allows choosing a background color and image alignment. It's also easy to do recursion:
images = map(Image.open, ['hummingbird.jpg', 'tiger.jpg', 'monarch.png'])
combo_1 = append_images(images, direction='horizontal')
combo_2 = append_images(images, direction='horizontal', aligment='top',
bg_color=(220, 140, 60))
combo_3 = append_images([combo_1, combo_2], direction='vertical')
combo_3.save('combo_3.png')
Rails 4 Authenticity Token
I think I just figured it out. I changed the (new) default
protect_from_forgery with: :exception
to
protect_from_forgery with: :null_session
as per the comment in ApplicationController
.
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
You can see the difference by looking at the source for request_forgery_protecton.rb
, or, more specifically, the following lines:
In Rails 3.2:
# This is the method that defines the application behavior when a request is found to be unverified.
# By default, \Rails resets the session when it finds an unverified request.
def handle_unverified_request
reset_session
end
In Rails 4:
def handle_unverified_request
forgery_protection_strategy.new(self).handle_unverified_request
end
Which will call the following:
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
Javascript reduce() on Object
If handled as an array is much easier
Return the total amount of fruits:
let fruits = [{ name: 'banana', id: 0, quantity: 9 }, { name: 'strawberry', id: 1, quantity: 1 }, { name: 'kiwi', id: 2, quantity: 2 }, { name: 'apple', id: 3, quantity: 4 }]
let total = fruits.reduce((sum, f) => sum + f.quantity, 0);
Injecting $scope into an angular service function()
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
batch script - read line by line
This has worked for me in the past and it will even expand environment variables in the file if it can.
for /F "delims=" %%a in (LogName.txt) do (
echo %%a>>MyDestination.txt
)
How add class='active' to html menu with php
A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>
Which will output
<ul>
<li class="current"><a href="index.php">Home</a></li>
<li class=""><a href="portfolio.php">Portfolio</a></li>
<li class=""><a href="services.php">Services</a></li>
<li class=""><a href="contact.php">Contact</a></li>
<li class=""><a href="links.php">Links</a></li>
</ul>
PowerShell - Start-Process and Cmdline Switches
Unless the OP is using PowerShell Community Extensions which does provide a Start-Process cmdlet along with a bunch of others. If this the case then Glennular's solution works a treat since it matches the positional parameters of pscx\start-process : -path (position 1) -arguments (positon 2).
Heap space out of memory
There are a variety of tools that you can use to help diagnose this problem. The JDK includes JVisualVM that will allow you to attach to your running process and show what objects might be growing out of control. Netbeans has a wrapper around it that works fairly well. Eclipse has the Eclipse Memory Analyzer which is the one I use most often, just seems to handle large dump files a bit better. There's also a command line option, -XX:+HeapDumpOnOutOfMemoryError that will give you a file that is basically a snapshot of your process memory when your program crashed. You can use any of the above mentioned tools to look at it, it can really help a lot when diagnosing these sort of problems.
Depending on how hard the program is working, it may be a simple case of the JVM not knowing when a good time to garbage collect may be, you might also look into the parallel garbage collection options as well.
Python - List of unique dictionaries
I don't know if you only want the id of your dicts in the list to be unique, but if the goal is to have a set of dict where the unicity is on all keys' values.. you should use tuples key like this in your comprehension :
>>> L=[
... {'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30},
... {'id':2,'name':'hanna', 'age':50}
... ]
>>> len(L)
4
>>> L=list({(v['id'], v['age'], v['name']):v for v in L}.values())
>>>L
[{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}, {'id': 2, 'name': 'hanna', 'age': 50}]
>>>len(L)
3
Hope it helps you or another person having the concern....
How to obtain the start time and end time of a day?
in getEndOfDay, you can add:
calendar.set(Calendar.MILLISECOND, 999);
Although mathematically speaking, you can't specify the end of a day other than by saying it's "before the beginning of the next day".
So instead of saying, if(date >= getStartOfDay(today) && date <= getEndOfDay(today))
, you should say: if(date >= getStartOfDay(today) && date < getStartOfDay(tomorrow))
. That is a much more solid definition (and you don't have to worry about millisecond precision).
When saving, how can you check if a field has changed?
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction
block and select_for_update()
@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.select_for_update().get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not obj.some_field == instance.some_field: # Field has changed
# do something
JavaScript query string
// How about this
function queryString(qs) {
var queryStr = qs.substr(1).split("&"),obj={};
for(var i=0; i < queryStr.length;i++)
obj[queryStr[i].split("=")[0]] = queryStr[i].split("=")[1];
return obj;
}
// Usage:
var result = queryString(location.search);
Delete commits from a branch in Git
The mistake:
I git rebase -i --root
'ed my branch, ignorantly thinking I could reword the first commit differing from the master (the GitHub for Windows default view is the comparison to master, hiding it's entirety).
I grew a Silicon Valley beard while 900+ commits loaded themselves into Sublime. Exiting with no changes, I charged my battery then proceeded to shave, as all 900+ individual commits nonchalantly rebased - resetting their commit times to now.
Determined to beat Git and preserve the original times, I deleted this local repository and re-cloned from the remote.
Now it had re-added a most recent unneeded commit to master I wished to remove, so proceeded like so.
Exhausting the options:
I didn't wish to git revert
- it would create an additional commit, giving Git the upper hand.
git reset --hard HEAD
did nothing, after checking the reflog
, the last and only HEAD
was the clone - Git wins.
To get the most recent SHA, I checked the remote repository on github.com - minor win.
After thinking git reset --hard <SHA>
had worked, I updated another branch to master and 1... 2... poof! the commit was back - Git wins.
Checking back out to master, time to try git rebase -i <SHA>
, then remove the line... to no avail, sad to say. "If you remove a line here THAT COMMIT WILL BE LOST". Ah...glossed over new feature troll the n00b in the 2.8.3 release notes.
The solution:
git rebase -i <SHA>
then d, drop = remove commit
.
To verify, I checked out to another branch, and voila - no hiding commit to fetch/pull from the master.
https://twitter.com/holman/status/706006896273063936
Good day to you.
How to get a thread and heap dump of a Java process on Windows that's not running in a console
Below java code is used to get the Heap Dump of a Java Process by providing PID. The Program uses Remote JMX connection to dump heap. It may be helpful for some one.
import java.lang.management.ManagementFactory;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.reflect.Method;
public class HeapDumper {
public static final String HOST = "192.168.11.177";
public static final String PORT = "1600";
public static final String FILE_NAME = "heapDump.hprof";
public static final String FOLDER_PATH = "C:/";
private static final String HOTSPOT_BEAN_NAME ="com.sun.management:type=HotSpotDiagnostic";
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("Enter PID of the Java Process !!!");
return;
}
String pidString = args[0];
int pid = -1;
if(pidString!=null && pidString.length() > 0) {
try {
pid = Integer.parseInt(pidString);
}
catch(Exception e) {
System.out.println("PID is not Valid !!!");
return;
}
}
boolean isHeapDumpSuccess = false;
boolean live = true;
if(pid > 0) {
MBeanServerConnection beanServerConn = getJMXConnection();
if(beanServerConn!=null) {
Class clazz = null;
String dumpFile = FOLDER_PATH+"/"+FILE_NAME;
try{
clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
Object hotspotMBean = ManagementFactory.newPlatformMXBeanProxy(beanServerConn, HOTSPOT_BEAN_NAME, clazz);
Method method = clazz.getMethod("dumpHeap", new Class[]{String.class , boolean.class});
method.setAccessible(true);
method.invoke(hotspotMBean , new Object[] {dumpFile, new Boolean(live)});
isHeapDumpSuccess = true;
}
catch(Exception e){
e.printStackTrace();
isHeapDumpSuccess = false;
}
finally{
clazz = null;
}
}
}
if(isHeapDumpSuccess){
System.out.println("HeapDump is Success !!!");
}
else{
System.out.println("HeapDump is not Success !!!");
}
}
private static MBeanServerConnection getJMXConnection() {
MBeanServerConnection mbeanServerConnection = null;
String urlString = "service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi";
try {
JMXServiceURL url = new JMXServiceURL(urlString);
JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
mbeanServerConnection = jmxConnector.getMBeanServerConnection();
System.out.println("JMX Connection is Success for the URL :"+urlString);
}
catch(Exception e) {
System.out.println("JMX Connection Failed !!!");
}
return mbeanServerConnection;
}
}
How can I invert color using CSS?
Add the same color of the background to the paragraph and then invert with CSS:
_x000D_
_x000D_
div {_x000D_
background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
color: #f00;_x000D_
-webkit-filter: invert(100%);_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
<p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Windows batch: echo without new line
Late answer here, but for anyone who needs to write special characters to a single line who find dbenham's answer to be about 80 lines too long and whose scripts may break (perhaps due to user-input) under the limitations of simply using set /p
, it's probably easiest to just to pair your .bat or .cmd with a compiled C++ or C-language executable and then just cout
or printf
the characters. This will also allow you to easily write multiple times to one line if you're showing a sort of progress bar or something using characters, as OP apparently was.
Select first occurring element after another element
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Change link color of the current page with CSS
JavaScript will get the job done.
Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.
JavaScript
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forE??ach(function(link) {
link.className += ' current-link')
});
</script>
One Liner Version of Above
document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});
CSS
.current-link {
color:#baada7;
}
Other Notes
Taraman's jQuery answer above only searches on [href]
which will return link
tags and tags other than a
which rely on the href
attribute. Searching on a[href='*https://urlofcurrentpage.com*']
captures only those links which meets the criteria and therefore runs faster.
In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.
NSRange to Range<String.Index>
extension StringProtocol where Index == String.Index {
func nsRange(of string: String) -> NSRange? {
guard let range = self.range(of: string) else { return nil }
return NSRange(range, in: self)
}
}
how to read all files inside particular folder
Try this It is working for me..
The syntax is GetFiles(string path, string searchPattern);
var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");
This code will return all the files inside App_Data
folder.
The second parameter . indicates the searchPattern with File Extension where the first *
is for file name and second is for format of the file or File Extension like (*.png -
any file name with .png format.
How to print React component on click of a button?
Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.
Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:
https://stackoverflow.com/a/30137174/3123109
This is what the component ended up looking like. It prints everything in the body of the modal.
import React, { Component } from 'react';
import {
Button,
Modal,
ModalBody,
ModalHeader
} from 'reactstrap';
export default class TestPrint extends Component{
constructor(props) {
super(props);
this.state = {
modal: false,
data: [
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test'
]
}
this.toggle = this.toggle.bind(this);
this.print = this.print.bind(this);
}
print() {
var content = document.getElementById('printarea');
var pri = document.getElementById('ifmcontentstoprint').contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
}
renderContent() {
var i = 0;
return this.state.data.map((d) => {
return (<p key={d + i++}>{i} - {d}</p>)
});
}
toggle() {
this.setState({
modal: !this.state.modal
})
}
render() {
return (
<div>
<Button
style={
{
'position': 'fixed',
'top': '50%',
'left': '50%',
'transform': 'translate(-50%, -50%)'
}
}
onClick={this.toggle}
>
Test Modal and Print
</Button>
<Modal
size='lg'
isOpen={this.state.modal}
toggle={this.toggle}
className='results-modal'
>
<ModalHeader toggle={this.toggle}>
Test Printing
</ModalHeader>
<iframe id="ifmcontentstoprint" style={{
height: '0px',
width: '0px',
position: 'absolute'
}}></iframe>
<Button onClick={this.print}>Print</Button>
<ModalBody id='printarea'>
{this.renderContent()}
</ModalBody>
</Modal>
</div>
)
}
}
Note: However, I am having difficulty getting styles to be reflected in the iframe
.
How to import a JSON file in ECMAScript 6?
Depending on your build tooling and the data structure within the JSON file, it may require importing the default
.
import { default as config } from '../config.json';
e.g. usage within Next.js
How to run jenkins as a different user
ISSUE 1:
Started by user anonymous
That does not mean that Jenkins started as an anonymous user.
It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the
"Started by anonymous"
will change to
"Started by < username >".
Note: You do not have to enable security in order to run jenkins or to clone correctly.
If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System
.
ISSUE 2:
The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.
Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.
Hope that helps.
Angular : Manual redirect to route
Angular routing : Manual navigation
First you need to import the angular router :
import {Router} from "@angular/router"
Then inject it in your component constructor :
constructor(private router: Router) { }
And finally call the .navigate
method anywhere you need to "redirect" :
this.router.navigate(['/your-path'])
You can also put some parameters on your route, like user/5
:
this.router.navigate(['/user', 5])
Documentation: Angular official documentaiton
How to change XML Attribute
If the attribute you want to change doesn't exist or has been accidentally removed, then an exception occurs. I suggest you first create a new attribute and send it to a function like the following:
private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList)
{
foreach (var attr in attrList)
{
if (node.Attributes[attr.Name] != null)
{
node.Attributes[attr.Name].Value = attr.Value;
}
else
{
node.Attributes.Append(attr);
}
}
}
Usage:
XmlAttribute attr = dom.CreateAttribute("name");
attr.Value = value;
SetAttrSafe(node, attr);
How to modify values of JsonObject / JsonArray directly?
This works for modifying childkey value using JSONObject
.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
How to count total lines changed by a specific author in a Git repository?
This script here will do it. Put it into authorship.sh, chmod +x it, and you're all set.
#!/bin/sh
declare -A map
while read line; do
if grep "^[a-zA-Z]" <<< "$line" > /dev/null; then
current="$line"
if [ -z "${map[$current]}" ]; then
map[$current]=0
fi
elif grep "^[0-9]" <<<"$line" >/dev/null; then
for i in $(cut -f 1,2 <<< "$line"); do
map[$current]=$((map[$current] + $i))
done
fi
done <<< "$(git log --numstat --pretty="%aN")"
for i in "${!map[@]}"; do
echo -e "$i:${map[$i]}"
done | sort -nr -t ":" -k 2 | column -t -s ":"
"Large data" workflows using pandas
I'd like to point out the Vaex package.
Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
Have a look at the documentation: https://vaex.readthedocs.io/en/latest/
The API is very close to the API of pandas.
How to increment an iterator by 2?
We can use both std::advance as well as std::next, but there's a difference between the two.
advance
modifies its argument and returns nothing. So it can be used as:
vector<int> v;
v.push_back(1);
v.push_back(2);
auto itr = v.begin();
advance(itr, 1); //modifies the itr
cout << *itr<<endl //prints 2
next
returns a modified copy of the iterator:
vector<int> v;
v.push_back(1);
v.push_back(2);
cout << *next(v.begin(), 1) << endl; //prints 2
Get a particular cell value from HTML table using JavaScript
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
Set LIMIT with doctrine 2?
I use Doctrine\ORM\Tools\Pagination\Paginator
for this, and it works perfectly (doctrine 2.2).
$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
->setFirstResult(0)
->setMaxResults(10);
$paginator = new Paginator($query, $fetchJoinCollection = true);
Cannot send a content-body with this verb-type
Because you didn't specify the Header.
I've added an extended example:
var request = (HttpWebRequest)WebRequest.Create(strServer + strURL.Split('&')[1].ToString());
Header(ref request, p_Method);
And the method Header:
private void Header(ref HttpWebRequest p_request, string p_Method)
{
p_request.ContentType = "application/x-www-form-urlencoded";
p_request.Method = p_Method;
p_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE)";
p_request.Host = strServer.Split('/')[2].ToString();
p_request.Accept = "*/*";
if (String.IsNullOrEmpty(strURLReferer))
{
p_request.Referer = strServer;
}
else
{
p_request.Referer = strURLReferer;
}
p_request.Headers.Add("Accept-Language", "en-us\r\n");
p_request.Headers.Add("UA-CPU", "x86 \r\n");
p_request.Headers.Add("Cache-Control", "no-cache\r\n");
p_request.KeepAlive = true;
}
Add the loading screen in starting of the android application
Write the code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
@Override
public void run() {
try {
super.run();
sleep(10000) //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
"Call to undefined function mysql_connect()" after upgrade to php-7
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
How to get terminal's Character Encoding
To see the current locale information use locale
command. Below is an example on RHEL 7.8
[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
Why use 'git rm' to remove a file instead of 'rm'?
Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory.
Here's how you might delete a file using rm -f
and then remove it from your index with git rm
$ rm -f index.html
$ git status -s
D index.html
$ git rm index.html
rm 'index.html'
$ git status -s
D index.html
However you can do this all in one go with just git rm
$ git status -s
$ git rm index.html
rm 'index.html'
$ ls
lib vendor
$ git status -s
D index.html
Cannot make a static reference to the non-static method fxn(int) from the type Two
A static method can NOT access a Non-static method or variable.
public static void main(String[] args)
is a static method, so can NOT access the Non-static public static int fxn(int y)
method.
Try it this way...
static int fxn(int y)
public class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
static int fxn(int y) {
y = 5;
return y;
}
}
How to load property file from classpath?
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
Can I pass column name as input parameter in SQL stored Procedure
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET @sql = 'SELECT ' + @columnName + ' FROM yourTable'
sp_executesql @sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE @columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
raw_input function in Python
If I let raw_input like that, no Josh or anything else.
It's a variable,I think,but I don't understand her roll :-(
The raw_input function prompts you for input and
returns that as a string. This certainly worked for
me. You don't need idle. Just open a "DOS prompt"
and run the program.
This is what it looked like for me:
C:\temp>type test.py
print "Halt!"
s = raw_input("Who Goes there? ")
print "You may pass,", s
C:\temp>python test.py
Halt!
Who Goes there? Magnus
You may pass, Magnus
I types my name and pressed [Enter
] after the program
had printed "Who Goes there?"
Create a custom View by inflating a layout?
Here is a simple demo to create customview (compoundview) by inflating from xml
attrs.xml
<resources>
<declare-styleable name="CustomView">
<attr format="string" name="text"/>
<attr format="reference" name="image"/>
</declare-styleable>
</resources>
CustomView.kt
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
init {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
View.inflate(context, R.layout.custom_layout, this)
val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
try {
val text = ta.getString(R.styleable.CustomView_text)
val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
if (drawableId != 0) {
val drawable = AppCompatResources.getDrawable(context, drawableId)
image_thumb.setImageDrawable(drawable)
}
text_title.text = text
} finally {
ta.recycle()
}
}
}
custom_layout.xml
We should use merge
here instead of ConstraintLayout
because
If we use ConstraintLayout
here, layout hierarchy will be ConstraintLayout
->ConstraintLayout
-> ImageView
+ TextView
=> we have 1 redundant ConstraintLayout
=> not very good for performance
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="android.support.constraint.ConstraintLayout">
<ImageView
android:id="@+id/image_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="@id/image_thumb"
app:layout_constraintStart_toStartOf="@id/image_thumb"
app:layout_constraintTop_toBottomOf="@id/image_thumb"
tools:text="Text" />
</merge>
Using
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00"
app:image="@drawable/ic_android"
app:text="Android" />
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0f0"
app:image="@drawable/ic_adb"
app:text="ADB" />
</LinearLayout>
Result
Github demo
Adding and reading from a Config file
Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config
(or web.config
) file to your project.
The ConfigurationManager
class would be a good start. You can use it to read different configuration values from the configuration file.
I suggest you start reading the MSDN document about Configuration Files.
javascript window.location in new tab
with jQuery its even easier and works on Chrome as well
$('#your-button').on('click', function(){
$('<a href="https://www.some-page.com" target="blank"></a>')[0].click();
})
what is the difference between XSD and WSDL
XSD : XML Schema Definition.
XML : eXtensible Markup Language.
WSDL : Web Service Definition Language.
I am not going to answer in technical terms. I am aiming this explanation at beginners.
It is not easy to communicate between two different applications that are developed using two different technologies. For example, a company in Chicago might develop a web application using Java and another company in New York might develop an application in C# and when these two companies decided to share information then XML comes into picture. It helps to store and transport data between two different applications that are developed using different technologies. Note: It is not limited to a programming language, please do research on the information transportation between two different apps.
XSD is a schema definition. By that what I mean is, it is telling users to develop their XML in such a schema. Please see below images, and please watch closely with "load-on-startup" element and its type which is integer. In the XSD image you can see it is meant to be integer value for the "load-on-startup" and hence when user created his/her XML they passed an int value to that particular element. As a reminder, XSD is a schema and style whereas XML is a form to communicate with another application or system. One has to see XSD and create XML in such a way or else it won't communicate with another application or system which has been developed with a different technology. A company in Chicago provides a XSD template for a company in Texas to write or generate their XML in the given XSD format. If the company in Texas failed to adhere with those rules or schema mentioned in XSD then it is impossible to expect correct information from the company in Chicago. There is so much to do after the above said story, which an amateur or newbie have to know while coding for some thing like I said above. If you really want to know what happens later then it is better to sit with senior software engineers who actually developed web services. Next comes WSDL, please follow the images and try to figure out where the WSDL will fit in.
***************========Below is partial XML image ==========***************
***************========Below is partial XSD image ==========***************
***************========Below is the partial WSDL image =======*************
I had to create a sample WSDL for a web service called Book. Note, it is an XSD but you have to call it WSDL (Web Service Definition Language) because it is very specific for Web Services. The above WSDL (or in other words XSD) is created for a class called Book.java and it has created a SOAP service. How the SOAP web service created it is a different topic. One has to write a Java class and before executing it create as a web service the user has to make sure Axis2 API is installed and Tomcat to host web service is in place.
As a servicer (the one who allows others (clients) to access information or data from their systems ) actually gives the client (the one who needs to use servicer information or data) complete access to data through a Web Service, because no company on the earth willing to expose their Database for outsiders. Like my company, decided to give some information about products via Web Services, hence we had to create XSD template and pass-on to few of our clients who wants to work with us. They have to write some code to make complete use of the given XSD and make Web Service calls to fetch data from servicer and convert data returned into their suitable requirement and then display or publish data or information about the product on their website. A simple example would be FLIGHT Ticket booking. An airline will let third parties to use flight data on their site for ticket sales. But again there is much more to it, it is just not letting third party flight ticket agent to sell tickets, there will be synchronize and security in place. If there is no sync then there is 100 % chances more than 1 customer might buy same flight ticket from various sources.
I am hoping experts will contribute to my answer. It is really hard for newbie or novice to understand XML, XSD and then to work on Web Services.
force line break in html table cell
It's hard to answer you without the HTML, but in general you can put:
style="width: 50%;"
On either the table cell, or place a div inside the table cell, and put the style on that.
But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.
Post a copy of your HTML and maybe you'll get a better answer.
How To: Execute command line in C#, get STD OUT results
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
System.IO.StreamReader myOutput = proc.StandardOutput;
proc.WaitForExit(2000);
if (proc.HasExited)
{
string output = myOutput.ReadToEnd();
}
sorting a List of Map<String, String>
Not really an answer to your question but I had a requirement to sort a List of maps by its values' properties, this will work in your case too:
List<Map<String, Object>> sortedListOfMaps = someListOfMaps.sorted(Comparator.comparing(map -> ((String) map.get("someKey")))).collect(Collectors.toList()))
Execute php file from another php
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
How do I dump the data of some SQLite3 tables?
You're not saying what you wish to do with the dumped file.
I would use the following to get a CSV file, which I can import into almost everything
.mode csv
-- use '.separator SOME_STRING' for something other than a comma.
.headers on
.out file.csv
select * from MyTable;
If you want to reinsert into a different SQLite database then:
.mode insert <target_table_name>
.out file.sql
select * from MyTable;
Get Value of Row in Datatable c#
for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){
double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT;
}
if you want to get around the + 1 issue
Modify tick label text
It's been a while since this question was asked. As of today (matplotlib 2.2.2
) and after some reading and trials, I think the best/proper way is the following:
Matplotlib has a module named ticker
that "contains classes to support completely configurable tick locating and formatting". To modify a specific tick from the plot, the following works for me:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
def update_ticks(x, pos):
if x == 0:
return 'Mean'
elif pos == 6:
return 'pos is 6'
else:
return x
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()
Caveat! x
is the value of the tick and pos
is its relative position in order in the axis. Notice that pos
takes values starting in 1
, not in 0
as usual when indexing.
In my case, I was trying to format the y-axis
of a histogram with percentage values. mticker
has another class named PercentFormatter
that can do this easily without the need to define a separate function as before:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()
In this case xmax
is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100
, that's why we fix xmax=1.0
. Also, decimals
is the number of decimal places to place after the point.
How do I create an abstract base class in JavaScript?
Is it possible to simulate abstract base class in JavaScript?
Certainly. There are about a thousand ways to implement class/instance systems in JavaScript. Here is one:
// Classes magic. Define a new class with var C= Object.subclass(isabstract),
// add class members to C.prototype,
// provide optional C.prototype._init() method to initialise from constructor args,
// call base class methods using Base.prototype.call(this, ...).
//
Function.prototype.subclass= function(isabstract) {
if (isabstract) {
var c= new Function(
'if (arguments[0]!==Function.prototype.subclass.FLAG) throw(\'Abstract class may not be constructed\'); '
);
} else {
var c= new Function(
'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
);
}
if (this!==Object)
c.prototype= new this(Function.prototype.subclass.FLAG);
return c;
}
Function.prototype.subclass.FLAG= new Object();
var cat = new Animal('cat');
That's not really an abstract base class of course. Do you mean something like:
var Animal= Object.subclass(true); // is abstract
Animal.prototype.say= function() {
window.alert(this._noise);
};
// concrete classes
var Cat= Animal.subclass();
Cat.prototype._noise= 'meow';
var Dog= Animal.subclass();
Dog.prototype._noise= 'bark';
// usage
var mycat= new Cat();
mycat.say(); // meow!
var mygiraffe= new Animal(); // error!
What does localhost:8080 mean?
Option 1
localhost/web is equal to localhost:80/web OR to 127.0.0.1:80/web
Option 2
localhost:8080/web is equal to localhost:8080/web OR to 127.0.0.1:8080/web
Open a Web Page in a Windows Batch FIle
Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,
start "iexplore.exe" http://www.website.com
What is the difference between an abstract function and a virtual function?
Here I am writing some sample code hoping this may be a rather tangible example to see the behaviors of the interfaces, abstract classes and ordinary classes on a very basic level. You can also find this code in github as a project if you want to use it as a demo: https://github.com/usavas/JavaAbstractAndInterfaceDemo
public interface ExampleInterface {
// public void MethodBodyInInterfaceNotPossible(){
// }
void MethodInInterface();
}
public abstract class AbstractClass {
public abstract void AbstractMethod();
// public abstract void AbstractMethodWithBodyNotPossible(){
//
// };
//Standard Method CAN be declared in AbstractClass
public void StandardMethod(){
System.out.println("Standard Method in AbstractClass (super) runs");
}
}
public class ConcreteClass
extends AbstractClass
implements ExampleInterface{
//Abstract Method HAS TO be IMPLEMENTED in child class. Implemented by ConcreteClass
@Override
public void AbstractMethod() {
System.out.println("AbstractMethod overridden runs");
}
//Standard Method CAN be OVERRIDDEN.
@Override
public void StandardMethod() {
super.StandardMethod();
System.out.println("StandardMethod overridden in ConcreteClass runs");
}
public void ConcreteMethod(){
System.out.println("Concrete method runs");
}
//A method in interface HAS TO be IMPLEMENTED in implementer class.
@Override
public void MethodInInterface() {
System.out.println("MethodInInterface Implemented by ConcreteClass runs");
// Cannot declare abstract method in a concrete class
// public abstract void AbstractMethodDeclarationInConcreteClassNotPossible(){
//
// }
}
}
'Static readonly' vs. 'const'
The readonly
keyword is different from the const
keyword. A const
field can only be initialized at the declaration of the field. A readonly
field can be initialized either at the declaration or in a constructor. Therefore, readonly
fields can have different values depending on the constructor used. Also, while a const
field is a compile-time constant, the readonly
field can be used for runtime constants
Short and clear MSDN reference here
How can I use external JARs in an Android project?
I know the OP ends his question with reference to the Eclipse plugin, but I arrived here with a search that didn't specify Eclipse. So here goes for Android Studio:
- Add
jar
file to libs directory (such as copy/paste)
- Right-Click on
jar
file and select "Add as Library..."
- click "Ok" on next dialog or renamed if you choose to.
That's it!
What is the correct way of reading from a TCP socket in C/C++?
1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:
#define BUFFER_SIZE 4096
char buffer[BUFFER_SIZE]
This saves you the worry of ensuring that you delete[]
the buffer should an exception be thrown.
But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.
2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).
Sending mail from Python using SMTP
The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.
Classes residing in App_Code is not accessible
In my case, I couldn't get a project to build with classes defined in the App_Code folder.
Can't replicate the scenario precisely to comment, but had to close and re-open visual studio for intellisense to co-operate agree...
I noticed that when a class in the App_Code folder is set to 'Compile' instead of 'Content' (right-click it) that the errors were coming from a second version of the class... Look to the left-most of the 3 of the 3 fields between the code pane and the tab. The 'other' one was called something along the lines of 10_App_Code or similar.
To rectify the issue, I renamed the folder from App_Code to Code, explicitly set namespaces on the classes and set all of the classes to 'Compile'
Using OR & AND in COUNTIFS
In a more general case:
N( A union B) = N(A) + N(B) - N(A intersect B)
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")
How to get my activity context?
The best and easy way to get the activity context is putting .this
after the name of the Activity. For example: If your Activity's name is SecondActivity
, its context will be SecondActivity.this
How to convert rdd object to dataframe in spark
This code works perfectly from Spark 2.x with Scala 2.11
Import necessary classes
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StringType, StructField, StructType}
Create SparkSession
Object, and Here it's spark
val spark: SparkSession = SparkSession.builder.master("local").getOrCreate
val sc = spark.sparkContext // Just used to create test RDDs
Let's an RDD
to make it DataFrame
val rdd = sc.parallelize(
Seq(
("first", Array(2.0, 1.0, 2.1, 5.4)),
("test", Array(1.5, 0.5, 0.9, 3.7)),
("choose", Array(8.0, 2.9, 9.1, 2.5))
)
)
Method 1
Using SparkSession.createDataFrame(RDD obj)
.
val dfWithoutSchema = spark.createDataFrame(rdd)
dfWithoutSchema.show()
+------+--------------------+
| _1| _2|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
| test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+
Method 2
Using SparkSession.createDataFrame(RDD obj)
and specifying column names.
val dfWithSchema = spark.createDataFrame(rdd).toDF("id", "vals")
dfWithSchema.show()
+------+--------------------+
| id| vals|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
| test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+
Method 3 (Actual answer to the question)
This way requires the input rdd
should be of type RDD[Row]
.
val rowsRdd: RDD[Row] = sc.parallelize(
Seq(
Row("first", 2.0, 7.0),
Row("second", 3.5, 2.5),
Row("third", 7.0, 5.9)
)
)
create the schema
val schema = new StructType()
.add(StructField("id", StringType, true))
.add(StructField("val1", DoubleType, true))
.add(StructField("val2", DoubleType, true))
Now apply both rowsRdd
and schema
to createDataFrame()
val df = spark.createDataFrame(rowsRdd, schema)
df.show()
+------+----+----+
| id|val1|val2|
+------+----+----+
| first| 2.0| 7.0|
|second| 3.5| 2.5|
| third| 7.0| 5.9|
+------+----+----+
How do I get the result of a command in a variable in windows?
The humble for command has accumulated some interesting capabilities over the years:
D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008
Note that "delims="
overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.
To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):
REM NB:in a batch file, need to use %%i not %i
setlocal EnableDelayedExpansion
SET lf=-
FOR /F "delims=" %%i IN ('dir \ /b') DO if ("!out!"=="") (set out=%%i) else (set out=!out!%lf%%%i)
ECHO %out%
To capture a piped expression, use ^|
:
FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"
Get variable from PHP to JavaScript
I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.
In your HTML pages, you can request data from the PHP scripts like this:
$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
alert('Result from PHP: ' + e.result);
});
In bar.php you can do this:
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));
This is what's usually called AJAX, and it is useful to give web pages a more
dynamic and desktop-like feel (you don't have to refresh the entire page to communicate
with PHP).
Other techniques are simpler. As others have suggested, you can simply generate the
variable data from your PHP script:
$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";
Most web pages nowadays use a combination of the two.
Boxplot show the value of mean
You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:
fun_mean <- function(x){
return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}
ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)
Laravel Eloquent - Get one Row
Using Laravel Eloquent you can get one row using first()
method,
it returns first row of table if where()
condition is not found otherwise it gives the first matched row of given criteria.
Syntax:
Model::where('fieldname',$value)->first();
Example:
$user = User::where('email',$email)->first();
//OR
//$user = User::whereEmail($email)->first();
Flutter - Wrap text on overflow, like insert ellipsis or fade
Depending on your situation, I think this is the best approach below.
final maxWidth = MediaQuery.of(context).size.width * 0.4;
Container(
textAlign: TextAlign.center),
child: Text('This is long text',
constraints: BoxConstraints(maxWidth: maxWidth),
),
Access images inside public folder in laravel
You simply need to use the asset
helper function in Laravel. (The url
helper can also be used in this manner)
<img src="{{ asset('images/arrow.gif') }}" />
For the absolute path, you use public_path
instead.
<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>
If you are providing the URL to a public image from a controller (backend) you can use asset
as well, or secure_asset
if you want HTTPS. eg:
$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif
return $secure_url;
Lastly, if you want to go directly to the image on a given route you can redirect to it:
return \Redirect::to($secure_url);
More Laravel helper functions can be found here
angular-cli where is webpack.config.js file - new angular6 does not support ng eject
There's a nice way to eject webpack.config.js from angular-cli. Just run:
$ ng eject
This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of
$ ng serve
you would have to do something like
$ npm run build & npm run start
This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)
Check if a variable exists in a list in Bash
Assuming TARGET variable can be only 'binomial' or 'regression', then following would do:
# Check for modeling types known to this script
if [ $( echo "${TARGET}" | egrep -c "^(binomial|regression)$" ) -eq 0 ]; then
echo "This scoring program can only handle 'binomial' and 'regression' methods now." >&2
usage
fi
You could add more strings into the list by separating them with a | (pipe) character.
Advantage of using egrep, is that you could easily add case insensitivity (-i), or check more complex scenarios with a regular expression.
Turn a single number into single digits Python
This can be done quite easily if you:
Use str
to convert the number into a string so that you can iterate over it.
Use a list comprehension to split the string into individual digits.
Use int
to convert the digits back into integers.
Below is a demonstration:
>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>
Get current user id in ASP.NET Identity 2.0
In order to get CurrentUserId in Asp.net Identity 2.0, at first import Microsoft.AspNet.Identity
:
C#:
using Microsoft.AspNet.Identity;
VB.NET:
Imports Microsoft.AspNet.Identity
And then call User.Identity.GetUserId()
everywhere you want:
strCurrentUserId = User.Identity.GetUserId()
This method returns current user id as defined datatype for userid in database (the default is String
).
Nested classes' scope?
All explanations can be found in Python Documentation The Python Tutorial
For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined
. The explanation is:
There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.
quoted from The Python Tutorial 9.4
For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined
When a class definition is left normally (via the end), a class object is created.
quoted from The Python Tutorial 9.3.1
So when you try inner_var = Outerclass.outer_var
, the Quterclass
hasn't been created yet, that's why name 'OuterClass' is not defined
A more detailed but tedious explanation for your first error:
Although classes have access to enclosing functions’ scopes, though, they do not act
as enclosing scopes to code nested within the class: Python searches enclosing functions
for referenced names, but never any enclosing classes. That is, a class is a local scope
and has access to enclosing local scopes, but it does not serve as an enclosing local scope
to further nested code.
quoted from Learning.Python(5th).Mark.Lutz
How to keep a VMWare VM's clock in sync?
If your host time is correct, you can set the following .vmx configuration file option to enable periodic synchronization:
tools.syncTime = true
By default, this synchronizes the time every minute. To change the periodic rate, set the following option to the desired synch time in seconds:
tools.syncTime.period = 60
For this to work you need to have VMWare tools installed in your guest OS.
See http://www.vmware.com/pdf/vmware_timekeeping.pdf for more information
Try-catch-finally-return clarification
Here is some code that show how it works.
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
The results is:
try
catch
finally
return in finally
Python memory usage of numpy arrays
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
How does java do modulus calculations with negative numbers?
Your answer is in wikipedia:
modulo operation
It says, that in Java the sign on modulo operation is the same as that of dividend. and since we're talking about the rest of the division operation is just fine, that it returns -13 in your case, since -13/64 = 0. -13-0 = -13.
EDIT: Sorry, misunderstood your question...You're right, java should give -13. Can you provide more surrounding code?
How to export JSON from MongoDB using Robomongo
Expanding on Anish's answer, I wanted something I can apply to any query to automatically output all fields vs. having to define them within the print statement. It can probably be simplified but this was something quick & dirty that works great:
var cursor = db.getCollection('foo').find({}, {bar: 1, baz: 1, created_at: 1, updated_at: 1}).sort({created_at: -1, updated_at: -1});
while (cursor.hasNext()) {
var record = cursor.next();
var output = "";
for (var i in record) {
output += record[i] + ",";
};
output = output.substring(0, output.length - 1);
print(output);
}
Difference between Fact table and Dimension table?
- The fact table mainly consists of business facts and foreign keys that refer to primary keys in the dimension tables. A dimension table consists mainly of descriptive attributes that are textual fields.
- A dimension table contains a surrogate key, natural key, and a set of attributes. On the contrary, a fact table contains a foreign key, measurements, and degenerated dimensions.
- Dimension tables provide descriptive or contextual information for the measurement of a fact table. On the other hand, fact tables provide the measurements of an enterprise.
- When comparing the size of the two tables, a fact table is bigger than a dimensional table. In a comparison table, more dimensions are presented than the fact tables. In a fact table, less numbers of facts are observed.
- The dimension table has to be loaded first. While loading the fact tables, one should have to look at the dimension table. This is because the fact table has measures, facts, and foreign keys that are the primary keys in the dimension table.
Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo
How can I tell Moq to return a Task?
Similar Issue
I have an interface that looked roughly like:
Task DoSomething(int arg);
Symptoms
My unit test failed when my service under test awaited
the call to DoSomething
.
Fix
Unlike the accepted answer, you are unable to call .ReturnsAsync()
on your Setup()
of this method in this scenario, because the method returns the non-generic Task
, rather than Task<T>
.
However, you are still able to use .Returns(Task.FromResult(default(object)))
on the setup, allowing the test to pass.
Convert a date format in epoch
You can also use the new Java 8 API
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowTest{
public static void main(String args[]){
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
}
}
The DateTimeFormatter
class replaces the old SimpleDateFormat
. You can then create a ZonedDateTime
from which you can extract the desired epoch time.
The main advantage is that you are now thread safe.
Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.
Difference between nVidia Quadro and Geforce cards?
The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.
The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:
Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.
If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.
Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.
Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.
So to sum up:
The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).
Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.
That's about it, price-vise the Quadros or FirePros are artificially overpriced.
How to save LogCat contents to file?
Click in the logcat window (on a log even). Followed by "Ctrl + A" (select all). Then either "Right click with the mouse" or "Ctrl +C" (copy). Then paste it anywhere you like using any editor you like.
One could also delete the logcat output before the logs relevant to us appear (before we start testing our use case) to get only relevant logs in the logcat.
Changing datagridview cell color based on condition
Let's say you have to color certain cell (not all cells of the row) by knowing two things:
- Name or index of the column.
- Value which is gonna be inside of the cell.
In thas case you have to use event CellFormatting
In my case I use like this
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
{
row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
}
else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
{
// row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row
row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
}
}
}
And result you can see here
So here you can access certain cell of the row in column by its name
row.Cells["Decade1Hours"]
How do you know this name?
Well in my case i create column of DataGridView like this.
var Decade1Hours = new DataGridViewTextBoxColumn()
{
Name = "Decade1Hours",
Width = 50,
DataPropertyName = "Decade1Hours",
ReadOnly = true,
DefaultCellStyle = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
ForeColor = System.Drawing.Color.Black,
Font = new Font(font, FontStyle.Bold),
Format = "n2"
},
HeaderCell = new DataGridViewColumnHeaderCell()
{
Style = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
BackColor = System.Drawing.Color.Blue
}
}
};
Decade1Hours.HeaderText = "???.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);
And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).
And code will lok like
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells[1].Value) > 0 )
{
row.Cells[1].Style.BackColor = Color.LightGreen;
}
}
}
Simplest way to wait some asynchronous tasks complete, in Javascript?
Use Promises.
var mongoose = require('mongoose');
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
return new Promise(function(resolve, reject) {
var collection = conn.collection(name);
collection.drop(function(err) {
if (err) { return reject(err); }
console.log('dropped ' + name);
resolve();
});
});
});
Promise.all(promises)
.then(function() { console.log('all dropped)'); })
.catch(console.error);
This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr
.
Previous answer (this pre-dates Node’s native support for Promises):
Use Q promises or Bluebird promises.
With Q:
var Q = require('q');
var mongoose = require('mongoose');
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa','bbb','ccc'].map(function(name){
var collection = conn.collection(name);
return Q.ninvoke(collection, 'drop')
.then(function() { console.log('dropped ' + name); });
});
Q.all(promises)
.then(function() { console.log('all dropped'); })
.fail(console.error);
With Bluebird:
var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose'));
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
return conn.collection(name).dropAsync().then(function() {
console.log('dropped ' + name);
});
});
Promise.all(promises)
.then(function() { console.log('all dropped'); })
.error(console.error);
Using intents to pass data between activities
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
Convert char array to a int number in C
I personally don't like atoi
function. I would suggest sscanf
:
char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);
It's very standard, it's in the stdio.h
library :)
And in my opinion, it allows you much more freedom than atoi
, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.
EDIT
I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi
, sscanf
and strtol
. Also, there is a nice more-detailed insight into sscanf
(actually, the whole family of *scanf
functions).
EDIT2
Looks like it's not just me personally disliking the atoi
function. Here's a link to an answer explaining that the atoi
function is deprecated and should not be used in newer code.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
How to git ignore subfolders / subdirectories?
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
/*.*
#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trail and error!
How to detect if a browser is Chrome using jQuery?
As a quick addition, and I'm surprised nobody has thought of this, you could use the in
operator:
"chrome" in window
Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.
Exec : display stdout "live"
There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn
and the { stdio: 'inherit' }
option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone
.
Simply do this:
var spawn = require('child_process').spawn;
spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });
Credit to @MorganTouvereyQuilling for pointing this out in this comment.
How do I convert a String to a BigInteger?
BigInteger has a constructor where you can pass string as an argument.
try below,
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
this.sum = this.sum.add(new BigInteger(newNumber));
}
how to read System environment variable in Spring applicationContext
You are close :o)
Spring 3.0 adds Spring Expression Language.
You can use
<util:properties id="dbProperties"
location="classpath:config_#{systemProperties['env']}/db.properties" />
Combined with java ... -Denv=QA
should solve your problem.
Note also a comment by @yiling:
In order to access system environment variable, that is OS level
variables as amoe commented, we can simply use "systemEnvironment"
instead of "systemProperties" in that EL. Like
#{systemEnvironment['ENV_VARIABLE_NAME']}
Accessing JSON object keys having spaces
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
How to check all checkboxes using jQuery?
html :
<div class="col-md-3 general-sidebar" id="CategoryGrid">
<h5>Category & Sub Category <span style="color: red;">* </span></h5>
<div class="checkbox">
<label>
<input onclick="checkUncheckAll(this)" type="checkbox">
All
</label>
</div>
<div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>
javascript:
function checkUncheckAll(ele) {
if (ele.checked) {
$('.cat').prop('checked', ele.checked);
$('.subcat').prop('checked', ele.checked);
}
else {
$('.cat').prop('checked', ele.checked);
$('.subcat').prop('checked', ele.checked);
}
}
Change UITableView height dynamically
Use simple and easy code
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let myCell = tableView.dequeueReusableCellWithIdentifier("mannaCustumCell") as! CustomCell
let heightForCell = myCell.bounds.size.height;
return heightForCell;
}
How to get the current working directory in Java?
Code :
public class JavaApplication {
public static void main(String[] args) {
System.out.println("Working Directory = " + System.getProperty("user.dir"));
}
}
This will print the absolute path of the current directory from where your application was initialized.
Explanation:
From the documentation:
java.io
package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir
and is the directory from where the JVM was invoked.
Spool Command: Do not output SQL statement to file
My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.
This did not resolve my problem:
set echo off
This resolved my problem:
set verify off
C# importing class into another class doesn't work
MyClass
is a class not a namespace. So this code is wrong:
using MyClass //THIS CODE IS NOT CORRECT
You should check the namespace of the MyClass
(e.g: MyNamespace). Then call it in a proper way:
MyNamespace.MyClass myClass =new MyNamespace.MyClass();
Include another HTML file in a HTML file
My solution is similar to the one of lolo above. However, I insert the HTML code via JavaScript's document.write instead of using jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
The reason for me against using jQuery is that jQuery.js is ~90kb in size, and I want to keep the amount of data to load as small as possible.
In order to get the properly escaped JavaScript file without much work, you can use the following sed command:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
Or just use the following handy bash script published as a Gist on Github, that automates all necessary work, converting b.html
to b.js
:
https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
Credits to Greg Minshall for the improved sed command that also escapes back slashes and single quotes, which my original sed command did not consider.
Alternatively for browsers that support template literals the following also works:
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
How can I run another application within a panel of my C# program?
I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).
Here's a link to OLE info to get started:
http://en.wikipedia.org/wiki/Object_Linking_and_Embedding
Local and global temporary tables in SQL Server
Table variables (DECLARE @t TABLE
) are visible only to the connection that creates it, and are deleted when the batch or stored procedure ends.
Local temporary tables (CREATE TABLE #t
) are visible only to the
connection that creates it, and are deleted when the connection is
closed.
Global temporary tables (CREATE TABLE ##t
) are visible to everyone,
and are deleted when all connections that have referenced them have closed.
Tempdb permanent tables (USE tempdb CREATE TABLE t
) are visible to
everyone, and are deleted when the server is restarted.
Send an Array with an HTTP Get
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
Positioning <div> element at center of screen
Set the width and height and you're good.
div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
}
If you want the element dimensions to be flexible (and don't care about legacy browsers), go with XwipeoutX's answer.
Regex Match all characters between two strings
For example
(?<=This is)(.*)(?=sentence)
Regexr
I used lookbehind (?<=)
and look ahead (?=)
so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence
.
The important thing here is that you activate the "dotall" mode of your regex engine, so that the .
is matching the newline. But how you do this depends on your regex engine.
The next thing is if you use .*
or .*?
. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.
Update
Regexr
This is(?s)(.*)sentence
Where the (?s) turns on the dotall modifier, making the .
matching the newline characters.
Update 2:
(?<=is \()(.*?)(?=\s*\))
is matching your example "This is (a simple) sentence". See here on Regexr
C++: Print out enum value as text
Here is an example based on Boost.Preprocessor:
#include <iostream>
#include <boost/preprocessor/punctuation/comma.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/comparison/equal.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#define DEFINE_ENUM(name, values) \
enum name { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_VALUE, , values) \
}; \
inline const char* format_##name(name val) { \
switch (val) { \
BOOST_PP_SEQ_FOR_EACH(DEFINE_ENUM_FORMAT, , values) \
default: \
return 0; \
} \
}
#define DEFINE_ENUM_VALUE(r, data, elem) \
BOOST_PP_SEQ_HEAD(elem) \
BOOST_PP_IIF(BOOST_PP_EQUAL(BOOST_PP_SEQ_SIZE(elem), 2), \
= BOOST_PP_SEQ_TAIL(elem), ) \
BOOST_PP_COMMA()
#define DEFINE_ENUM_FORMAT(r, data, elem) \
case BOOST_PP_SEQ_HEAD(elem): \
return BOOST_PP_STRINGIZE(BOOST_PP_SEQ_HEAD(elem));
DEFINE_ENUM(Errors,
((ErrorA)(0))
((ErrorB))
((ErrorC)))
int main() {
std::cout << format_Errors(ErrorB) << std::endl;
}
How can you represent inheritance in a database?
I lean towards method #1 (a unified Section table), for the sake of efficiently retrieving entire policies with all their sections (which I assume your system will be doing a lot).
Further, I don't know what version of SQL Server you're using, but in 2008+ Sparse Columns help optimize performance in situations where many of the values in a column will be NULL.
Ultimately, you'll have to decide just how "similar" the policy sections are. Unless they differ substantially, I think a more-normalized solution might be more trouble than it's worth... but only you can make that call. :)
How to specify names of columns for x and y when joining in dplyr?
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
Renaming Column Names in Pandas Groupby function
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary,
e.g., m.x is equivalent to m.dict["x"]
How to import a single table in to mysql database using command line
First of all, login to your database and check whether the database table which you want to import is not available on your database.
If it is available, delete the table using the command. Else it will throw an error while importing the table.
DROP TABLE Table_Name;
Then, move to the folder in which you have the .sql
file to import and run the following command from your terminal
mysql -u username -p databasename < yourtable.sql
The terminal will ask you to enter the password. Enter it and check the database.