How to convert Nvarchar column to INT
I know its Too late But I hope it will work new comers
Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
How to hide console window in python?
Simply save it with a .pyw
extension. This will prevent the console window from opening.
On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.
Explanation at the bottom of section 2.2.2
How to set delay in vbscript
If you're trying to simulate a sleep delay in VBScript but WScript is not available (eg: your script is called from Microsoft's BGInfo tool), then try the following approach.
The example below will delay until 10 seconds from the moment the instruction is processed:
Dim dteWait
dteWait = DateAdd("s", 10, Now())
Do Until (Now() > dteWait)
Loop
grep --ignore-case --only
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
Are HTTPS headers encrypted?
HTTP version 1.1 added a special HTTP method, CONNECT - intended to create the SSL tunnel, including the necessary protocol handshake and cryptographic setup.
The regular requests thereafter all get sent wrapped in the SSL tunnel, headers and body inclusive.
Cannot issue data manipulation statements with executeQuery()
This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver
try {
String Query = "INSERT INTO `stock`(`stock`, `min_stock`,
`id_stock`) VALUES ("
+ "\"" + p.get_Stock().getStock() + "\", "
+ "\"" + p.get_Stock().getStockMinimo() + "\","
+ "" + "null" + ")";
Statement st = miConexion.createStatement();
st.executeUpdate(Query);
java.sql.ResultSet rs;
rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");
rs.next(); //para posicionar el puntero en la primer fila
ultimo_id = rs.getInt("LAST_INSERT_ID()");
} catch (SqlException ex) { ex.printTrace;}
How to get Last record from Sqlite?
Here's a simple example that simply returns the last line without need to sort anything from any column:
"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"
Git error: src refspec master does not match any
You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:
git add a_text_file.txt
... do:
git commit -m "Initial commit."
... and those errors should go away.
VBA: Conditional - Is Nothing
In my sample code, I was setting my object
to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing
and also if not My_Object is nothing
. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:
if My_Object is Nothing Then
'do nothing
Else
'Do something
End if
Add my custom http header to Spring RestTemplate request / extend RestTemplate
You can pass custom http headers with RestTemplate exchange method as below.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);
RestTemplate template = new RestTemplate();
ResponseEntity<RestResponse> respEntity = template
.exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
EDIT : Below is the updated code. This link has several ways of calling rest service with examples
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);
Mall[] resp = respEntity.getBody();
How to check size of a file using Bash?
alternative solution with awk and double parenthesis:
FILENAME=file.txt
SIZE=$(du -sb $FILENAME | awk '{ print $1 }')
if ((SIZE<90000)) ; then
echo "less";
else
echo "not less";
fi
How do I run a single test using Jest?
From the command line, use the --testNamePattern
or -t
flag:
jest -t 'fix-order-test'
This will only run tests that match the test name pattern you provide. It's in the Jest documentation.
Another way is to run tests in watch mode, jest --watch
, and then press P to filter the tests by typing the test file name or T to run a single test name.
If you have an it
inside of a describe
block, you have to run
jest -t '<describeString> <itString>'
Get checkbox list values with jQuery
$(document).ready(function() {
$('#someButton').click(function() {
var names = [];
$('#MyDiv input:checked').each(function() {
names.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it
});
});
SimpleDateFormat parsing date with 'Z' literal
tl;dr
Instant.parse ( "2010-04-05T17:16:00Z" )
ISO 8601 Standard
Your String complies with the ISO 8601 standard (of which the mentioned RFC 3339 is a profile).
Avoid java.util.Date
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Instead use either the Joda-Time library or the new java.time package in Java 8. Both use ISO 8601 as their defaults for parsing and generating string representations of date-time values.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The Instant
class in java.time represents a moment on the timeline in UTC time zone.
The Z
at the end of your input string means Zulu
which stands for UTC
. Such a string can be directly parsed by the Instant
class, with no need to specify a formatter.
String input = "2010-04-05T17:16:00Z";
Instant instant = Instant.parse ( input );
Dump to console.
System.out.println ( "instant: " + instant );
instant: 2010-04-05T17:16:00Z
From there you can apply a time zone (ZoneId
) to adjust this Instant
into a ZonedDateTime
. Search Stack Overflow for discussion and examples.
If you must use a java.util.Date
object, you can convert by calling the new conversion methods added to the old classes such as the static method java.util.Date.from( Instant )
.
java.util.Date date = java.util.Date.from( instant );
Joda-Time
Example in Joda-Time 2.5.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ):
DateTime dateTime = new DateTime( "2010-04-05T17:16:00Z", timeZone );
Convert to UTC.
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Convert to a java.util.Date if necessary.
java.util.Date date = dateTime.toDate();
Proper indentation for Python multiline strings
Use inspect.cleandoc
like so:
def method():
string = inspect.cleandoc("""
line one
line two
line three""")
Relative indentation will be maintained as expected. As commented below, if you want to keep preceding empty lines, use textwrap.dedent
. However that also keeps the first line break.
Note: It's good practice to indent logical blocks of code under its related context to clarify the structure. E.g. the multi-line string belonging to the variable string
.
How to import functions from different js file in a Vue+webpack+vue-loader project
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
Use require in .vue
files
<script>
var mylib = require('./mylib');
export default {
....
Exports in mylib
exports.myfunc = () => {....}
Avoid import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
How to use JavaScript with Selenium WebDriver Java
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here.
How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
making matplotlib scatter plots from dataframes in Python's pandas
I will recommend to use an alternative method using seaborn
which more powerful tool for data plotting. You can use seaborn scatterplot
and define colum 3 as hue
and size
.
Working code:
import pandas as pd
import seaborn as sns
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")
Heatmap in matplotlib with pcolor?
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
if (select count(column) from table) > 0 then
Edit:
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
Edited
You can simply do it all within the update statement (ie no if
construct):
update table
set ...
where ...
and exists (select 'x' from table where ...)
SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
Fastest method of screen capturing on Windows
EDIT: I can see that this is listed under your first edit link as "the GDI way". This is still a decent way to go even with the performance advisory on that site, you can get to 30fps easily I would think.
From this comment (I have no experience doing this, I'm just referencing someone who does):
HDC hdc = GetDC(NULL); // get the desktop device context
HDC hDest = CreateCompatibleDC(hdc); // create a device context to use yourself
// get the height and width of the screen
int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
// create a bitmap
HBITMAP hbDesktop = CreateCompatibleBitmap( hdc, width, height);
// use the previously created device context with the bitmap
SelectObject(hDest, hbDesktop);
// copy from the desktop device context to the bitmap device context
// call this once per 'frame'
BitBlt(hDest, 0,0, width, height, hdc, 0, 0, SRCCOPY);
// after the recording is done, release the desktop context you got..
ReleaseDC(NULL, hdc);
// ..delete the bitmap you were using to capture frames..
DeleteObject(hbDesktop);
// ..and delete the context you created
DeleteDC(hDest);
I'm not saying this is the fastest, but the BitBlt
operation is generally very fast if you're copying between compatible device contexts.
For reference, Open Broadcaster Software implements something like this as part of their "dc_capture" method, although rather than creating the destination context hDest
using CreateCompatibleDC
they use an IDXGISurface1
, which works with DirectX 10+. If there is no support for this they fall back to CreateCompatibleDC
.
To change it to use a specific application, you need to change the first line to GetDC(game)
where game
is the handle of the game's window, and then set the right height
and width
of the game's window too.
Once you have the pixels in hDest/hbDesktop, you still need to save it to a file, but if you're doing screen capture then I would think you would want to buffer a certain number of them in memory and save to the video file in chunks, so I will not point to code for saving a static image to disk.
PHP convert XML to JSON
With accepted (antonio's) answer, from such source:
<MyData>
<Level1 myRel="parent" myName="AAA">
<Level2 myRel="child1" myName="BBB">
<Level2 myRel="child2" myName="CCC">
...
you will get array like:
'Level1' =>
[
0 =>
[
'@attributes' =>
[
'myRel' => 'parent'
'myName' => 'AAA'
],
'Level2' =>
[
0 =>
[
'@attributes' =>
[
'myRel' => 'child_1'
'myName' => 'BBB'
],
So, if you want to have Key-Paired array (instead of 0
numbers), with your chosen key, i.e. myName
:
'Level1' =>
[
'AAA' =>
[
'@attributes' =>
[
'myRel' => 'parent'
'myName' => 'AAA'
],
'Level2' =>
[
'BBB' =>
[
'@attributes' =>
[
'myRel' => 'child_1'
'myName' => 'BBB'
],
then use xmlToArrayByKey($xmlContent, 'myName')
. Code Here:
public function xmlToArrayByKey($content, $keyName)
{
try
{
$xml = simplexml_load_string($content, "SimpleXMLElement", LIBXML_NOCDATA );
$array= json_decode( json_encode($xml), TRUE);
return $this->xmlSetChild($array, $keyName);
} catch (Exception $ex) {
return ['xmlerror'=>$ex];
}
}
public function xmlSetChild($array, $keyName, $step=0)
{
$new_array= [];
foreach ($array as $key_1=>$value_1)
{
if (is_array($value_1) && isset($value_1[0]))
{
foreach ($value_1 as $idx=>$value_2)
{
$keyValue = $value_2['@attributes'][$keyName];
$new_array[$key_1][$keyValue] = $this->xmlSetChild($value_2, $keyName, $step+1);
}
}
else{
$new_array[$key_1]=$value_1;
}
}
return $new_array;
}
href="file://" doesn't work
Share your folder for "everyone" or some specific group and try this:
_x000D_
_x000D_
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a>
_x000D_
_x000D_
_x000D_
ldap query for group members
Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.
How about:
(&(objectClass=group)(member=cn=my,ou=full,dc=domain))
(You forgot the (& ) bit in your example in the question as well).
Jenkins pipeline if else not working
your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if
as a top-level step in declarative, so you need to wrap it in a script
step. here's a working declarative version:
pipeline {
agent any
stages {
stage('test') {
steps {
sh 'echo hello'
}
}
stage('test1') {
steps {
sh 'echo $TEST'
}
}
stage('test3') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
}
}
you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!
Query to list all users of a certain group
memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:
(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
If you don't yet have the distinguished name, you can search for it with:
(&(objectCategory=group)(cn=myCustomGroup))
and return the attribute distinguishedName
. Case may matter.
Excel Formula which places date/time in cell when data is entered in another cell in the same row
Another way to do this is described below.
First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation
. Then set maximum iterations to 1000.
After doing this, use the following formula.
=If(D55="","",IF(C55="",NOW(),C55))
Once anything is typed into cell D55
(for this example) then C55
populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.
This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.
Disabling enter key for form
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
jQuery If DIV Doesn't Have Class "x"
When you are checking if an element has or does not have a class, make sure you didn't accidentally put a dot in the class name:
<div class="className"></div>
$('div').hasClass('className');
$('div').hasClass('.className'); #will not work!!!!
After a long time of staring at my code I realized I had done this. A little typo like this took me an hour to figure out what I had done wrong. Check your code!
SQL Server: UPDATE a table by using ORDER BY
No.
Not a documented 100% supported way. There is an approach sometimes used for calculating running totals called "quirky update" that suggests that it might update in order of clustered index if certain conditions are met but as far as I know this relies completely on empirical observation rather than any guarantee.
But what version of SQL Server are you on? If SQL2005+ you might be able to do something with row_number
and a CTE (You can update the CTE)
With cte As
(
SELECT id,Number,
ROW_NUMBER() OVER (ORDER BY id DESC) AS RN
FROM Test
)
UPDATE cte SET Number=RN
How to check if a textbox is empty using javascript
<pre><form name="myform" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
Note: before using the code above you have to add the gen_validatorv31.js
file.
What is the difference between json.dumps and json.load?
dumps
takes an object and produces a string:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would take a file-like object, read the data from that object, and use that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
Note that dump
and load
convert between files and objects, while dumps
and loads
convert between strings and objects. You can think of the s
-less functions as wrappers around the s
functions:
def dump(obj, fh):
fh.write(dumps(obj))
def load(fh):
return loads(fh.read())
Convert Date/Time for given Timezone - java
display date and time for all timezones
import java.util.Calendar;
import java.util.TimeZone;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssZ";
DateFormat dateFormat = new SimpleDateFormat(ISO8601);
Calendar c = Calendar.getInstance();
String formattedTime;
for (String availableID : TimeZone.getAvailableIDs()) {
dateFormat.setTimeZone(TimeZone.getTimeZone(availableID));
formattedTime = dateFormat.format(c.getTime());
System.out.println(formattedTime + " " + availableID);
}
What is the difference between vmalloc and kmalloc?
One of other differences is kmalloc will return logical address (else you specify GPF_HIGHMEM). Logical addresses are placed in "low memory" (in the first gigabyte of physical memory) and are mapped directly to physical addresses (use __pa macro to convert it). This property implies kmalloced memory is continuous memory.
In other hand, Vmalloc is able to return virtual addresses from "high memory". These addresses cannot be converted in physical addresses in a direct fashion (you have to use virt_to_page function).
Using cut command to remove multiple columns
The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1
perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'
is equivalent to:
cut -d, -f2-4,6-10,12-20
If the commas are not needed in the output:
perl -F, -lane 'print "@F[1..3,5..9,11..19]"'
Should try...catch go inside or outside a loop?
setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.
depending on the number of iterations, performance difference will likely be negligible.
However i agree with the others that having it outside the loop make the loop body look cleaner.
If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.
How do I redirect in expressjs while passing some context?
we can use express-session to send the required data
when you initialise the app
const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));
so before redirection just save the context for the session
app.post('/category', function(req, res) {
// add your context here
req.session.context ='your context here' ;
res.redirect('/');
});
Now you can get the context anywhere for the session. it can get just by req.session.context
app.get('/', function(req, res) {
// So prepare the context
var context=req.session.context;
res.render('home.jade', context);
});
Insert variable values in the middle of a string
I would use a StringBuilder class for doing string manipulation as it will more efficient (being mutable)
string flights = "Flight A, B,C,D";
StringBuilder message = new StringBuilder();
message.Append("Hi We have these flights for you: ");
message.Append(flights);
message.Append(" . Which one do you want?");
convert double to int
My ways are :
- Convert.ToInt32(double_value)
- (int)double_value
- Int32.Parse(double_value.ToString());
IF EXISTS in T-SQL
Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0
which often won't.
With EXISTS
if you look at the execution plan you will see that the actual number of rows coming out of table1
will not be more than 1 irrespective of number of matching records.
In some circumstances SQL Server can convert the tree for the COUNT
query to the same as the one for EXISTS
during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.
For more complicated sub trees than shown in the question you may occasionally find the COUNT
performs better than EXISTS
however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.
Generate unique random numbers between 1 and 100
This is my personal solution :
<script>
var i, k;
var numbers = new Array();
k = Math.floor((Math.random()*8));
numbers[0]=k;
for (var j=1;j<8;j++){
k = Math.floor((Math.random()*8));
i=0;
while (i < numbers.length){
if (numbers[i] == k){
k = Math.floor((Math.random()*8));
i=0;
}else {i++;}
}
numbers[j]=k;
}
for (var j=0;j<8;j++){
alert (numbers[j]);
}
</script>
It randomly generates 8 unique array values (between 0 and 7), then displays them using an alert box.
How to get parameters from a URL string?
Dynamic function which parse string url and get value of query parameter passed in URL
function getParamFromUrl($url,$paramName){
parse_str(parse_url($url,PHP_URL_QUERY),$op);// fetch query parameters from string and convert to associative array
return array_key_exists($paramName,$op) ? $op[$paramName] : "Not Found"; // check key is exist in this array
}
Call Function to get result
echo getParamFromUrl('https://google.co.in?name=james&surname=bond','surname'); // bond will be o/p here
CSS: Hover one element, effect for multiple elements?
This is not difficult to achieve, but you need to use the javascript onmouseover
function. Pseudoscript:
<div class="section ">
<div class="image"><img src="myImage.jpg" onmouseover=".layer {border: 1px solid black;} .image {border: 1px solid black;}" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
Use your own colors. You can also reference javascript functions in the mouseover command.
How to drop column with constraint?
The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.
ALTER TABLE MyTable
DROP CONSTRAINT FK_MyColumn
CONSTRAINT DK_MyColumn
-- etc...
COLUMN MyColumn
GO
Printing with sed or awk a line following a matching pattern
This might work for you (GNU sed):
sed -n ':a;/regexp/{n;h;p;x;ba}' file
Use seds grep-like option -n
and if the current line contains the required regexp replace the current line with the next, copy that line to the hold space (HS), print the line, swap the pattern space (PS) for the HS and repeat.
how to add css class to html generic control div?
You don't add the css file to the div, you add a class to it then put your import at the top of the HTML page like so:
<link href="../files/external.css" rel="stylesheet" type="text/css" />
Then add a class like the following to your code: 'myStyle'.
Then in the css file do something like:
.myStyle
{
border-style: 1px solid #DBE0E4;
}
Start/Stop and Restart Jenkins service on Windows
Open Console/Command line --> Go to your Jenkins installation directory. Execute the following commands respectively:
to stop:
jenkins.exe stop
to start:
jenkins.exe start
to restart:
jenkins.exe restart
How to prevent XSS with HTML/PHP?
You are also able to set some XSS related HTTP response headers via header(...)
X-XSS-Protection "1; mode=block"
to be sure, the browser XSS protection mode is enabled.
Content-Security-Policy "default-src 'self'; ..."
to enable browser-side content security. See this one for Content Security Policy (CSP) details: http://content-security-policy.com/
Especially setting up CSP to block inline-scripts and external script sources is helpful against XSS.
for a general bunch of useful HTTP response headers concerning the security of you webapp, look at OWASP: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
How to delete an object by id with entity framework
dwkd's answer mostly worked for me in Entity Framework core, except when I saw this exception:
InvalidOperationException: The instance of entity type 'Customer' cannot
be tracked because another instance with the same key value for {'Id'}
is already being tracked. When attaching existing entities, ensure
that only one entity instance with a given key value is attached.
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to
see the conflicting key values.
To avoid the exception, I updated the code:
Customer customer = context.Customers.Local.First(c => c.Id == id);
if (customer == null) {
customer = new Customer () { Id = id };
context.Customers.Attach(customer);
}
context.Customers.Remove(customer);
context.SaveChanges();
How to fix getImageData() error The canvas has been tainted by cross-origin data?
I was seeing this error on Chrome
while I was testing my code locally. I switched to Firefox
and I am not seeing the error any more. Maybe switching to another browser is a quick fix.
If you are using the solution given in first answer, then make sure you add img.crossOrigin = "Anonymous";
just after you declare the img
variable (for eg. var img = new Image();
).
Trim a string in C
#include "stdafx.h"
#include <string.h>
#include <ctype.h>
char* trim(char* input);
int _tmain(int argc, _TCHAR* argv[])
{
char sz1[]=" MQRFH ";
char sz2[]=" MQRFH";
char sz3[]=" MQR FH";
char sz4[]="MQRFH ";
char sz5[]="MQRFH";
char sz6[]="M";
char sz7[]="M ";
char sz8[]=" M";
char sz9[]="";
char sz10[]=" ";
printf("sz1:[%s] %d\n",trim(sz1), strlen(sz1));
printf("sz2:[%s] %d\n",trim(sz2), strlen(sz2));
printf("sz3:[%s] %d\n",trim(sz3), strlen(sz3));
printf("sz4:[%s] %d\n",trim(sz4), strlen(sz4));
printf("sz5:[%s] %d\n",trim(sz5), strlen(sz5));
printf("sz6:[%s] %d\n",trim(sz6), strlen(sz6));
printf("sz7:[%s] %d\n",trim(sz7), strlen(sz7));
printf("sz8:[%s] %d\n",trim(sz8), strlen(sz8));
printf("sz9:[%s] %d\n",trim(sz9), strlen(sz9));
printf("sz10:[%s] %d\n",trim(sz10), strlen(sz10));
return 0;
}
char *ltrim(char *s)
{
while(isspace(*s)) s++;
return s;
}
char *rtrim(char *s)
{
char* back;
int len = strlen(s);
if(len == 0)
return(s);
back = s + len;
while(isspace(*--back));
*(back+1) = '\0';
return s;
}
char *trim(char *s)
{
return rtrim(ltrim(s));
}
Output:
sz1:[MQRFH] 9
sz2:[MQRFH] 6
sz3:[MQR FH] 8
sz4:[MQRFH] 7
sz5:[MQRFH] 5
sz6:[M] 1
sz7:[M] 2
sz8:[M] 2
sz9:[] 0
sz10:[] 8
Xcode - ld: library not found for -lPods
The below solution worked for me for the core-plot 2.3 version.
Do the below changes under other linker flags section.
1.Add $(inherited) and drag this item to top position
2.Remove "Pods-" prefix from -l"Pods-fmemopen”, l"Pods-NSAttributedStringMarkdownParser” and -l"Pods-MagicalRecord”.
if still issue persists, Finally see if PODS_ROOT is set or not. You can check it under user defined section.
C# - using List<T>.Find() with custom objects
Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.
var element = myList.Find(e => [some condition on e]);
In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.
In your case, that would be:
var reponse = list.Find(r => r.Statement == "statement1")
And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:
var response = list.Find(delegate (Response r) {
return r.Statement == "statement1";
});
Setting cursor at the end of any text of a textbox
Try like below... it will help you...
Some time in Window Form Focus()
doesn't work correctly. So better you can use Select()
to focus the textbox.
txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox
How to reload current page in ReactJS?
Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount()
in a React class.
For you edit, you may want to try something like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.onAddBucket = this.onAddBucket.bind(this);
}
componentWillMount() {
this.setState({
buckets: {},
})
}
componentDidMount() {
this.onAddBucket();
}
onAddBucket() {
let self = this;
let getToken = localStorage.getItem('myToken');
var apiBaseUrl = "...";
let input = {
"name" : this.state.fields["bucket_name"]
}
axios.defaults.headers.common['Authorization'] = getToken;
axios.post(apiBaseUrl+'...',input)
.then(function (response) {
if (response.data.status == 200) {
this.setState({
buckets: this.state.buckets.concat(response.data.buckets),
});
} else {
alert(response.data.message);
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
{this.state.bucket}
);
}
}
How to print number with commas as thousands separators?
You can also use '{:n}'.format( value )
for a locale representation. I think this is the simpliest way for a locale solution.
For more information, search for thousands
in Python DOC.
For currency, you can use locale.currency
, setting the flag grouping
:
Code
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )
Output
'Portuguese_Brazil.1252'
'R$ 1.234.567,89'
Calculate RSA key fingerprint
The fastest way if your keys are in an SSH agent:
$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin
Each key in the agent will be printed as:
4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)
git stash and git pull
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Convert base64 string to image
public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
if (inputStream.isPresent()) {
ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
FileCopyUtils.copy(inputStream.get(), output);
//TODO retrieve content type from file, & replace png below with it
return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
}
return Optional.empty();
Render HTML to PDF in Django site
Try the solution from Reportlab.
Download it and install it as usual with python setup.py install
You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.
Here is an usage example:
First define this function:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Then you can use it like this:
def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
The template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
Hope it helps.
AngularJS format JSON string output
You can use an optional parameter of JSON.stringify()
JSON.stringify(value[, replacer [, space]])
Parameters
- value The value to convert to a JSON string.
- replacer If a function,
transforms values and properties encountered while stringifying; if an
array, specifies the set of properties included in objects in the
final string. A detailed description of the replacer function is
provided in the javaScript guide article Using native JSON.
- space
Causes the resulting string to be pretty-printed.
For example:
JSON.stringify({a:1,b:2,c:{d:3, e:4}},null," ")
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
Get user's non-truncated Active Directory groups from command line
Based on answer by P.Brian.Mackey-- I tried using gpresult /user <UserName> /r
command, but it only seemed to work for my user account; for other users accounts I got this result: The user "userNameHere" does not have RSOP data
.
So I read through this blog-- https://blog.thesysadmins.co.uk/group-policy-gpresult-examples.html-- and came upon a solution. You have to know the users computer name:
gpresult /s <UserComputer> /r /user:<UserName>
After running the command, you have to ENTER
a few times for the program to complete because it will pause in the middle of the ouput. Also, the results gave a bunch of data including a section for "COMPUTER SETTINGS> Applied Group Policy Objects
" and then "COMPUTER SETTINGS> Security groups
" and finally "USER SETTINGS> security groups
" (this is what we are looking for with the AD groups listed with non-truncated descriptions!).
Interesting to note that GPRESULT had some extra members not seen in NET USER command. Also, the sort order does not match and is not alphabetical. Any body who can add more insights in the comments that would be great.
RESULTS: gpresult (with ComputerName, UserName)
For security reasons, I have included only a subset of the membership results. (36 TOTAL, 12 SAMPLE)
The user is a part of the following security groups
---------------------------------------------------
..
Internet Email
GEVStandardPSMViewers
GcoFieldServicesEditors
AnimalWelfare_Readers
Business Objects
Zscaler_Standard_Access
..
GCM
..
GcmSharesEditors
GHVStandardPSMViewers
IntranetReportsViewers
JetDWUsers -- (NOTE: this one was deleted today, the other "Jet" one was added)
..
Time and Attendance Users
..
RESULTS: net user /DOMAIN (with UserName)
For security reasons, I have included only a subset of the membership results. (23 TOTAL, 12 SAMPLE)
Local Group Memberships
Global Group memberships ...
*Internet Email *GEVStandardPSMViewers
*GcoFieldServicesEdito*AnimalWelfare_Readers
*Business Objects *Zscaler_Standard_Acce
...
*Time and Attendance U*GCM
...
*GcmSharesEditors *GHVStandardPSMViewers
*IntranetReportsViewer*JetPowerUsers
The command completed successfully.
jQuery click function doesn't work after ajax call?
Since the class is added dynamically, you need to use event delegation to register the event handler like:
$('#LangTable').on('click', '.deletelanguage', function(event) {
event.preventDefault();
alert("success");
});
This will attach your event to any anchors within the #LangTable
element,
reducing the scope of having to check the whole document
element tree and increasing efficiency.
FIDDLE DEMO
link button property to open in new tab?
This is not perfect, but it works.
<asp:LinkButton id="lbnkVidTtile1" runat="Server"
CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'
OnClientClick="return PostToNewWindow();" />
<script type="text/javascript">
function PostToNewWindow()
{
originalTarget = document.forms[0].target;
document.forms[0].target='_blank';
window.setTimeout("document.forms[0].target=originalTarget;",300);
return true;
}
</script>
How to loop through a HashMap in JSP?
Depending on what you want to accomplish within the loop, iterate over one of these instead:
countries.keySet()
countries.entrySet()
countries.values()
SQL Server procedure declare a list
Alternative to @Peter Monks.
If the number in the 'in' statement is small and fixed.
DECLARE @var1 varchar(30), @var2 varchar(30), @var3 varchar(30);
SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';
Select * FROM Database Where x in (@var1,@var2,@var3);
Best way to remove items from a collection
There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:
shortname => SPRoleAssignment
If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.
Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.
Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?
This is very easy by import repository feature
Login to github.com
,
Side of profile picture you will find +
button click on that then there will be option to import repository
.
you will find page like this.
Your old repository’s clone URL is required which is gitlab repo url in your case.
then select Owner and then type name for this repo and click to begin import button.
Is there an easy way to strike through text in an app widget?
Android resources have pretty good HTML markup support
The below HTML elements are supported:
Bold: <b>, <em>
Italic: <i>, <cite>, <dfn>
25% larger text: <big>
20% smaller text: <small>
Setting font properties: <font face=”font_family“ color=”hex_color”>. Examples of possible font families include monospace, serif, and sans_serif.
Setting a monospace font family: <tt>
Strikethrough: <s>, <strike>, <del>
Underline: <u>
Superscript: <sup>
Subscript: <sub>
Bullet points: <ul>, <li>
Line breaks: <br>
Division: <div>
CSS style: <span style=”color|background_color|text-decoration”>
Paragraphs: <p dir=”rtl | ltr” style=”…”>
Note however that it's not rendered in android studio layouts preview. Last tested on Android Studio 3.3.1
For example, the Strikethrough will look like that:
<string name="cost"><strike>$10</strike> $5 a month</string>
Writing files in Node.js
options
may also include a start
option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags
mode of r+
rather than the default mode w
. The encoding can be any one of those accepted by Buffer.
If autoClose
is set to true (default behavior) on 'error'
or 'finish'
the file descriptor will be closed automatically. If autoClose
is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.
Like ReadStream, if fd
is specified, WriteStream will ignore the path
argument and will use the specified file descriptor. This means that no 'open'
event will be emitted. fd
should be blocking; non-blocking fd
s should be passed to net.Socket.
If options
is a string, then it specifies the encoding.
After, reading this long article. You should understand how it works.
So, here's an example of createWriteStream()
.
/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');
"No X11 DISPLAY variable" - what does it mean?
For those who are trying to get an X Window application working from Windows from Linux:
What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0
Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.
How to get substring in C
char originalString[] = "THESTRINGHASNOSPACES";
char aux[5];
int j=0;
for(int i=0;i<strlen(originalString);i++){
aux[j] = originalString[i];
if(j==3){
aux[j+1]='\0';
printf("%s\n",aux);
j=0;
}else{
j++;
}
}
Inheriting from a template class in c++
For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.
Specifically, Area
is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int>
is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>
. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.
Since Area
is not a class, you cannot derive the class Rectangle
from it. You only can derive a class from another class (or several of them). Since Area<int>
is a class, you could, for example, derive Rectangle
from it:
class Rectangle:
public Area<int>
{
// ...
};
Since Area<int>
and Area<char>
are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):
class Rectangle:
public Area<int>,
public Area<char>
{
// ...
};
However you have to specify which classed to derive from when you define Rectangle
. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.
What you can do is to make Rectangle
a template as well. If you write
template<typename T> class Rectangle:
public Area<T>
{
// ...
};
You have a template Rectangle
from which you can get a class Rectangle<int>
which derives from Area<int>
, and a different class Rectangle<char>
which derives from Area<char>
.
It may be that you want to have a single type Rectangle
so that you can pass all sorts of Rectangle
to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T>
classes generated by instantiating the template Rectangle
are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:
class Rectangle // not inheriting from any Area type
{
// Area independent interface
};
template<typename T> class SpecificRectangle:
public Rectangle,
public Area<T>
{
// Area dependent stuff
};
void foo(Rectangle&); // A function which works with generic rectangles
int main()
{
SpecificRectangle<int> intrect;
foo(intrect);
SpecificRectangle<char> charrect;
foo(charrect);
}
If it is important that your generic Rectangle
is derived from a generic Area
you can do the same trick with Area
too:
class Area
{
// generic Area interface
};
class Rectangle:
public virtual Area // virtual because of "diamond inheritance"
{
// generic rectangle interface
};
template<typename T> class SpecificArea:
public virtual Area
{
// specific implementation of Area for type T
};
template<typename T> class SpecificRectangle:
public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
public SpecificArea<T> // no virtual inheritance needed here
{
// specific implementation of Rectangle for type T
};
Function to close the window in Tkinter
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
how to make a cell of table hyperlink
I have seen this before when people are trying to build a calendar. You want the cell linked but do not want to mess with anything else inside of it, try this and it might solve your problem.
<tr>
<td onClick="location.href='http://www.stackoverflow.com';">
Cell content goes here
</td>
</tr>
Space between two divs
DIVs inherently lack any useful meaning, other than to divide, of course.
Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.
<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>
h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}
Formatting a field using ToText in a Crystal Reports formula field
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
Make flex items take content width, not width of parent container
In addtion to align-self
you can also consider auto margin which will do almost the same thing
_x000D_
_x000D_
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How can I access a hover state in reactjs?
React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover
in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter
and onMouseLeave
. You then attach them to handlers in your component like so:
<ReactComponent
onMouseEnter={() => this.someHandler}
onMouseLeave={() => this.someOtherHandler}
/>
You'll then use some combination of state/props to pass changed state or properties down to your child React components.
"id cannot be resolved or is not a field" error?
For me the cause of the problem was that I had 2 images with the same name in my drawable-hdpi folder. Once I resolved that, then the R.java rebuilt itself and the problem was automatically solved.
ggplot geom_text font size control
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
Adding Google Translate to a web site
Code
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'hi', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Tri-state Check box in HTML?
Here is a runnable example using the mentioned indeterminate
attribute:
_x000D_
_x000D_
const indeterminates = document.getElementsByClassName('indeterminate');_x000D_
indeterminates['0'].indeterminate = true;
_x000D_
<form>_x000D_
<div>_x000D_
<input type="checkbox" checked="checked" />True_x000D_
</div>_x000D_
<div>_x000D_
<input type="checkbox" />False_x000D_
</div>_x000D_
<div>_x000D_
<input type="checkbox" class="indeterminate" />Indeterminate_x000D_
</div>_x000D_
</form>
_x000D_
_x000D_
_x000D_
Just run the code snippet to see how it looks like.
How do I ignore a directory with SVN?
...and if you want to ignore more than one directory (say build/
temp/
and *.tmp
files), you could either do it in two steps (ignoring the first and edit ignore properties (see other answers here) or one could write something like
svn propset svn:ignore "build
temp
*.tmp" .
on the command line.
How to easily resize/optimize an image size with iOS?
If you image is in document directory, Add this URL extension:
extension URL {
func compressedImageURL(quality: CGFloat = 0.3) throws -> URL? {
let imageData = try Data(contentsOf: self)
debugPrint("Image file size before compression: \(imageData.count) bytes")
let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".jpg")
guard let actualImage = UIImage(data: imageData) else { return nil }
guard let compressedImageData = UIImageJPEGRepresentation(actualImage, quality) else {
return nil
}
debugPrint("Image file size after compression: \(compressedImageData.count) bytes")
do {
try compressedImageData.write(to: compressedURL)
return compressedURL
} catch {
return nil
}
}
}
Usage:
guard let localImageURL = URL(string: "< LocalImagePath.jpg >") else {
return
}
//Here you will get URL of compressed image
guard let compressedImageURL = try localImageURL.compressedImageURL() else {
return
}
debugPrint("compressedImageURL: \(compressedImageURL.absoluteString)")
Note:- Change < LocalImagePath.jpg > with your local jpg image path.
how to read xml file from url using php
Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On
on php.ini)
Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:
<?php
if (($response_xml_data = file_get_contents($map_url))===false){
echo "Error fetching XML\n";
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
echo "Error loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
} else {
print_r($data);
}
}
?>
If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents()
on example 4 at http://php.net/manual/en/function.file-get-contents.php
MySQL VARCHAR size?
100 characters.
This is the var (variable) in varchar
: you only store what you enter (and an extra 2 bytes to store length upto 65535)
If it was char(200)
then you'd always store 200 characters, padded with 100 spaces
See the docs: "The CHAR and VARCHAR Types"
PostgreSQL create table if not exists
I created a generic solution out of the existing answers which can be reused for any table:
CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN
IF EXISTS (
SELECT *
FROM pg_catalog.pg_tables
WHERE tablename = table_name
) THEN
RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
EXECUTE create_stmt;
RETURN 'CREATED';
END IF;
END;
$_$ LANGUAGE plpgsql;
Usage:
select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');
It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.
How to duplicate a whole line in Vim?
yy or Y to copy the line (mnemonic: yank)
or
dd to delete the line (Vim copies what you deleted into a clipboard-like "register", like a cut operation)
then
p to paste the copied or deleted text after the current line
or
P to paste the copied or deleted text before the current line
Find distance between two points on map using Google Map API V2
simple util function to calculate distance between two geopoints:
public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {
double l1 = toRadians(lat1);
double l2 = toRadians(lat2);
double g1 = toRadians(lng1);
double g2 = toRadians(lng2);
double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
if(dist < 0) {
dist = dist + Math.PI;
}
return Math.round(dist * 6378100);
}
how to count the total number of lines in a text file using python
here is how you can do it through list comprehension, but this will waste a little bit of your computer's memory as line.strip() has been called twice.
with open('textfile.txt') as file:
lines =[
line.strip()
for line in file
if line.strip() != '']
print("number of lines = {}".format(len(lines)))
What is the unix command to see how much disk space there is and how much is remaining?
Note: The original question was answered already, but I would just like to expand on it with some extras that are relevant to the topic.
Your AIX installation would first be put into volume groups. This is done upon installation.
It will first create rootvg (as in root volume group). This is kinda like your actual hard drive mapped.
This would be equivalent to Disc Management in Windows. AIX wont use up all of that space for its file systems like we tend to do it in consumer Windows machines. Instead there will be a good bit of unallocated space.
To check how much space your rootvg would have you use the following command.
lsvg rootvg
That would stand for list volume group rootvg. This will give you information like the size of physical partitions (PP), Total PPs assigned to the volume group, Free PPs in the volume group, etc. Regardless, the output should be fairly comprehensive.
Next thing you may be interested in, is the file systems on the volume group. Each file system would have certain amount of space given within the volume group it belongs to.
To check what file systems you got on your volume group you use the following command.
lsvgfs rootvg
As in list volume group file systems for rootvg.
You can check how much space each file system has using the following command.
df
I personally like to refine it with flags like -m and -g (in megabytes and gigabytes respectively)
If you have free space available in your volume group, you can assign it to your file systems using the following command.
chfs -a size=+1G /home
As in change file system attribute size by adding 1 G where file system is /home. use man chfs for more instructions. This is a powerful tool. This example is for adjusting size, however you can do more with this command than that.
Sources:
http://www.ibm.com/developerworks/aix/library/au-rootvg/
+ My own experience working with AIX.
Android - Start service on boot
Well here is a complete example of an AutoStart Application
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
service.java
public class service extends Service
{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),hello.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
hello.java - This will pop-up everytime you start the device after executing the Applicaton once.
public class hello extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
Disable dragging an image from an HTML page
Directly use this: ondragstart="return false;"
in your image tag.
<img src="http://image-example.png" ondragstart="return false;"/>
If you have multiple images, wrapped on a <div>
tag:
<div ondragstart="return false;">
<img src="image1.png"/>
<img scr="image2.png"/>
</div>
Works in all major browsers.
Which passwordchar shows a black dot (•) in a winforms textbox?
One more solution to use this Unicode black circle >>
Start >> All Programs >> Accessories >> System Tools >> Character Map
Then select Arial font
and choose the Black circle
copy it and paste it into PasswordChar
property of the textbox.
That's it....
Download a file from HTTPS using download.file()
Offering the curl package as an alternative that I found to be reliable when extracting large files from an online database. In a recent project, I had to download 120 files from an online database and found it to half the transfer times and to be much more reliable than download.file.
#install.packages("curl")
library(curl)
#install.packages("RCurl")
library(RCurl)
ptm <- proc.time()
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
proc.time() - ptm
ptm
ptm1 <- proc.time()
curl_download(url =URL ,destfile="TEST.CSV",quiet=FALSE, mode="wb")
proc.time() - ptm1
ptm1
ptm2 <- proc.time()
y = download.file(URL, destfile = "./data/data.csv", method="curl")
proc.time() - ptm2
ptm2
In this case, rough timing on your URL showed no consistent difference in transfer times. In my application, using curl_download in a script to select and download 120 files from a website decreased my transfer times from 2000 seconds per file to 1000 seconds and increased the reliability from 50% to 2 failures in 120 files. The script is posted in my answer to a question I asked earlier, see .
How can I echo a newline in a batch file?
You can also do like this,
(for %i in (a b "c d") do @echo %~i)
The output will be,
a
b
c d
Note that when this is put in a batch file, '%' shall be doubled.
(for %%i in (a b "c d") do @echo %%~i)
Set up a scheduled job?
Although not part of Django, Airflow is a more recent project (as of 2016) that is useful for task management.
Airflow is a workflow automation and scheduling system that can be used to author and manage data pipelines. A web-based UI provides the developer with a range of options for managing and viewing these pipelines.
Airflow is written in Python and is built using Flask.
Airflow was created by Maxime Beauchemin at Airbnb and open sourced in the spring of 2015. It joined the Apache Software Foundation’s incubation program in the winter of 2016. Here is the Git project page and some addition background information.
Returning a value from callback function in Node.js
Example code for node.js - async function to sync function:
var deasync = require('deasync');
function syncFunc()
{
var ret = null;
asyncFunc(function(err, result){
ret = {err : err, result : result}
});
while((ret == null))
{
deasync.runLoopOnce();
}
return (ret.err || ret.result);
}
Convert and format a Date in JSP
Date td = new Date();
String b = new String("");
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
b = format.format(td);
out.println(b);
How to implement HorizontalScrollView like Gallery?
You may use HorizontalScrollView to implement Horizontal scrolling.
Code
<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
android:id="@+id/innerLay"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
featured.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="160dp"
android:layout_margin="4dp"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar
android:layout_width="15dip"
android:layout_height="15dip"
android:id="@+id/progress"
android:layout_centerInParent="true"
/>
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#20000000"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center"
android:textColor="#000000"
android:background="#ffffff"
android:text="Image Text" />
</RelativeLayout>
</LinearLayout>
Java Code:
LayoutInflater inflater;
inflater=getLayoutInflater();
LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);
for(int x=0;x<10;x++)
{
inLay.addView(getView(x));
}
View getView(final int x)
{
View rootView = inflater.inflate( R.layout.featured_item,null);
ImageView image = (ImageView) rootView.findViewById(R.id.image);
//Thease Two Line is sufficient my dear to implement lazyLoading
AQuery aq = new AQuery(rootView);
String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,
Toast.LENGTH_LONG).show();
}
});
return rootView;
}
Note: to implement lazy loading, please use this link for AQUERY
https://code.google.com/p/android-query/wiki/ImageLoading
Connect Bluestacks to Android Studio
first open bluestacks and go to settings > preferences > check the
Enable Android Debug Bridge (ADB) and press Change path button, then
select adb path. (default location:
%LocalAppData%\Android\sdk\platform-tools)
then install one apk in emulator (by click the installed apps >
install apk in bluestacks home screen)
after doing this works run cmd by administrator and got to adb path then run this command:
adb connect localhost:5555
now you can open VSCodde or AndroidStudio and select BlueStacks emulator.
Build tree array from flat array in javascript
My solution:
- Allows bi-directional mapping (root to leaves and leaves to root)
- Returns all nodes, roots, and leaves
- One data pass and very fast performance
- Vanilla Javascript
/**
*
* @param data items array
* @param idKey item's id key (e.g., item.id)
* @param parentIdKey item's key that points to parent (e.g., item.parentId)
* @param noParentValue item's parent value when root (e.g., item.parentId === noParentValue => item is root)
* @param bidirectional should parent reference be added
*/
function flatToTree(data, idKey, parentIdKey, noParentValue = null, bidirectional = true) {
const nodes = {}, roots = {}, leaves = {};
// iterate over all data items
for (const i of data) {
// add item as a node and possibly as a leaf
if (nodes[i[idKey]]) { // already seen this item when child was found first
// add all of the item's data and found children
nodes[i[idKey]] = Object.assign(nodes[i[idKey]], i);
} else { // never seen this item
// add to the nodes map
nodes[i[idKey]] = Object.assign({ $children: []}, i);
// assume it's a leaf for now
leaves[i[idKey]] = nodes[i[idKey]];
}
// put the item as a child in parent item and possibly as a root
if (i[parentIdKey] !== noParentValue) { // item has a parent
if (nodes[i[parentIdKey]]) { // parent already exist as a node
// add as a child
(nodes[i[parentIdKey]].$children || []).push( nodes[i[idKey]] );
} else { // parent wasn't seen yet
// add a "dummy" parent to the nodes map and put the item as its child
nodes[i[parentIdKey]] = { $children: [ nodes[i[idKey]] ] };
}
if (bidirectional) {
// link to the parent
nodes[i[idKey]].$parent = nodes[i[parentIdKey]];
}
// item is definitely not a leaf
delete leaves[i[parentIdKey]];
} else { // this is a root item
roots[i[idKey]] = nodes[i[idKey]];
}
}
return {roots, nodes, leaves};
}
Usage example:
const data = [{id: 2, parentId: 0}, {id: 1, parentId: 2} /*, ... */];
const { nodes, roots, leaves } = flatToTree(data, 'id', 'parentId', 0);
Difference between char* and const char*?
In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char *
or const char *
.
However, the difference is that if the pointer is const char *
then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char *
then it does not.
Is it possible to decompile an Android .apk file?
Are the users able to convert the apk file of my application back to the actual code?
yes.
People can use various tools to:
- analysis: your apk
- decode/hack your apk
- using
FDex2
to dump out dex
file
- then using
dex2jar
to convert to jar
- then using
jadx
to conver to java
source code
If they do - is there any way to prevent this?
yes. Several (can combined) ways to prevent (certain degree) this:
- low level: code obfuscation
- high level: use android harden scenario
More details can refer my Chinese tutorial: ??????????
What's the difference between a null pointer and a void pointer?
A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int
pointer you would do
int* p = 0;
A null pointer will be returned by malloc
on failure.
We can test if a pointer is null, i.e. if malloc
or some other function failed simply by testing its boolean value:
if (p) {
/* Pointer is not null */
} else {
/* Pointer is null */
}
A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.
How to change button color with tkinter
When you do self.button = Button(...).grid(...)
, what gets assigned to self.button
is the result of the grid()
command, not a reference to the Button
object created.
You need to assign your self.button
variable before packing/griding it.
It should look something like this:
self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
HashMap to return default value for non-found keys?
You can simply create a new class that inherits HashMap and add getDefault method.
Here is a sample code:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
public V getDefault(K key, V defaultValue) {
if (containsKey(key)) {
return get(key);
}
return defaultValue;
}
}
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).
Javascript swap array elements
If you don't want to use temp variable in ES5, this is one way to swap array elements.
var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
How to split a string into an array in Bash?
Another approach can be:
str="a, b, c, d" # assuming there is a space after ',' as in Q
arr=(${str//,/}) # delete all occurrences of ','
After this 'arr' is an array with four strings.
This doesn't require dealing IFS or read or any other special stuff hence much simpler and direct.
Android: How to use webcam in emulator?
UPDATE
In Android Studio AVD:
- Open AVD Manager:
- Add/Edit AVD:
- Click Advanced Settings in the bottom of the screen:
- Set your camera of choice as the front/back cameras:
Matplotlib-Animation "No MovieWriters Available"
For fellow googlers using Anaconda, install the ffmpeg package:
conda install -c conda-forge ffmpeg
This works on Windows too.
(Original answer used menpo
package owner but as mentioned by @harsh their version is a little behind at time of writing)
"Too many characters in character literal error"
Here's an example:
char myChar = '|';
string myString = "||";
Chars are delimited by single quotes, and strings by double quotes.
The good news is C# switch statements work with strings!
switch (mytoken)
{
case "==":
//Something here.
break;
default:
//Handle when no token is found.
break;
}
Where and how is the _ViewStart.cshtml layout file linked?
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file
called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the
\Views folder of your project:
The _ViewStart file can be used to define common view code that you
want to execute at the start of each View’s rendering. For example,
we could write code within our _ViewStart.cshtml file to
programmatically set the Layout property for each View to be the
SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer
need to explicitly set the Layout in any of our individual view files
(except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we
can optionally make our Layout selection logic richer than just a
basic property set. For example: we could vary the Layout template
that we use depending on what type of device is accessing the site –
and have a phone or tablet optimized layout for those devices, and a
desktop optimized layout for PCs/Laptops. Or if we were building a
CMS system or common shared app that is used across multiple customers
we could select different layouts to use depending on the customer (or
their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more
easily write view logic once, and avoid repeating it in multiple
places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is
a software design paradigm which seeks to decrease the number of
decisions that developers need to make, gaining simplicity, but not
necessarily losing flexibility. The phrase essentially means a
developer only needs to specify unconventional aspects of the
application. For example, if there's a class Sale in the model, the
corresponding table in the database is called “sales” by default. It
is only if one deviates from this convention, such as calling the
table “products_sold”, that one needs to write code regarding these
names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Using str_replace so that it only acts on the first match?
$str = "Hello there folks!"
$str_ex = explode("there, $str, 2); //explodes $string just twice
//outputs: array ("Hello ", " folks")
$str_final = implode("", $str_ex); // glues above array together
// outputs: str("Hello folks")
There is one more additional space but it didnt matter as it was for backgound script in my case.
What's the equivalent of Java's Thread.sleep() in JavaScript?
Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:
async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}
You can then use the sleep function in any other async function like this:
async function testSleep() {
console.log("Waiting for 1 second...");
await sleep(1000);
console.log("Waiting done."); // Called 1 second after the first console.log
}
This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.
From MDN:
The await expression causes async function execution to pause until a
Promise is fulfilled or rejected, and to resume execution of the async
function after fulfillment.
For a full explanation see:
How can I get last characters of a string
Following script shows the result for get last 5 characters and last 1 character in a string using JavaScript:
var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character
Output :
Tabs1 // Got 5 characters
1 // Got 1 character
Adding multiple columns AFTER a specific column in MySQL
Alternatively:
ALTER TABLE users
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `lastname`,
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`;
Will put them in the order you want while streamlining the AFTER statement.
what is Promotional and Feature graphic in Android Market/Play Store?
In market client on phones at least
featured apps with high ratings get to
display the promotional graphic.
This is the one that shows up on top
even before you start searching the
market for a specific app.
See this answer from Android market forum.
Edited: One of the google employee gives some clarifications here
Update: Both links above are now broken but the detailed information can be found here
Selected applications have the ability
to be featured atop their respective
categories. This is not a guaranteed
feature, but uploading promotional
graphics is something that we
recommend.
Convert.ToDateTime: how to set format
DateTime
doesn't have a format. the format only applies when you're turning a DateTime
into a string, which happens implicitly you show the value on a form, web page, etc.
Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).
How to launch html using Chrome at "--allow-file-access-from-files" mode?
That flag is dangerous!! Leaves your file system open for access. Documents originating from anywhere, local or web, should not, by default, have any access to local file:/// resources.
Much better solution is to run a little http server locally.
--- For Windows ---
The easiest is to install http-server globally using node's package manager:
npm install -g http-server
Then simply run http-server
in any of your project directories:
Eg. d:\my_project> http-server
Starting up http-server, serving ./
Available on:
http:169.254.116.232:8080
http:192.168.88.1:8080
http:192.168.0.7:8080
http:127.0.0.1:8080
Hit CTRL-C to stop the server
Or as prusswan suggested, you can also install Python under windows, and follow the instructions below.
--- For Linux ---
Since Python is usually available in most linux distributions, just run python -m SimpleHTTPServer
in your project directory, and you can load your page on http://localhost:8000
In Python 3 the SimpleHTTPServer
module has been merged into http.server
, so the new command is python3 -m http.server
.
Easy, and no security risk of accidentally leaving your browser open vulnerable.
Install Qt on Ubuntu
In Ubuntu 18.04 the QtCreator examples and API docs missing,
This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
Replace console output in Python
A more elegant solution could be:
def progressBar(current, total, barLength = 20):
percent = float(current) * 100 / total
arrow = '-' * int(percent/100 * barLength - 1) + '>'
spaces = ' ' * (barLength - len(arrow))
print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
call this function with value
and endvalue
, result should be
Progress: [-------------> ] 69 %
Note: Python 2.x version here.
Passing string to a function in C - with or without pointers?
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
JBoss debugging in Eclipse
You mean remote debug JBoss from Eclipse ?
From Configuring Eclipse for Remote Debugging:
Set the JAVA_OPTS variable as follows:
set JAVA_OPTS= -Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%
or:
JAVA_OPTS="-Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS"
In the Debug frame, select the Remote Java Application node.
In the Connection Properties, specify localhost
as the Host and specify the Port as the port that was specified in the run batch script of the JBoss server, 8787
.
Implement Stack using Two Queues
Here is some simple pseudo code, push is O(n), pop / peek is O(1):
Qpush = Qinstance()
Qpop = Qinstance()
def stack.push(item):
Qpush.add(item)
while Qpop.peek() != null: //transfer Qpop into Qpush
Qpush.add(Qpop.remove())
swap = Qpush
Qpush = Qpop
Qpop = swap
def stack.pop():
return Qpop.remove()
def stack.peek():
return Qpop.peek()
How do I set log4j level on the command line?
Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work
Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.
Logger.getRootLogger().setLevel(Level.WARN);
HashMap<String,Level> logLevels=new HashMap<String,Level>();
logLevels.put("ALL",Level.ALL);
logLevels.put("TRACE",Level.TRACE);
logLevels.put("DEBUG",Level.DEBUG);
logLevels.put("INFO",Level.INFO);
logLevels.put("WARN",Level.WARN);
logLevels.put("ERROR",Level.ERROR);
logLevels.put("FATAL",Level.FATAL);
logLevels.put("OFF",Level.OFF);
for(String name:System.getProperties().stringPropertyNames()){
String logger="log4j.logger.";
if(name.startsWith(logger)){
String loggerName=name.substring(logger.length());
String loggerValue=System.getProperty(name);
if(logLevels.containsKey(loggerValue))
Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
else
Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
}
}
Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
Splitting a string at every n-th character
I recently encountered this issue, and here is the solution I came up with
final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";
Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.
StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
currentSb.append( test.charAt( i ) ); // add the current char to our sb
}
List<String> comments = stringBuilderMap.entrySet().stream()
.sorted( Comparator.comparing( Map.Entry::getKey ) )
.map( entrySet -> entrySet.getValue().toString() )
.collect( Collectors.toList() );
//done
// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8
// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true