Better way to call javascript function in a tag
Neither is good.
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
The advantage of this is that it
- Separates markup and behaviour in the same way that CSS separates markup and style
- Centralises configuration (this is somewhat a corollary of 1).
- Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn’t have JavaScript enabled.
Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How to get a list column names and datatypes of a table in PostgreSQL?
Below will list all the distinct data types of all the table in the provided schema name.
\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv' delimiter as ',' CSV header
Pointers in Python?
Yes! there is a way to use a variable as a pointer in python!
I am sorry to say that many of answers were partially wrong. In principle every equal(=) assignation shares the memory address (check the id(obj) function), but in practice it is not such. There are variables whose equal("=") behaviour works in last term as a copy of memory space, mostly in simple objects (e.g. "int" object), and others in which not (e.g. "list","dict" objects).
Here is an example of pointer assignation
dict1 = {'first':'hello', 'second':'world'}
dict2 = dict1 # pointer assignation mechanism
dict2['first'] = 'bye'
dict1
>>> {'first':'bye', 'second':'world'}
Here is an example of copy assignation
a = 1
b = a # copy of memory mechanism. up to here id(a) == id(b)
b = 2 # new address generation. therefore without pointer behaviour
a
>>> 1
Pointer assignation is a pretty useful tool for aliasing without the waste of extra memory, in certain situations for performing comfy code,
class cls_X():
...
def method_1():
pd1 = self.obj_clsY.dict_vars_for_clsX['meth1'] # pointer dict 1: aliasing
pd1['var4'] = self.method2(pd1['var1'], pd1['var2'], pd1['var3'])
#enddef method_1
...
#endclass cls_X
but one have to be aware of this use in order to prevent code mistakes.
To conclude, by default some variables are barenames (simple objects like int, float, str,...), and some are pointers when assigned between them (e.g. dict1 = dict2). How to recognize them? just try this experiment with them. In IDEs with variable explorer panel usually appears to be the memory address ("@axbbbbbb...") in the definition of pointer-mechanism objects.
I suggest investigate in the topic. There are many people who know much more about this topic for sure. (see "ctypes" module). I hope it is helpful. Enjoy the good use of the objects! Regards, José Crespo
Just what is an IntPtr exactly?
A direct interpretation
An IntPtr is an integer which is the same size as a pointer.
You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.
The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.
The name "IntPtr" is confusing -- something like Handle
might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.
An alternative perspective
An IntPtr
is a pointer with two limitations:
- It cannot be directly dereferenced
- It doesn't know the type of the data that it points to.
In other words, an IntPtr
is just like a void*
-- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.
In order to dereference an IntPtr
, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal
class. Using the Marshal
class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.
Get Android shared preferences value in activity/normal class
This is the procedure that seems simplest to me:
SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();
if (sp.getString("sharedString", null).equals("true")
|| sp.getString("sharedString", null) == null) {
e.putString("sharedString", "false").commit();
// Do something
} else {
// Do something else
}
Simple and fast method to compare images for similarity
Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:
- Simple euclidean distance as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).
- (Normalized) Cross Correlation - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.
- Histogram comparison - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.
- Detectors of salient points/areas - such as MSER (Maximally Stable Extremal Regions), SURF or SIFT. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: Local invariant feature detectors: a survey.
Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html. The salient point/area detectors are also available - see OpenCV Feature Detection.
Importing class/java files in Eclipse
I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.
How do I count unique values inside a list
Use a set:
words = ['a', 'b', 'c', 'a']
unique_words = set(words) # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3
Armed with this, your solution could be as simple as:
words = []
ipta = raw_input("Word: ")
while ipta:
words.append(ipta)
ipta = raw_input("Word: ")
unique_word_count = len(set(words))
print "There are %d unique words!" % unique_word_count
Get records of current month
This query should work for you:
SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
How to Check byte array empty or not?
You must swap the order of your test:
From:
if (Attachment.Length > 0 && Attachment != null)
To:
if (Attachment != null && Attachment.Length > 0 )
The first version attempts to dereference Attachment
first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").
[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:
if (Attachment?.Length > 0)
How to write a multiline Jinja statement
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
Big O, how do you calculate/approximate it?
For the 1st case, the inner loop is executed n-i
times, so the total number of executions is the sum for i
going from 0
to n-1
(because lower than, not lower than or equal) of the n-i
. You get finally n*(n + 1) / 2
, so O(n²/2) = O(n²)
.
For the 2nd loop, i
is between 0
and n
included for the outer loop; then the inner loop is executed when j
is strictly greater than n
, which is then impossible.
Submitting HTML form using Jquery AJAX
If you add:
jquery.form.min.js
You can simply do this:
<script>
$('#myform').ajaxForm(function(response) {
alert(response);
});
// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>
NOTE:
You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.
MySQL query finding values in a comma separated string
This will work for sure, and I actually tried it out:
lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)
lwdba@localhost (DB test) :: CREATE TABLE shirts
-> (<BR>
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ticketnumber INT,
-> colors VARCHAR(30)
-> );<BR>
Query OK, 0 rows affected (0.19 sec)
lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
-> (32423,'1,2,5,12,15'),
-> (32424,'1,5,12,15,30'),
-> (32425,'2,5,11,15,28'),
-> (32426,'1,2,7,12,15'),
-> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors |
+----+--------------+--------------+
| 1 | 32423 | 1,2,5,12,15 |
| 2 | 32424 | 1,5,12,15,30 |
| 4 | 32426 | 1,2,7,12,15 |
+----+--------------+--------------+
3 rows in set (0.00 sec)
Give it a Try !!!
How do I build an import library (.lib) AND a DLL in Visual C++?
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
How to convert Set<String> to String[]?
Use the Set#toArray(IntFunction<T[]>)
method taking an IntFunction
as generator.
String[] GPXFILES1 = myset.toArray(String[]::new);
If you're not on Java 11 yet, then use the Set#toArray(T[])
method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
While still not on Java 11, and you can't guarantee that myset
is unmodifiable at the moment of conversion to array, then better specify an empty typed array.
String[] GPXFILES1 = myset.toArray(new String[0]);
Characters allowed in GET parameter
From RFC 1738 on which characters are allowed in URLs:
Only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
The reserved characters are ";", "/", "?", ":", "@", "=" and "&", which means you would need to URL encode them if you wish to use them.
Scanner is skipping nextLine() after using next() or nextFoo()?
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
Tomcat won't stop or restart
I had this error message having started up a second Tomcat server on a Linux server.
$CATALINA_PID was set but the specified file does not exist. Is Tomcat running? Stop aborted.
When starting up the 2nd Tomcat I had set CATALINA_PID as asked but my mistake was to set it to a directory (I assumed Tomcat would write a default file name in there with the pid).
The fix was simply to change my CATALINA_PID to add a file name to the end of it (I chose catalina.pid from the above examples). Next I went to the directory and did a simple:
touch catalina.pid
creating an empty file of the correct name. Then when I did my shutdown.sh I got the message back saying:
PID file is empty and has been ignored.
Tomcat stopped.
I didn't have the option to kill Tomcat as the JVM was in use so I was glad I found this.
VBA setting the formula for a cell
Try:
.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address
If your worksheet name (strProjectName
) has spaces, you need to include the single quotes in the formula string.
If this does not resolve it, please provide more information about the specific error or failure.
Update
In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:
strProjectName = Replace(strProjectName," ", "_")
But if you're not also pushing that change to the Worksheet.Name
property, you can expect these to happen:
- The file browse dialog appears
- The formula returns
#REF
error
The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.
So you need to do:
Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")
Then, your formula should work.
CSS3 animate border color
You can try this also...
_x000D_
_x000D_
button {
background: none;
border: 0;
box-sizing: border-box;
margin: 1em;
padding: 1em 2em;
box-shadow: inset 0 0 0 2px #f45e61;
color: #f45e61;
font-size: inherit;
font-weight: 700;
vertical-align: middle;
position: relative;
}
button::before, button::after {
box-sizing: inherit;
content: '';
position: absolute;
width: 100%;
height: 100%;
}
.draw {
-webkit-transition: color 0.25s;
transition: color 0.25s;
}
.draw::before, .draw::after {
border: 2px solid transparent;
width: 0;
height: 0;
}
.draw::before {
top: 0;
left: 0;
}
.draw::after {
bottom: 0;
right: 0;
}
.draw:hover {
color: #60daaa;
}
.draw:hover::before, .draw:hover::after {
width: 100%;
height: 100%;
}
.draw:hover::before {
border-top-color: #60daaa;
border-right-color: #60daaa;
-webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
}
.draw:hover::after {
border-bottom-color: #60daaa;
border-left-color: #60daaa;
-webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
}
_x000D_
<section class="buttons">
<button class="draw">Draw</button>
</section>
_x000D_
_x000D_
_x000D_
How to access /storage/emulated/0/
If you are using a simulator in Android Studio on Mac you can go to View -> Tool Windows -> Device File Explorer
. Here you can use a finder-like structure.
How to get a variable name as a string in PHP?
I have this:
debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));
I would prefer this:
debug_echo($query, $nrUsers, $hdr);
The existing function displays a yellow box with a red outline and shows each variable by name and value. The array solution works but is a little convoluted to type when it is needed.
That's my use case and yes, it does have to do with debugging. I agree with those who question its use otherwise.
How to get the current time as datetime
for only date in specific format
let dateFormatter1 = NSDateFormatter()
dateFormatter1.dateStyle = .MediumStyle
dateFormatter1.timeStyle = .NoStyle
dateFormatter1.dateFormat = "dd-MM-yyyy"
let date = dateFormatter1.stringFromDate(NSDate())
How to get `DOM Element` in Angular 2?
Use ViewChild with #localvariable as shown here,
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
In component,
OLDEST Way
import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
ngAfterViewInit()
{
this.el.nativeElement.focus();
}
OLD Way
import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer) {}
ngAfterViewInit() {
this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}
Updated on 22/03(March)/2017
NEW Way
Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed.
Since Angular team will deprecate invokeElementMethod
, above code no longer can be used.
BREAKING CHANGES
since 4.0 rc.1:
rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2
import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
console.log(this.rd)
will give you following methods and you can see now invokeElementMethod
is not there. Attaching img as yet it is not documented.
NOTE: You can use following methods of Rendere2
with/without ViewChild variable to do so many things.
CSS for grabbing cursors (drag & drop)
I may be late, but you can try the following code, which worked for me for Drag and Drop.
.dndclass{
cursor: url('../images/grab1.png'), auto;
}
.dndclass:active {
cursor: url('../images/grabbing1.png'), auto;
}
You can use the images below in the URL above. Make sure it is a PNG transparent image. If not, download one from google.
Invert "if" statement to reduce nesting
There are several good points made here, but multiple return points can be unreadable as well, if the method is very lengthy. That being said, if you're going to use multiple return points just make sure that your method is short, otherwise the readability bonus of multiple return points may be lost.
Connect different Windows User in SQL Server Management Studio (2005 or later)
None of these answers did what I needed:
Login to a remote server using a different domain account than I was logged into on my local machine, and it's a client's domain across a vpn. I don't want to be on their domain!
Instead, on the connect to server dialog, select "Windows Authentication", click the Options button, and then on the Additional Connection Parameters tab, enter
user id=domain\user;password=password
SSMS won't remember, but it will connect with that account.
Efficient way to do batch INSERTS with JDBC
Though the question asks inserting efficiently to Oracle using JDBC, I'm currently playing with DB2 (On IBM mainframe), conceptually inserting would be similar so thought it might be helpful to see my metrics between
Here go the metrics
1) Inserting one record at a time
public void writeWithCompileQuery(int records) {
PreparedStatement statement;
try {
Connection connection = getDatabaseConnection();
connection.setAutoCommit(true);
String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
" VALUES" + "(?, ?, ?, ?, ?)";
statement = connection.prepareStatement(compiledQuery);
long start = System.currentTimeMillis();
for(int index = 1; index < records; index++) {
statement.setInt(1, index);
statement.setString(2, "emp number-"+index);
statement.setInt(3, index);
statement.setInt(4, index);
statement.setString(5, "username");
long startInternal = System.currentTimeMillis();
statement.executeUpdate();
System.out.println("each transaction time taken = " + (System.currentTimeMillis() - startInternal) + " ms");
}
long end = System.currentTimeMillis();
System.out.println("total time taken = " + (end - start) + " ms");
System.out.println("avg total time taken = " + (end - start)/ records + " ms");
statement.close();
connection.close();
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
ex = ex.getNextException();
}
}
}
The metrics for 100 transactions :
each transaction time taken = 123 ms
each transaction time taken = 53 ms
each transaction time taken = 48 ms
each transaction time taken = 48 ms
each transaction time taken = 49 ms
each transaction time taken = 49 ms
...
..
.
each transaction time taken = 49 ms
each transaction time taken = 49 ms
total time taken = 4935 ms
avg total time taken = 49 ms
The first transaction is taking around 120-150ms
which is for the query parse and then execution, the subsequent transactions are only taking around 50ms
. (Which is still high, but my database is on a different server(I need to troubleshoot the network))
2) With insertion in a batch (efficient one) - achieved by preparedStatement.executeBatch()
public int[] writeInABatchWithCompiledQuery(int records) {
PreparedStatement preparedStatement;
try {
Connection connection = getDatabaseConnection();
connection.setAutoCommit(true);
String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
" VALUES" + "(?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(compiledQuery);
for(int index = 1; index <= records; index++) {
preparedStatement.setInt(1, index);
preparedStatement.setString(2, "empo number-"+index);
preparedStatement.setInt(3, index+100);
preparedStatement.setInt(4, index+200);
preparedStatement.setString(5, "usernames");
preparedStatement.addBatch();
}
long start = System.currentTimeMillis();
int[] inserted = preparedStatement.executeBatch();
long end = System.currentTimeMillis();
System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
System.out.println("total time taken = " + (end - start)/records + " s");
preparedStatement.close();
connection.close();
return inserted;
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
ex = ex.getNextException();
}
throw new RuntimeException("Error");
}
}
The metrics for a batch of 100 transactions is
total time taken to insert the batch = 127 ms
and for 1000 transactions
total time taken to insert the batch = 341 ms
So, making 100 transactions in ~5000ms
(with one trxn at a time) is decreased to ~150ms
(with a batch of 100 records).
NOTE - Ignore my network which is super slow, but the metrics values would be relative.
How do I publish a UDP Port on Docker?
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs:
https://docs.docker.com/config/containers/container-networking/
(Courtesy of Old Pro in the comments)
Create a variable name with "paste" in R?
In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.
lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))
Request UAC elevation from within a Python script?
It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
Xcode 8 shows error that provisioning profile doesn't include signing certificate
This might help you
iOS Distribution profile
Scenario:
Another developer gave me a certificate.
I installed this simply
Error :
Xcode 8 shows error that provisioning profile doesn't include signing certificate
Which was not exactly correct error.
The error was the private key missing
Preference -> Accounts -> Double click team
Call the developer to send the private key.
and installed it into your locally
SECOND SOLUTION
Create a fresh certificate.
Edit your existing provisioning profile
Include fresh certificate
Save and download
What is the difference between the kernel space and the user space?
The correct answer is: There is no such thing as kernel space and user space. The processor instruction set has special permissions to set destructive things like the root of the page table map, or access hardware device memory, etc.
Kernel code has the highest level privileges, and user code the lowest. This prevents user code from crashing the system, modifying other programs, etc.
Generally kernel code is kept under a different memory map than user code (just as user spaces are kept in different memory maps than each other). This is where the "kernel space" and "user space" terms come from. But that is not a hard and fast rule. For example, since the x86 indirectly requires its interrupt/trap handlers to be mapped at all times, part (or some OSes all) of the kernel must be mapped into user space. Again, this does not mean that such code has user privileges.
Why is the kernel/user divide necessary? Some designers disagree that it is, in fact, necessary. Microkernel architecture is based on the idea that the highest privileged sections of code should be as small as possible, with all significant operations done in user privileged code. You would need to study why this might be a good idea, it is not a simple concept (and is famous for both having advantages and drawbacks).
Counting the number of elements in array
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
I got the same error in this case:
var result = Db.SystemLog
.Where(log =>
eventTypeValues.Contains(log.EventType)
&& (
search.Contains(log.Id.ToString())
|| log.Message.Contains(search)
|| log.PayLoad.Contains(search)
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
)
)
.OrderByDescending(log => log.Id)
.Select(r => r);
After spending way too much time debugging, I figured out that error appeared in the logic expression.
The first line search.Contains(log.Id.ToString())
does work fine, but the last line that deals with a DateTime object made it fail miserably:
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
Remove the problematic line and problem solved.
I do not fully understand why, but it seems as ToString() is a LINQ expression for strings, but not for Entities. LINQ for Entities deals with database queries like SQL, and SQL has no notion of ToString(). As such, we can not throw ToString() into a .Where() clause.
But how then does the first line work? Instead of ToString(), SQL have CAST
and CONVERT
, so my best guess so far is that linq for entities uses that in some simple cases. DateTime objects are not always found to be so simple...
"Parser Error Message: Could not load type" in Global.asax
I spent multiple days on this issue. I finally got it resolved with the following combination of suggestions from this post.
- Change platform target to Any CPU. I did not have this configuration currently, so I had to go to the Configuration Manager and add it. I was specifically compiling for x64. This alone did not resolve the error.
- Change the output path to
bin\
instead of bin\x64\Debug
. I had tried this several times already before I changed the platform target. It never made a difference other than getting an error that it failed to load the assembly because of an invalid format.
To be clear, I had to do both of these before it started working. I had tried them individually multiple times but it never fixed it until I did both.
If I change either one of these settings back to the original, I get the same error again, despite having run Clean Solution, and manually deleting everything in the bin
directory.
2D arrays in Python
>>> a = []
>>> for i in xrange(3):
... a.append([])
... for j in xrange(3):
... a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
Regular Expression for alphanumeric and underscores
To match a string that contains only those characters (or an empty string), try
"^[a-zA-Z0-9_]*$"
This works for .NET regular expressions, and probably a lot of other languages as well.
Breaking it down:
^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string
If you don't want to allow empty strings, use + instead of *.
As others have pointed out, some regex languages have a shorthand form for [a-zA-Z0-9_]
. In the .NET regex language, you can turn on ECMAScript behavior and use \w
as a shorthand (yielding ^\w*$
or ^\w+$
). Note that in other languages, and by default in .NET, \w
is somewhat broader, and will match other sorts of Unicode characters as well (thanks to Jan for pointing this out). So if you're really intending to match only those characters, using the explicit (longer) form is probably best.
How to convert list of key-value tuples into dictionary?
This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required
THAT is your actual question.
The answer is that the elements of your list are not what you think they are. If you type myList[0]
you will find that the first element of your list is not a two-tuple, e.g. ('A', 1)
, but rather a 1916-length iterable.
Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]
), all you need to do is dict(myList)
.
How can I compare strings in C using a `switch` statement?
Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by MikeBrom).
char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
printf("B1!\n");
It could be generalized for BE case.
How to find most common elements of a list?
nltk is convenient for a lot of language processing stuff. It has methods for frequency distribution built in. Something like:
import nltk
fdist = nltk.FreqDist(your_list) # creates a frequency distribution from a list
most_common = fdist.max() # returns a single element
top_three = fdist.keys()[:3] # returns a list
Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)
Answers by ‘smartnut007’, ‘Bill Karwin’, and ‘sqlvogel’ are excellent. Yet let me put an interesting perspective to it.
Well, we have prime and non-prime keys.
When we focus on how non-primes depend on primes, we see two cases:
Non-primes can be dependent or not.
What about dependencies among primes?
Now you see, we’re not addressing the dependency relationship among primes by either 2nd or 3rd NF.
Further such dependency, if any, is not desirable and thus we’ve a single rule to address that. This is BCNF.
Referring to the example from Bill Karwin's post here, you’ll notice that both ‘Topping’, and ‘Topping Type’ are prime keys and have a dependency. Had they been non-primes with dependency, then 3NF would have kicked in.
Note:
The definition of BCNF is very generic and without differentiating attributes between prime and non-prime. Yet, the above way of thinking helps to understand how some anomaly is percolated even after 2nd and 3rd NF.
Advanced Topic: Mapping generic BCNF to 2NF & 3NF
Now that we know BCNF provides a generic definition without reference to any prime/non-prime attribues, let's see how BCNF and 2/3 NF's are related.
First, BCNF requires (other than the trivial case) that for each functional dependency X -> Y
(FD), X should be super-key.
If you just consider any FD, then we've three cases - (1) Both X and Y non-prime, (2) Both prime and (3) X prime and Y non-prime, discarding the (nonsensical) case X non-prime and Y prime.
For case (1), 3NF takes care of.
For case (3), 2NF takes care of.
For case (2), we find the use of BCNF
c# search string in txt file
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach
loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
Use stored procedure to insert some data into a table
If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY()
would be a better approach. I would not advice to use @@IDENTITY
, as this can return any ID.
CREATE PROC [dbo].[sp_Test] (
@myID int output,
@myFirstName nvarchar(50),
@myLastName nvarchar(50),
@myAddress nvarchar(50),
@myPort int
) AS
BEGIN
INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
VALUES (@myFirstName, @myLastName, @myAddress, @myPort);
SET @myID = SCOPE_IDENTITY();
END
GO
How to give color to each class in scatter plot in R?
Here is a solution using traditional graphics (and Dirk's data):
> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE))
> DF
x y z
1 1 6.628380 c
2 2 6.403279 b
3 3 6.708716 a
4 4 7.011677 c
5 5 6.363794 a
6 6 5.912945 b
7 7 2.996335 a
8 8 5.242786 c
9 9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)
This relies on the fact that DF$z
is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z
as follows:
> c("red","blue","green")[DF$z]
[1] "green" "blue" "red" "green" "red" "blue" "red" "green" "green" "red"
You can add a legend using the legend
function:
legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)
Adding a column to an existing table in a Rails migration
When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.
You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.
As currently posted, you're adding the column and then creating the table.
If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.
The SQL OVER() clause - when and why is it useful?
The OVER
clause is powerful in that you can have aggregates over different ranges ("windowing"), whether you use a GROUP BY
or not
Example: get count per SalesOrderID
and count of all
SELECT
SalesOrderID, ProductID, OrderQty
,COUNT(OrderQty) AS 'Count'
,COUNT(*) OVER () AS 'CountAll'
FROM Sales.SalesOrderDetail
WHERE
SalesOrderID IN(43659,43664)
GROUP BY
SalesOrderID, ProductID, OrderQty
Get different COUNT
s, no GROUP BY
SELECT
SalesOrderID, ProductID, OrderQty
,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS 'CountQtyPerOrder'
,COUNT(OrderQty) OVER(PARTITION BY ProductID) AS 'CountQtyPerProduct',
,COUNT(*) OVER () AS 'CountAllAgain'
FROM Sales.SalesOrderDetail
WHERE
SalesOrderID IN(43659,43664)
Error "initializer element is not constant" when trying to initialize variable with const
In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.
A "large" object is never a constant expression in C, even if the object is declared as const
.
Moreover, in C language, the term "constant" refers to literal constants (like 1
, 'a'
, 0xFF
and so on), enum members, and results of such operators as sizeof
. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.
For example, this is NOT a constant
const int N = 5; /* `N` is not a constant in C */
The above N
would be a constant in C++, but it is not a constant in C. So, if you try doing
static int j = N; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant.
This is the reason why, in C language, we predominantly use #define
to declare named constants, and also resort to #define
to create named aggregate initializers.
C++ - unable to start correctly (0xc0150002)
In our case (next to trying Dependency Walker) it was a faulty manifest file, mixing 64 bits and 32 bits. We use two extra files while running in Debug mode: dbghelp.dll and Microsoft.DTfW.DHL.manifest.
The manifest file looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- $Id -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<noInheritable />
<assemblyIdentity type="win32" name="Microsoft.DTfW.DHL" version="6.11.1.404" processorArchitecture="x86" />
<file name="dbghelp.dll" />
</assembly>
Notice the 'processorArchitecture' field. It was set to "amd64" instead of "x86". It's probably not always the cause, but in our case it was the root cause, so it may be helpful to some. For 64-bit runs, you'll want "amd64" in there.
An error has occured. Please see log file - eclipse juno
This instruction works 100% for me:
- Rename the Eclipse workspace name
- Start Eclipse (it will start successfully with empty workspace)
- Exit it and change workspace name to previous state(if ask to replace some files, press no)
- Start Eclipse again and Re import projects in current workspace
Enjoy!
How to Export-CSV of Active Directory Objects?
HI you can try this...
Try..
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation
Or
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer
Hope it works for you.
Determine whether a Access checkbox is checked or not
Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.
In Access, there are two types:
2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.
3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.
Minor quibble with the answers:
There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:
?Me!MyCheckBox.Value
?Me!MyCheckBox
The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:
If Me!MyCheckBox Then
...write one of these options:
If (Me!MyCheckBox) Then ' forces evaluation of the control
If Me!MyCheckBox = True Then
If (Me!MyCheckBox = True) Then
If (Me!MyCheckBox = Not False) Then
Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.
Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.
How to trigger Jenkins builds remotely and to pass parameters
In your Jenkins job configuration, tick the box named "This build is parameterized
", click the "Add Parameter
" button and select the "String Parameter
" drop down value.
Now define your parameter - example:
Now you can use your parameter in your job / build pipeline, example:
Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):
http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value
Create HTTP post request and receive response using C# console application
Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.
Also microsoft recommends to use the HttpClient on this article
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
An example could look like this:
var client = new HttpClient();
var content = new MultipartFormDataContent
{
{ new StringContent("myUserId"), "userid"},
{ new StringContent("myFileName"), "filename"},
{ new StringContent("myPassword"), "password"},
{ new StringContent("myType"), "type"}
};
var responseMessage = await client.PostAsync("some url", content);
var stream = await responseMessage.Content.ReadAsStreamAsync();
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I'll try to give the benchmark of the three most common way (also mentioned above):
from timeit import repeat
setup = """
import numpy as np;
import random;
x = np.linspace(0,100);
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) * (x <= ub)]', 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'
for _ in range(3):
for stmt in stmts:
t = min(repeat(stmt, setup, number=100_000))
print('%.4f' % t, stmt)
print()
result:
0.4808 x[(x > lb) * (x <= ub)]
0.4726 x[(x > lb) & (x <= ub)]
0.4904 x[np.logical_and(x > lb, x <= ub)]
0.4725 x[(x > lb) * (x <= ub)]
0.4806 x[(x > lb) & (x <= ub)]
0.5002 x[np.logical_and(x > lb, x <= ub)]
0.4781 x[(x > lb) * (x <= ub)]
0.4336 x[(x > lb) & (x <= ub)]
0.4974 x[np.logical_and(x > lb, x <= ub)]
But, *
is not supported in Panda Series, and NumPy Array is faster than pandas data frame (arround 1000 times slower, see number):
from timeit import repeat
setup = """
import numpy as np;
import random;
import pandas as pd;
x = pd.DataFrame(np.linspace(0,100));
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'
for _ in range(3):
for stmt in stmts:
t = min(repeat(stmt, setup, number=100))
print('%.4f' % t, stmt)
print()
result:
0.1964 x[(x > lb) & (x <= ub)]
0.1992 x[np.logical_and(x > lb, x <= ub)]
0.2018 x[(x > lb) & (x <= ub)]
0.1838 x[np.logical_and(x > lb, x <= ub)]
0.1871 x[(x > lb) & (x <= ub)]
0.1883 x[np.logical_and(x > lb, x <= ub)]
Note: adding one line of code x = x.to_numpy()
will need about 20 µs.
For those who prefer %timeit
:
import numpy as np
import random
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
lb, ub
x = pd.DataFrame(np.linspace(0,100))
def asterik(x):
x = x.to_numpy()
return x[(x > lb) * (x <= ub)]
def and_symbol(x):
x = x.to_numpy()
return x[(x > lb) & (x <= ub)]
def numpy_logical(x):
x = x.to_numpy()
return x[np.logical_and(x > lb, x <= ub)]
for i in range(3):
%timeit asterik(x)
%timeit and_symbol(x)
%timeit numpy_logical(x)
print('\n')
result:
23 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
35.6 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
31.3 µs ± 8.9 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.4 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
21.9 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.7 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
25.1 µs ± 3.71 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
36.8 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
28.2 µs ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
SQL Plus change current directory
I don't think you can!
/home/export/user1 $ sqlplus /
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql
script2.sql has to be in /home/export/user1
.
You either use the full path, or exit the script and start sqlplus
again from the right directory.
#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql
(something like that - doing this from memory!)
How does Django's Meta class work?
Extending on Tadeck's Django answer above, the use of 'class Meta:' in Django is just normal Python too.
The internal class is a convenient namespace for shared data among the class instances (hence the name Meta for 'metadata' but you can call it anything you like). While in Django it's generally read-only configuration stuff, there is nothing to stop you changing it:
In [1]: class Foo(object):
...: class Meta:
...: metaVal = 1
...:
In [2]: f1 = Foo()
In [3]: f2 = Foo()
In [4]: f1.Meta.metaVal
Out[4]: 1
In [5]: f2.Meta.metaVal = 2
In [6]: f1.Meta.metaVal
Out[6]: 2
In [7]: Foo.Meta.metaVal
Out[7]: 2
You can explore it in Django directly too e.g:
In [1]: from django.contrib.auth.models import User
In [2]: User.Meta
Out[2]: django.contrib.auth.models.Meta
In [3]: User.Meta.__dict__
Out[3]:
{'__doc__': None,
'__module__': 'django.contrib.auth.models',
'abstract': False,
'verbose_name': <django.utils.functional.__proxy__ at 0x26a6610>,
'verbose_name_plural': <django.utils.functional.__proxy__ at 0x26a6650>}
However, in Django you are more likely to want to explore the _meta
attribute which is an Options
object created by the model metaclass
when a model is created. That is where you'll find all of the Django class 'meta' information. In Django, Meta
is just used to pass information into the process of creating the _meta
Options
object.
How can I trim leading and trailing white space?
I created a trim.strings ()
function to trim leading and/or trailing whitespace as:
# Arguments: x - character vector
# side - side(s) on which to remove whitespace
# default : "both"
# possible values: c("both", "leading", "trailing")
trim.strings <- function(x, side = "both") {
if (is.na(match(side, c("both", "leading", "trailing")))) {
side <- "both"
}
if (side == "leading") {
sub("^\\s+", "", x)
} else {
if (side == "trailing") {
sub("\\s+$", "", x)
} else gsub("^\\s+|\\s+$", "", x)
}
}
For illustration,
a <- c(" ABC123 456 ", " ABC123DEF ")
# returns string without leading and trailing whitespace
trim.strings(a)
# [1] "ABC123 456" "ABC123DEF"
# returns string without leading whitespace
trim.strings(a, side = "leading")
# [1] "ABC123 456 " "ABC123DEF "
# returns string without trailing whitespace
trim.strings(a, side = "trailing")
# [1] " ABC123 456" " ABC123DEF"
How to disable phone number linking in Mobile Safari?
My experience is the same as some others mentioned. The meta tag...
<meta name = "format-detection" content = "telephone=no">
...works when the website is running in Mobile Safari (i.e., with chrome) but stops working when run as a webapp (i.e., is saved to home screen and runs without chrome).
My less-than-ideal solution is to insert the values into input fields...
<input type="text" readonly="readonly" style="border:none;" value="3105551212">
It's less than ideal because, despite the border being set to none, iOS renders a multi-pixel gray bar above the field. But, it's better than seeing the number as a link.
update one table with data from another
Oracle 11g R2:
create table table1 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
create table table2 (
id number,
name varchar2(10),
desc_ varchar2(10)
);
insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');
insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');
merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;
select * from table1;
ID NAME DESC_
---------- ---------- ----------
1 x 123
2 y 456
3 c ghi
See also Oracle - Update statement with inner join.
Difference between git pull and git pull --rebase
Suppose you have two commits in local branch:
D---E master
/
A---B---C---F origin/master
After "git pull", will be:
D--------E
/ \
A---B---C---F----G master, origin/master
After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:
A---B---C---F---D'---E' master, origin/master
Npm Please try using this command again as root/administrator
WHAT WORKED FOR ME
I ran Command Prompt as Administrator. This helped partially - as I no longer got the error, "Please try using this command again as root/administrator". I was trying to install Cordova. To do it successfully, I also had to do the following:
(1) "npm update node", plus...
(2) I also added the " -g " in the >>npm install cordova<<. In other words, type this: >>npm install -g cordova<<
~~~ FOR WINDOWS 8.1 ~~~
"RUN AS ADMINISTRATOR" COMMAND PROMPT
For windows 8.1, I don't have an ACCESSORIES group when I click START > ALL PROGRAMS. But I do have that older -- but trusty and reliable -- START BUTTON and START MENU - thanks to the free Classic Start Menu app. So, with that installed....
ALTERNATIVE #1:
1. Type "cmd" in the SEARCH BOX at the bottom of the START menu.
2. When cmd.exe shows up in the top of the search results, right click it and select RUN AS ADMINISTRATOR.
ALTERNATIVE #2 If you already have a Command Prompt window open and running - and you want to open another one to Run As Administrator:
1. Locate the Command Prompt app icon in the Taskbar (usually along the bottom of you screen unless you have moved it a different dock/location).
2. Right click the app icon.
3. Now, right click "COMMAND PROMPT" and select RUN AS ADMINISTRATOR.
Hope this helps someone.
How to monitor SQL Server table changes by using c#?
Use SqlTableDependency. It is a c# component raising events when a record is changes.
You can find others detail at: https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency
It is similat to .NET SqlDependency except that SqlTableDependency raise events containing modified / deleted or updated database table values:
string conString = "data source=.;initial catalog=myDB;integrated security=True";
using(var tableDependency = new SqlTableDependency<Customers>(conString))
{
tableDependency.OnChanged += TableDependency_Changed;
tableDependency.Start();
Console.WriteLine("Waiting for receiving notifications...");
Console.WriteLine("Press a key to stop");
Console.ReadKey();
}
...
...
void TableDependency_Changed(object sender, RecordChangedEventArgs<Customers> e)
{
if (e.ChangeType != ChangeType.None)
{
var changedEntity = e.Entity;
Console.WriteLine("DML operation: " + e.ChangeType);
Console.WriteLine("ID: " + changedEntity.Id);
Console.WriteLine("Name: " + changedEntity.Name);
Console.WriteLine("Surname: " + changedEntity.Surname);
}
}
Referencing Row Number in R
These are present by default as rownames
when you create a data.frame
.
R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
a b c
1 0.3336944 0.39746731 a
2 -0.2334404 0.12242856 b
3 1.4886706 0.07984085 c
4 -1.4853724 0.83163342 d
5 0.7291344 0.10981827 e
6 0.1786753 0.47401690 f
7 -0.9173701 0.73992239 g
8 0.7805941 0.91925413 h
9 0.2469860 0.87979229 i
10 1.2810961 0.53289335 j
and you can access them via the rownames
command.
R> rownames(df)
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
if you need them as numbers, simply coerce to numeric by adding as.numeric
, as in as.numeric(rownames(df))
.
You don't need to add them, as if you know what you are looking for (say item df$c == 'i'
, you can use the which command:
R> which(df$c =='i')
[1] 9
or if you don't know the column
R> which(df == 'i', arr.ind=T)
row col
[1,] 9 3
you may access the element using df[9, 'c']
, or df$c[9]
.
If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df))
, though this may be less robust than df$rownumber <- 1:nrow(df)
as there are cases when you might have assigned to rownames
so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames
).
Print new output on same line
Lets take an example where you want to print numbers from 0 to n in the same line. You can do this with the help of following code.
n=int(raw_input())
i=0
while(i<n):
print i,
i = i+1
At input, n = 5
Output : 0 1 2 3 4
File path for project files?
I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:
- added the file
test.txt
to my test project
- on the solution explorer hit
alt-enter
(file properties)
- there I set
BuildAction
to Content
and Copy to Output Directory
to Copy if newer
, I guess Copy always
would have done it as well
then on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt")
and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug
(or whatever configuration you are using) folder.
Hopes this helps someone
What's the difference between VARCHAR and CHAR?
CHAR
- Used to store character string value of fixed length.
- The maximum no. of characters the data type can hold is 255 characters.
- It's 50% faster than VARCHAR.
- Uses static memory allocation.
VARCHAR
- Used to store variable length alphanumeric data.
- The maximum this data type can hold is up to
- Pre-MySQL 5.0.3: 255 characters.
- Post-MySQL 5.0.3: 65,535 characters shared for the row.
- It's slower than CHAR.
- Uses dynamic memory allocation.
Checking if an input field is required using jQuery
A little bit of a more complete answer, inspired by the accepted answer:
$( '#form_id' ).submit( function( event ) {
event.preventDefault();
//validate fields
var fail = false;
var fail_log = '';
var name;
$( '#form_id' ).find( 'select, textarea, input' ).each(function(){
if( ! $( this ).prop( 'required' )){
} else {
if ( ! $( this ).val() ) {
fail = true;
name = $( this ).attr( 'name' );
fail_log += name + " is required \n";
}
}
});
//submit if fail never got set to true
if ( ! fail ) {
//process form here.
} else {
alert( fail_log );
}
});
In this case we loop all types of inputs and if they are required, we check if they have a value, and if not, a notice that they are required is added to the alert that will run.
Note that this, example assumes the form will be proceed inside the positive conditional via AJAX or similar. If you are submitting via traditional methods, move the second line, event.preventDefault();
to inside the negative conditional.
Regex remove all special characters except numbers?
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
Programmatically add new column to DataGridView
Here's a sample method that adds two extra columns programmatically to the grid view:
private void AddColumnsProgrammatically()
{
// I created these columns at function scope but if you want to access
// easily from other parts of your class, just move them to class scope.
// E.g. Declare them outside of the function...
var col3 = new DataGridViewTextBoxColumn();
var col4 = new DataGridViewCheckBoxColumn();
col3.HeaderText = "Column3";
col3.Name = "Column3";
col4.HeaderText = "Column4";
col4.Name = "Column4";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
}
A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)
For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:
// Note that this info scattered throughout the designer but can easily collected.
System.Windows.Forms.DataGridViewTextBoxColumn Column1;
System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
What is NODE_ENV and how to use it in Express?
Typically, you'd use the NODE_ENV
variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV
is set to production
or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error
:
app.get('/error', function(req, res) {
if ('production' !== app.get('env')) {
console.log("Forcing an error!");
}
throw new Error('TestError');
});
app.use(function (req, res, next) {
res.status(501).send("Error!")
})
Note that the latter app.use()
must be last, after all other method handlers!
If you set NODE_ENV
to production
before you start your server, and then send a GET /error
request to it, you should not see the text Forcing an error!
in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).
If, instead, you set NODE_ENV
to something else before starting your server, the opposite should happen.
In Linux, set the environment variable NODE_ENV like this:
export NODE_ENV='value'
Regex Email validation
To validate your email ID, you can simply create such method and use it.
public static bool IsValidEmail(string email)
{
var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
return !String.IsNullOrEmpty(email) && r.IsMatch(email);
}
This will return True / False. (Valid / Invalid Email Id)
How to concatenate multiple column values into a single column in Panda dataframe
@derchambers I found one more solution:
import pandas as pd
# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'
def eval_join(df, columns):
sum_elements = [f"df['{col}']" for col in list('1234')]
to_eval = "+ '_' + ".join(sum_elements)
return eval(to_eval)
#profile
%timeit df3 = eval_join(df, list('1234')) # 504 ms
Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?
I've found the answer regarding how to do this myself. Inside the model code, just put:
For Rails <= 2:
include ActionController::UrlWriter
For Rails 3:
include Rails.application.routes.url_helpers
This magically makes thing_path(self)
return the URL for the current thing, or other_model_path(self.association_to_other_model)
return some other URL.
Unordered List (<ul>) default indent
If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt>
tags, but not the indenting description <dd>
tags, neither of which produces a bullet.
<dl>
<dt>Item 1</dt>
<dt>Item 2</dt>
<dt>Item 3</dt>
</dl>
The output looks like this:
Item 1
Item 2
Item 3
How do you make a deep copy of an object?
Here is an easy example on how to deep clone any object:
Implement serializable first
public class CSVTable implements Serializable{
Table<Integer, Integer, String> table;
public CSVTable() {
this.table = HashBasedTable.create();
}
public CSVTable deepClone() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (CSVTable) ois.readObject();
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
}
}
And then
CSVTable table = new CSVTable();
CSVTable tempTable = table.deepClone();
is how you get the clone.
Swift apply .uppercaseString to only the first letter of a string
Credits to Leonardo Savio Dabus:
I imagine most use cases is to get Proper Casing:
import Foundation
extension String {
var toProper:String {
var result = lowercaseString
result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
return result
}
}
Generating Random Number In Each Row In Oracle Query
If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL
Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error
The error is trying to say that Chrome was cut off while the page was being sent. Your issue is trying to figure out why.
Apparently, this might be a known issue impacting a couple of versions of Chrome. As far as I can tell, it is an issue of these versions being massively sensitive to the content length of the chunk being sent and the expressed size of that chunk (I could be far off on that one). In short, a slightly imperfect headers issue.
On the other hand, it could be that the server does not send the terminal 0-length chunk. Which might be fixable with ob_flush();
. It is also possible that Chrome (or connection or something) is being slow. So when the connection is closed, the page is not yet loaded. I have no idea why this might happen.
Here is the paranoid programmers answer:
<?php
// ... your code
flush();
ob_flush();
sleep(2);
exit(0);
?>
In your case, it might be a case of the script timing out. I am not really sure why it should affect only you but it could be down to a bunch of race conditions? That's an utter guess. You should be able to test this by extending the script execution time.
<?php
// ... your while code
set_time_limit(30);
// ... more while code
?>
It also may be as simple as you need to update your Chrome install (as this problem is Chrome specific).
UPDATE: I was able to replicate this error (at last) when a fatal error was thrown while PHP (on the same localhost) was output buffering. I imagine the output was too badly mangled to be of much use (headers but little or no content).
Specifically, I accidentally had my code recursively calling itself until PHP, rightly, gave up. Thus, the server did not send the terminal 0-length chunk - which was the problem I identified earlier.
Disable a Button
Swift 5 / SwiftUI
Nowadays it's done like this.
Button(action: action) {
Text(buttonLabel)
}
.disabled(!isEnabled)
XML string to XML document
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output:
0002
0006
How to transform numpy.matrix or array to scipy sparse matrix
There are several sparse matrix classes in scipy.
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix
Any of them can do the conversion.
import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)
(0, 0) 1
(0, 2) 1
(1, 2) 1
See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .
What is an opaque response, and what purpose does it serve?
Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch
event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).
Dependency injection with Jersey 2.0
First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract )
. You can alternative chain .in( scope )
. Default scope of PerLookup
. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped
available
Also, instead of bind(Class).to(Class)
, you can also bind(Instance).to(Class)
, which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder
implementation in your web.xml (i.e. you're not using a ResourceConfig
), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature
:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
@Provider
public class Hk2Feature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The @Provider
annotation should allow the Feature
to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature
in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
and for general information from the Jersey documentation
UPDATE
Factories
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
@Context
private HttpHeaders headers;
@Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
@Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService
into your resource class.
What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?
I find it useful, because when I didn't know about env, before I started to write script I was doing this:
type nodejs > scriptname.js #or any other environment
and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env
is very useful. Maybe there are details with this, but this is my reason
How do you POST to a page using the PHP header() function?
private function sendHttpRequest($host, $path, $query, $port=80){
header("POST $path HTTP/1.1\r\n" );
header("Host: $host\r\n" );
header("Content-type: application/x-www-form-urlencoded\r\n" );
header("Content-length: " . strlen($query) . "\r\n" );
header("Connection: close\r\n\r\n" );
header($query);
}
This will get you right away
SFTP file transfer using Java JSch
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey
exception.
Get all parameters from JSP page
Even though this is an old question, I had to do something similar today but I prefer JSTL:
<c:forEach var="par" items="${paramValues}">
<c:if test="${fn:startsWith(par.key, 'question')}">
${par.key} = ${par.value[0]}; //whatever
</c:if>
</c:forEach>
Can I make a phone call from HTML on Android?
I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:
in your onCreate you'll need to use a webview and assign a WebViewClient, as below:
browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());
then handle the click on a phone number like this:
private class InternalWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("tel:") > -1) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
Let me know if you need more pointers.
How to set ID using javascript?
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
How do I use MySQL through XAMPP?
XAMPP Apache + MariaDB + PHP + Perl (X -any OS)
By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).
For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'
How ViewBag in ASP.NET MVC works
ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData.
ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.
e.g:
1. Creating ViewBag:
ViewBag.FirstName="John";
- Accessing View:
@ViewBag.FirstName.
Calculating how many days are between two dates in DB2?
Wouldn't it just be:
SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';
That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.
If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.
Android Spinner : Avoid onItemSelected calls during initialization
My solution:
protected boolean inhibit_spinner = true;
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
if (inhibit_spinner) {
inhibit_spinner = false;
}else {
if (getDataTask != null) getDataTask.cancel(true);
updateData();
}
}
Deploying Java webapp to Tomcat 8 running in Docker container
There's a oneliner for this one.
You can simply run,
docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
How to create a Jar file in Netbeans
I also tried to make an executable jar file that I could run with the following command:
java -jar <jarfile>
After some searching I found the following link:
Packaging and Deploying Desktop Java Applications
I set the project's main class:
- Right-click the project's node and choose Properties
- Select the Run panel and enter the main class in the Main Class field
- Click OK to close the Project Properties dialog box
- Clean and build project
Then in the fodler dist the newly created jar should be executable with the command I mentioned above.
Check if an element is a child of a parent
Vanilla 1-liner for IE8+:
parent !== child && parent.contains(child);
Here, how it works:
_x000D_
_x000D_
function contains(parent, child) {_x000D_
return parent !== child && parent.contains(child);_x000D_
}_x000D_
_x000D_
var parentEl = document.querySelector('#parent'),_x000D_
childEl = document.querySelector('#child')_x000D_
_x000D_
if (contains(parentEl, childEl)) {_x000D_
document.querySelector('#result').innerText = 'I confirm, that child is within parent el';_x000D_
}_x000D_
_x000D_
if (!contains(childEl, parentEl)) {_x000D_
document.querySelector('#result').innerText += ' and parent is not within child';_x000D_
}
_x000D_
<div id="parent">_x000D_
<div>_x000D_
<table>_x000D_
<tr>_x000D_
<td><span id="child"></span></td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_
ASP.NET jQuery Ajax Calling Code-Behind Method
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
Develop Android app using C#
Having used Mono, I would NOT recommend it. The Mono runtime is bundled with your app, so your apk ends up being bloated at more than 6MB. A better programming solution for C# would be dot42. Both Mono and dot42 are licensed products.
Personally, I would recommend using Java with the IntelliJ IDEA dev environment. I say this for 3 reasons:
- There is so much Java code out there for Android already; do yourself a favour and don't re-invent the wheel.
- IDEA is similar enough to Visual Studio as to be a cinch to learn; it is made by JetBrains and the intelli-sense is better than VS.
- IDEA is free.
I have been a C# programmer for 12 years and started developing for Android with C# but ended up jumping ship and going the Java route. The languages are so similar you really won't notice much of a learning curve.
P.S. If you want to use LINQ, serialization and other handy features that are native to C# then you just need to look for the equivalent java library.
Retrieving Property name from lambda expression
public string GetName<TSource, TField>(Expression<Func<TSource, TField>> Field)
{
return (Field.Body as MemberExpression ?? ((UnaryExpression)Field.Body).Operand as MemberExpression).Member.Name;
}
This handles member and unary expressions. The difference being that you will get a UnaryExpression
if your expression represents a value type whereas you will get a MemberExpression
if your expression represents a reference type. Everything can be cast to an object, but value types must be boxed. This is why the UnaryExpression exists. Reference.
For the sakes of readability (@Jowen), here's an expanded equivalent:
public string GetName<TSource, TField>(Expression<Func<TSource, TField>> Field)
{
if (object.Equals(Field, null))
{
throw new NullReferenceException("Field is required");
}
MemberExpression expr = null;
if (Field.Body is MemberExpression)
{
expr = (MemberExpression)Field.Body;
}
else if (Field.Body is UnaryExpression)
{
expr = (MemberExpression)((UnaryExpression)Field.Body).Operand;
}
else
{
const string Format = "Expression '{0}' not supported.";
string message = string.Format(Format, Field);
throw new ArgumentException(message, "Field");
}
return expr.Member.Name;
}
Rename multiple files by replacing a particular pattern in the filenames using a shell script
find . -type f |
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" |
xargs -p -n 2 mv
eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"
explanation:
1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"
2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)
example output:
foo_factory.py foo_service.py
bar_factory.py bar_service.py
3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.
How to get 'System.Web.Http, Version=5.2.3.0?
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Then in the project Add Reference -> Browse. Push the browse button and go to the
C:\Users\UserName\Documents\Visual Studio 2015\Projects\ProjectName\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45 and add the needed .dll file
Python element-wise tuple operations like sum
Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
Note: using self.__class__
instead of stuple
to ease subclassing.
Refresh Page and Keep Scroll Position
this will do the magic
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
window.onbeforeunload = function(e) {
localStorage.setItem('scrollpos', window.scrollY);
};
</script>
Checking if a list is empty with LINQ
Ok, so what about this one?
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
return !enumerable.GetEnumerator().MoveNext();
}
EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards
How is VIP swapping + CNAMEs better than IP swapping + A records?
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
SQL statement to select all rows from previous day
get today no time:
SELECT dateadd(day,datediff(day,0,GETDATE()),0)
get yestersday no time:
SELECT dateadd(day,datediff(day,1,GETDATE()),0)
query for all of rows from only yesterday:
select
*
from yourTable
WHERE YourDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND YourDate < dateadd(day,datediff(day,0,GETDATE()),0)
database attached is read only
Another Way which worked for me is:
After dettaching before you attach
List item
-> if not there than click on edit button
-> click on add button
and enter\search NT SERVICE\MSSQLSERVER
then attach
Using custom std::set comparator
1. Modern C++20 solution
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
Online demo
2. Modern C++11 solution
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Online demo
3. Similar to first solution, but with function instead of lambda
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
Online demo
or this way:
std::set<int, decltype(&cmp)> s(&cmp);
Online demo
4. Old solution using struct with ()
operator
struct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
Online demo
5. Alternative solution: create struct from boolean function
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
Finally, use the struct as comparator
std::set<X, Cmp> set;
Online demo
Bootstrap modal z-index
I found this question as I had a similar problem. While data-backdrop
does "solve" the issue; I found another problem in my markup.
I had the button which launched this modal and the modal dialog itself was in the footer. The problem is that the footer was defined as navbar_fixed_bottom
, and that contained position:fixed
.
After I moved the dialog outside of the fixed section, everything worked as expected.
Get current cursor position in a textbox
Here's one possible method.
function isMouseInBox(e) {
var textbox = document.getElementById('textbox');
// Box position & sizes
var boxX = textbox.offsetLeft;
var boxY = textbox.offsetTop;
var boxWidth = textbox.offsetWidth;
var boxHeight = textbox.offsetHeight;
// Mouse position comes from the 'mousemove' event
var mouseX = e.pageX;
var mouseY = e.pageY;
if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
if(mouseY>=boxY && mouseY<=boxY+boxHeight){
// Mouse is in the box
return true;
}
}
}
document.addEventListener('mousemove', function(e){
isMouseInBox(e);
})
Javascript Object push() function
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
Jenkins Pipeline Wipe Out Workspace
The mentioned solutions deleteDir()
and cleanWs()
(if using the workspace cleanup plugin) both work, but the recommendation to use it in an extra build step is usually not the desired solution. If the build fails and the pipeline is aborted, this cleanup-stage is never reached and therefore the workspace is not cleaned on failed builds.
=> In most cases you should probably put it in a post-built-step condition like always
:
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
post {
always {
cleanWs()
}
}
}
Find duplicate records in MySQL
This will select duplicates in one table pass, no subqueries.
SELECT *
FROM (
SELECT ao.*, (@r := @r + 1) AS rn
FROM (
SELECT @_address := 'N'
) vars,
(
SELECT *
FROM
list a
ORDER BY
address, id
) ao
WHERE CASE WHEN @_address <> address THEN @r := 0 ELSE 0 END IS NOT NULL
AND (@_address := address ) IS NOT NULL
) aoo
WHERE rn > 1
This query actially emulates ROW_NUMBER()
present in Oracle
and SQL Server
See the article in my blog for details:
Reading data from a website using C#
The WebClient class should be more than capable of handling the functionality you describe, for example:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
string webData = System.Text.Encoding.UTF8.GetString(raw);
or (further to suggestion from Fredrick in comments)
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.
You could go a level lower and implement something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(requestData);
}
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
Insert/Update/Delete with function in SQL Server
Just another alternative using sp_executesql (tested only in SQL 2016).
As previous posts noticed, atomicity must be handled elsewhere.
CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
@ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;
design a stack such that getMinimum( ) should be O(1)
I am posting the complete code here to find min and max in a given stack.
Time complexity will be O(1)..
package com.java.util.collection.advance.datastructure;
/**
*
* @author vsinha
*
*/
public abstract interface Stack<E> {
/**
* Placing a data item on the top of the stack is called pushing it
* @param element
*
*/
public abstract void push(E element);
/**
* Removing it from the top of the stack is called popping it
* @return the top element
*/
public abstract E pop();
/**
* Get it top element from the stack and it
* but the item is not removed from the stack, which remains unchanged
* @return the top element
*/
public abstract E peek();
/**
* Get the current size of the stack.
* @return
*/
public abstract int size();
/**
* Check whether stack is empty of not.
* @return true if stack is empty, false if stack is not empty
*/
public abstract boolean empty();
}
package com.java.util.collection.advance.datastructure;
@SuppressWarnings("hiding")
public abstract interface MinMaxStack<Integer> extends Stack<Integer> {
public abstract int min();
public abstract int max();
}
package com.java.util.collection.advance.datastructure;
import java.util.Arrays;
/**
*
* @author vsinha
*
* @param <E>
*/
public class MyStack<E> implements Stack<E> {
private E[] elements =null;
private int size = 0;
private int top = -1;
private final static int DEFAULT_INTIAL_CAPACITY = 10;
public MyStack(){
// If you don't specify the size of stack. By default, Stack size will be 10
this(DEFAULT_INTIAL_CAPACITY);
}
@SuppressWarnings("unchecked")
public MyStack(int intialCapacity){
if(intialCapacity <=0){
throw new IllegalArgumentException("initial capacity can't be negative or zero");
}
// Can't create generic type array
elements =(E[]) new Object[intialCapacity];
}
@Override
public void push(E element) {
ensureCapacity();
elements[++top] = element;
++size;
}
@Override
public E pop() {
E element = null;
if(!empty()) {
element=elements[top];
// Nullify the reference
elements[top] =null;
--top;
--size;
}
return element;
}
@Override
public E peek() {
E element = null;
if(!empty()) {
element=elements[top];
}
return element;
}
@Override
public int size() {
return size;
}
@Override
public boolean empty() {
return size == 0;
}
/**
* Increases the capacity of this <tt>Stack by double of its current length</tt> instance,
* if stack is full
*/
private void ensureCapacity() {
if(size != elements.length) {
// Don't do anything. Stack has space.
} else{
elements = Arrays.copyOf(elements, size *2);
}
}
@Override
public String toString() {
return "MyStack [elements=" + Arrays.toString(elements) + ", size="
+ size + ", top=" + top + "]";
}
}
package com.java.util.collection.advance.datastructure;
/**
* Time complexity will be O(1) to find min and max in a given stack.
* @author vsinha
*
*/
public class MinMaxStackFinder extends MyStack<Integer> implements MinMaxStack<Integer> {
private MyStack<Integer> minStack;
private MyStack<Integer> maxStack;
public MinMaxStackFinder (int intialCapacity){
super(intialCapacity);
minStack =new MyStack<Integer>();
maxStack =new MyStack<Integer>();
}
public void push(Integer element) {
// Current element is lesser or equal than min() value, Push the current element in min stack also.
if(!minStack.empty()) {
if(min() >= element) {
minStack.push(element);
}
} else{
minStack.push(element);
}
// Current element is greater or equal than max() value, Push the current element in max stack also.
if(!maxStack.empty()) {
if(max() <= element) {
maxStack.push(element);
}
} else{
maxStack.push(element);
}
super.push(element);
}
public Integer pop(){
Integer curr = super.pop();
if(curr !=null) {
if(min() == curr) {
minStack.pop();
}
if(max() == curr){
maxStack.pop();
}
}
return curr;
}
@Override
public int min() {
return minStack.peek();
}
@Override
public int max() {
return maxStack.peek();
}
@Override
public String toString() {
return super.toString()+"\nMinMaxStackFinder [minStack=" + minStack + "\n maxStack="
+ maxStack + "]" ;
}
}
// You can use the below program to execute it.
package com.java.util.collection.advance.datastructure;
import java.util.Random;
public class MinMaxStackFinderApp {
public static void main(String[] args) {
MinMaxStack<Integer> stack =new MinMaxStackFinder(10);
Random random =new Random();
for(int i =0; i< 10; i++){
stack.push(random.nextInt(100));
}
System.out.println(stack);
System.out.println("MAX :"+stack.max());
System.out.println("MIN :"+stack.min());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack);
System.out.println("MAX :"+stack.max());
System.out.println("MIN :"+stack.min());
}
}
Let me know if you are facing any issue
Thanks,
Vikash
Using jquery to get all checked checkboxes with a certain class name
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
An example to demonstrate.
:checkbox
is a selector for checkboxes (in fact, you could omit the input
part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions).
.class
is the selector for element class attribute containing class
.
Parsing a YAML file in Python, and accessing the data?
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
Alter and Assign Object Without Side Effects
Objects are passed by reference.. To create a new object, I follow this approach..
//Template code for object creation.
function myElement(id, value) {
this.id = id;
this.value = value;
}
var myArray = [];
//instantiate myEle
var myEle = new myElement(0, 0);
//store myEle
myArray[0] = myEle;
//Now create a new object & store it
myEle = new myElement(0, 1);
myArray[1] = myEle;
Convert string to integer type in Go?
If you control the input data, you can use the mini version
package main
import (
"testing"
"strconv"
)
func Atoi (s string) int {
var (
n uint64
i int
v byte
)
for ; i < len(s); i++ {
d := s[i]
if '0' <= d && d <= '9' {
v = d - '0'
} else if 'a' <= d && d <= 'z' {
v = d - 'a' + 10
} else if 'A' <= d && d <= 'Z' {
v = d - 'A' + 10
} else {
n = 0; break
}
n *= uint64(10)
n += uint64(v)
}
return int(n)
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in := Atoi("9999")
_ = in
}
}
func BenchmarkStrconvAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
in, _ := strconv.Atoi("9999")
_ = in
}
}
the fastest option (write your check if necessary). Result :
Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2 100000000 14.6 ns/op
BenchmarkStrconvAtoi-2 30000000 51.2 ns/op
PASS
ok path 3.293s
How to Copy Text to Clip Board in Android?
Yesterday I made this class. Take it, it's for all API Levels
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;
import de.lochmann.nsafirewall.R;
public class MyClipboardManager {
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText(
context.getResources().getString(
R.string.message), text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
@SuppressLint("NewApi")
public String readFromClipboard(Context context) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
} else {
ClipboardManager clipboard = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
// Gets a content resolver instance
ContentResolver cr = context.getContentResolver();
// Gets the clipboard data from the clipboard
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
String text = null;
String title = null;
// Gets the first item from the clipboard data
ClipData.Item item = clip.getItemAt(0);
// Tries to get the item's contents as a URI pointing to a note
Uri uri = item.getUri();
// If the contents of the clipboard wasn't a reference to a
// note, then
// this converts whatever it is to text.
if (text == null) {
text = coerceToText(context, item).toString();
}
return text;
}
}
return "";
}
@SuppressLint("NewApi")
public CharSequence coerceToText(Context context, ClipData.Item item) {
// If this Item has an explicit textual value, simply return that.
CharSequence text = item.getText();
if (text != null) {
return text;
}
// If this Item has a URI value, try using that.
Uri uri = item.getUri();
if (uri != null) {
// First see if the URI can be opened as a plain text stream
// (of any sub-type). If so, this is the best textual
// representation for it.
FileInputStream stream = null;
try {
// Ask for a stream of the desired type.
AssetFileDescriptor descr = context.getContentResolver()
.openTypedAssetFileDescriptor(uri, "text/*", null);
stream = descr.createInputStream();
InputStreamReader reader = new InputStreamReader(stream,
"UTF-8");
// Got it... copy the stream into a local string and return it.
StringBuilder builder = new StringBuilder(128);
char[] buffer = new char[8192];
int len;
while ((len = reader.read(buffer)) > 0) {
builder.append(buffer, 0, len);
}
return builder.toString();
} catch (FileNotFoundException e) {
// Unable to open content URI as text... not really an
// error, just something to ignore.
} catch (IOException e) {
// Something bad has happened.
Log.w("ClippedData", "Failure loading text", e);
return e.toString();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
// If we couldn't open the URI as a stream, then the URI itself
// probably serves fairly well as a textual representation.
return uri.toString();
}
// Finally, if all we have is an Intent, then we can just turn that
// into text. Not the most user-friendly thing, but it's something.
Intent intent = item.getIntent();
if (intent != null) {
return intent.toUri(Intent.URI_INTENT_SCHEME);
}
// Shouldn't get here, but just in case...
return "";
}
}
html 5 audio tag width
Set it the same way you'd set the width of any other HTML element, with CSS:
audio { width: 200px; }
Note that audio
is an inline element by default in Firefox, so you might also want to set it to display: block
. Here's an example.
Android: resizing imageview in XML
Please try this one works for me:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:layout_gravity="center"
android:maxHeight="60dp"
android:scaleType="fitCenter"
android:src="@drawable/icon"
/>
Are lists thread-safe?
To clarify a point in Thomas' excellent answer, it should be mentioned that append()
is thread safe.
This is because there is no concern that data being read will be in the same place once we go to write to it. The append()
operation does not read data, it only writes data to the list.
Get property value from C# dynamic object by string (reflection?)
Thought this might help someone in the future.
If you know the property name already, you can do something like the following:
[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
var stringValue = args.MyPropertyName.ToString();
//do something with the string value. If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
//some more code here....
return stringValue;
}
What does the ">" (greater-than sign) CSS selector mean?
>
(greater-than sign) is a CSS Combinator.
A combinator is something that explains the relationship between the selectors.
A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
There are four different combinators in CSS3:
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
Note: <
is not valid in CSS selectors.
For example:
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<span><p>Paragraph 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Output:
More information about CSS Combinators
How to define static property in TypeScript interface
The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:
interface AppPackageCheck<T> {
new (packageExists: boolean): T
checkIfPackageExists(): boolean;
}
class WebApp {
public static checkIfPackageExists(): boolean {
return false;
}
constructor(public packageExists: boolean) {}
}
class BackendApp {
constructor(public packageExists: boolean) {}
}
function createApp<T>(type: AppPackageCheck<T>): T {
const packageExists = type.checkIfPackageExists();
return new type(packageExists)
}
let web = createApp(WebApp);
// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp);
SQL Server: IF EXISTS ; ELSE
EDIT
I want to add the reason that your IF
statement seems to not work. When you do an EXISTS
on an aggregate, it's always going to be true
. It returns a value even if the ID
doesn't exist. Sure, it's NULL
, but its returning it. Instead, do this:
if exists(select 1 from table where id = 4)
and you'll get to the ELSE
portion of your IF
statement.
Now, here's a better, set-based solution:
update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid
This has the benefit of being able to run on the entire table rather than individual ids.
NameError: name 'reduce' is not defined in Python
In this case I believe that the following is equivalent:
l = sum([1,2,3,4]) % 2
The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?
pandas get rows which are NOT in other dataframe
My way of doing this involves adding a new column that is unique to one dataframe and using this to choose whether to keep an entry
df2[col3] = 1
df1 = pd.merge(df_1, df_2, on=['field_x', 'field_y'], how = 'outer')
df1['Empt'].fillna(0, inplace=True)
This makes it so every entry in df1 has a code - 0 if it is unique to df1, 1 if it is in both dataFrames. You then use this to restrict to what you want
answer = nonuni[nonuni['Empt'] == 0]
Ubuntu: Using curl to download an image
For those who don't have nor want to install wget, curl -O
(capital "o", not a zero) will do the same thing as wget
. E.g. my old netbook doesn't have wget, and is a 2.68 MB install that I don't need.
curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
Portable way to get file size (in bytes) in shell?
If you use find
from GNU fileutils:
size=$( find . -maxdepth 1 -type f -name filename -printf '%s' )
Unfortunately, other implementations of find
usually don't support -maxdepth
, nor -printf
. This is the case for e.g. Solaris and macOS find
.