Laravel - check if Ajax request
$request->wantsJson()
You can try $request->wantsJson()
if $request->ajax()
does not work
$request->ajax()
works if your JavaScript library sets an X-Requested-With HTTP header.
By default Laravel set this header in js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
In my case, I used a different frontend code and I had to put this header manually for $request->ajax()
to work.
But $request->wantsJson()
will check the axios query without the need for a header X-Requested-With
:
// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or
\Request::wantsJson() // not \Illuminate\Http\Request
How do I add button on each row in datatable?
I contribute with my settings for buttons: view, edit and delete.
The last column has data: null
At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
enter image description here
Jquery ajax call click event submit button
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
call a function in success of datatable ajax call
You can use dataSrc :
Here is a typical example of datatables.net
var table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "ajax.php",
"dataSrc": function ( json ) {
//Make your callback here.
alert("Done!");
return json.data;
}
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
MVC Return Partial View as JSON
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
What does `unsigned` in MySQL mean and when to use it?
MySQL says:
All integer types can have an optional
(nonstandard) attribute UNSIGNED.
Unsigned type can be used to permit
only nonnegative numbers in a column
or when you need a larger upper
numeric range for the column. For
example, if an INT column is UNSIGNED,
the size of the column's range is the
same but its endpoints shift from
-2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Boolean vs tinyint(1) for boolean values in MySQL
Whenever you choose int or bool it matters especially when nullable column comes into play.
Imagine a product with multiple photos. How do you know which photo serves as a product cover? Well, we would use a column that indicates it.
So far out product_image
table has two columns: product_id
and is_cover
Cool? Not yet. Since the product can have only one cover we need to add a unique index on these two columns.
But wait, if these two column will get an unique index how would you store many non-cover images for the same product? The unique index would throw an error here.
So you may though "Okay, but you can use NULL value since these are ommited by unique index checks", and yes this is truth, but we are loosing linguistic rules here.
What is the purpose of NULL value in boolean type column? Is it "all", "any", or "no"? The null value in boolean column allows us to use the unique index, but it also messes up how we interpret the records.
I would tell that in some cases the integer can serve a better purpose since its not bound to strict true or false meaning
Difference between Xms and Xmx and XX:MaxPermSize
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
References:
How is the java memory pool divided?
What is perm space?
Java (JVM) Memory Model – Memory Management in Java
Java 7 SE Command Line Options
Java 7 HotSpot VM Options
Visualizing decision tree in scikit-learn
Here is one liner for those who are using jupyter and sklearn(18.2+) You don't even need matplotlib
for that. Only requirement is graphviz
pip install graphviz
than run (according to code in question X is a pandas DataFrame)
from graphviz import Source
from sklearn import tree
Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
This will display it in SVG format. Code above produces Graphviz's Source object (source_code - not scary) That would be rendered directly in jupyter.
Some things you are likely to do with it
Display it in jupter:
from IPython.display import SVG
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
SVG(graph.pipe(format='svg'))
Save as png:
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
graph.format = 'png'
graph.render('dtree_render',view=True)
Get the png image, save it and view it:
graph = Source( tree.export_graphviz(dtreg, out_file=None, feature_names=X.columns))
png_bytes = graph.pipe(format='png')
with open('dtree_pipe.png','wb') as f:
f.write(png_bytes)
from IPython.display import Image
Image(png_bytes)
If you are going to play with that lib here are the links to examples and userguide
How do I export an Android Studio project?
It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).
Eclipse had the ability to export zip files which could be sent over email for example.
If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable.
Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.
Here's a solution though:
You can use source control. Android Studio supports that. Your code will be stored online.
A git will do the trick. Look under "VCS" in the top menu in Android Studio.
It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.
Kubernetes how to make Deployment to update image
kubectl rollout restart deployment myapp
This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout
like rollbacks.
Override element.style using CSS
Use JavaScript.
For example:
var elements = document.getElementById("demoFour").getElementsByTagName("li");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "inline";
}
Align Bootstrap Navigation to Center
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Updated Fiddle
Since You Have used the float
property we don't have many options except to adjust it manually.
display: inline-block extra margin
Can you post a link to the HTML in question?
Ultimately you should be able to do:
div {
margin:0;
padding: 0;
}
to remove the spacing. Is this just in one particular browser or all of them?
The network path was not found
Same problem with me. I solved this by adding @
before connection string (C# has a thing called 'String Literals') like so:
SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");
sconnection.Open();
Get Selected Item Using Checkbox in Listview
You have to add an OnItemClickListener to the listview to determine which item was clicked, then find the checkbox.
mListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox_id);
}
});
what is the difference between GROUP BY and ORDER BY in sql
They have totally different meaning and aren't really related at all.
ORDER BY allows you to sort the result set according to different criteria, such as first sort by name from a-z, then sort by the price highest to lowest.
(ORDER BY name, price DESC)
GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on those groups. You could for instance select all employees, group them by their workplace location and calculate the average salary of all employees of each workplace location.
How to use paginator from material angular?
Hey so I stumbled upon this and got it working, here is how:
inside my component.html
<mat-paginator #paginator [pageSize]="pageSize" [pageSizeOptions]="[5, 10, 20]" [showFirstLastButtons]="true" [length]="totalSize"
[pageIndex]="currentPage" (page)="pageEvent = handlePage($event)">
</mat-paginator>
Inside my component.ts
public array: any;
public displayedColumns = ['', '', '', '', ''];
public dataSource: any;
public pageSize = 10;
public currentPage = 0;
public totalSize = 0;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private app: AppService) { }
ngOnInit() {
this.getArray();
}
public handlePage(e: any) {
this.currentPage = e.pageIndex;
this.pageSize = e.pageSize;
this.iterator();
}
private getArray() {
this.app.getDeliveries()
.subscribe((response) => {
this.dataSource = new MatTableDataSource<Element>(response);
this.dataSource.paginator = this.paginator;
this.array = response;
this.totalSize = this.array.length;
this.iterator();
});
}
private iterator() {
const end = (this.currentPage + 1) * this.pageSize;
const start = this.currentPage * this.pageSize;
const part = this.array.slice(start, end);
this.dataSource = part;
}
All the paging work is done from within the iterator
method. This method works out the skip
and take
and assigns that to the dataSource
for the Material table.
Find object in list that has attribute equal to some value (that meets any condition)
Old question but I use this quite frequently (for version 3.8). It's a bit of syntactic salt, but it has the advantage over the top answer in that you could retrieve a list of results (if there are multiple) by simply removing the [0]
and it still defaults to None
if nothing is found. For any other condition, simply change the x.value==value
to what ever you're looking for.
_[0] if (_:=[x for x in test_list if x.value==value]) else None
How to filter empty or NULL names in a QuerySet?
You could do this:
Name.objects.exclude(alias__isnull=True)
If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:
Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')
Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias
is either null or an empty string, so you get all Name
objects that have a not-null, not-empty alias
field. The generated SQL would look something like:
SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""
You can also pass multiple arguments to a single call to exclude
, which would ensure that only objects that meet every condition get excluded:
Name.objects.exclude(some_field=True, other_field=True)
Here, rows in which some_field
and other_field
are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:
SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)
Alternatively, if your logic is more complex than that, you could use Django's Q objects:
from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))
For more info see this page and this page in the Django docs.
As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.
Is having an 'OR' in an INNER JOIN condition a bad idea?
This kind of JOIN
is not optimizable to a HASH JOIN
or a MERGE JOIN
.
It can be expressed as a concatenation of two resultsets:
SELECT *
FROM maintable m
JOIN othertable o
ON o.parentId = m.id
UNION
SELECT *
FROM maintable m
JOIN othertable o
ON o.id = m.parentId
, each of them being an equijoin, however, SQL Server
's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).
How to select true/false based on column value?
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
How to achieve pagination/table layout with Angular.js?
The best simple plug and play solution for pagination.
https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002
you would jus need to replace ng-repeat with custom directive.
<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>
Within the page u just need to add
<div align="center">
<dir-pagination-controls
max-size="100"
direction-links="true"
boundary-links="true" >
</dir-pagination-controls>
</div>
In your index.html load
<script src="./js/dirPagination.js"></script>
In your module just add dependencies
angular.module('userApp',['angularUtils.directives.dirPagination']);
and thats all needed for pagination.
Might be helpful for someone.
calling parent class method from child class object in java
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
@Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.
RSA: Get exponent and modulus given a public key
It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.
Command-line / OpenSSL
If you want to use something like OpenSSL on a unix command line, you can do something as follows.
I'm assuming you public.key file contains something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----
Then, the commands would be:
PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`
Then, you can look into the ASN.1 structure:
echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i
This should give you something like this:
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING
The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse
:
echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19
This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
265:d=1 hl=2 l= 3 prim: INTEGER :010001
That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.
Alternatively (and this might be easier to put into a script),
openssl rsa -pubin -inform PEM -text -noout < public.key
will return this:
Modulus (2048 bit):
00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
21:1d
Exponent: 65537 (0x10001)
Java
It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey()
: this object has two getters for the modulus and the exponent.
If it's in the format as above, you might want to use BouncyCastle and its PEMReader
to read it. I haven't tried the following code, but this would look more or less like this:
PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
// Just in case your file contains in fact an X.509 certificate,
// useless otherwise.
obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
// ... use the getters to get the BigIntegers.
}
(You can use BouncyCastle similarly in C# too.)
dropping rows from dataframe based on a "not in" condition
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
Pass command parameter to method in ViewModel in WPF?
Try this:
public class MyVmBase : INotifyPropertyChanged
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
}
}
public void MyAction(object message)
{
if(message == null)
{
Notify($"Method {message} not defined");
return;
}
switch (message.ToString())
{
case "btnAdd":
{
btnAdd_Click();
break;
}
case "BtnEdit_Click":
{
BtnEdit_Click();
break;
}
default:
throw new Exception($"Method {message} not defined");
break;
}
}
}
public class CommandHandler : ICommand
{
private Action<object> _action;
private Func<object, bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action<object> action, Func<object, bool> canExecute)
{
if (action == null) throw new ArgumentNullException(nameof(action));
_action = action;
_canExecute = canExecute ?? (x => true);
}
public CommandHandler(Action<object> action) : this(action, null)
{
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_action(parameter);
}
public void Refresh()
{
CommandManager.InvalidateRequerySuggested();
}
}
And in xaml:
<Button
Command="{Binding ClickCommand}"
CommandParameter="BtnEdit_Click"/>
load external URL into modal jquery ui dialog
I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.
var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
modal: true,
height: $("#body").height(),
width: $("#body").width()*.8
});
Vector erase iterator
Do not erase and then increment the iterator. No need to increment, if your vector has an odd (or even, I don't know) number of elements you will miss the end of the vector.
Remove last characters from a string in C#. An elegant way?
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
- I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
- Speed.
Programmatically navigate using react router V4
My answer is similar to Alex's. I'm not sure why React-Router made this so needlessly complicated. Why should I have to wrap my component with a HoC just to get access to what's essentially a global?
Anyway, if you take a look at how they implemented <BrowserRouter>
, it's just a tiny wrapper around history.
We can pull that history bit out so that we can import it from anywhere. The trick, however, is if you're doing server-side rendering and you try to import
the history module, it won't work because it uses browser-only APIs. But that's OK because we usually only redirect in response to a click or some other client-side event. Thus it's probably OK to fake it:
// history.js
if(__SERVER__) {
module.exports = {};
} else {
module.exports = require('history').createBrowserHistory();
}
With the help of webpack, we can define some vars so we know what environment we're in:
plugins: [
new DefinePlugin({
'__SERVER__': 'false',
'__BROWSER__': 'true', // you really only need one of these, but I like to have both
}),
And now you can
import history from './history';
From anywhere. It'll just return an empty module on the server.
If you don't want use these magic vars, you'll just have to require
in the global object where it's needed (inside your event handler). import
won't work because it only works at the top-level.
PHP session handling errors
check your cpanels space.remove unused file or error.log file & then try to login your application(This work for me);
What does it mean: The serializable class does not declare a static final serialVersionUID field?
The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.
Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).
If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial")
.
If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.
How to check if IEnumerable is null or empty?
I built this off of the answer by @Matt Greer
He answered the OP's question perfectly.
I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.
Specifically I wanted to still be able to pass in a predicate.
public static class Utilities
{
/// <summary>
/// Determines whether a sequence has a value and contains any elements.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
/// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
{
return source?.Any() == true;
}
/// <summary>
/// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
return source?.Any(predicate) == true;
}
}
The naming of the extension method could probably be better.
MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger
@gerrit_hoekstra wrote: "However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case."
That is correct but you can select the auto-increment field value that will be inserted by the subsequent INSERT quite easily. This is an example that works:
CREATE DEFINER = CURRENT_USER TRIGGER `lgffin`.`variable_BEFORE_INSERT` BEFORE INSERT
ON `variable` FOR EACH ROW
BEGIN
SET NEW.prefixed_id = CONCAT(NEW.fixed_variable, (SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'lgffin'
AND TABLE_NAME = 'variable'));
END
how to sort order of LEFT JOIN in SQL query?
Several other answer give the solution using MAX. In some scenarios using an agregate function is either not possilbe, or not performant.
The alternative that I use a lot is to use a correlated sub-query in the join...
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.id = (
SELECT id FROM `cars` WHERE BelongsToUser = users.id ORDER BY carPrice DESC LIMIT 1
)
WHERE `id`='4'
jQuery $.cookie is not a function
I had this problem as well. I found out that having a $(document).ready function that included a $.cookie in a script tag inside body while having cookie js load in the head BELOW jquery as intended resulted in $(document).ready beeing processed before the cookie plugin could finish loading.
I moved the cookie plugin load script in the body before the $(document).ready script and the error disappeared :D
Git: Pull from other remote
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
Java collections maintaining insertion order
Theres's a section in the O'Reilly Java Cookbook called "Avoiding the urge to sort" The question you should be asking is actually the opposite of your original question ... "Do we gain something by sorting?" It take a lot of effort to sort and maintain that order. Sure sorting is easy but it usually doesn't scale in most programs. If you're going to be handling thousands or tens of thousands of requests (insrt,del,get,etc) per second whether not you're using a sorted or non sorted data structure is seriously going to matter.
How can I search sub-folders using glob.glob module?
There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):
glob.glob('*.txt') :
matches all files ending in '.txt' in current directory
glob.glob('*/*.txt') :
same as 1
glob.glob('**/*.txt') :
matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
glob.glob('*.txt',recursive=True) :
same as 1
glob.glob('*/*.txt',recursive=True) :
same as 3
glob.glob('**/*.txt',recursive=True):
matches all files ending in '.txt' in the current directory and in all subdirectories
So it's best to always specify recursive=True.
Build .so file from .c file using gcc command line
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
subquery in codeigniter active record
Like this in simple way .
$this->db->select('*');
$this->db->from('certs');
$this->db->where('certs.id NOT IN (SELECT id_cer FROM revokace)');
return $this->db->get()->result();
read file from assets
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
What's the difference between :: (double colon) and -> (arrow) in PHP?
Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'
. My bad, I had a $instance::method()
that should have been $instance->method()
. Silly me.
The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.
So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.
If anybody can expand on why that is, please do.
How do I make a transparent border with CSS?
Yep, you can use border: 1px solid transparent
Another solution is to use outline
on hover (and set the border to 0) which doesn't affect the document flow:
li{
display:inline-block;
padding:5px;
border:0;
}
li:hover{
outline:1px solid #FC0;
}
NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.
Update one MySQL table with values from another
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
Java error: Implicit super constructor is undefined for default constructor
Short answer:
Add a constructor with no argument in base/parent/super class. i.e for example,
class Parent{
String name;
int age;
String occupation;
//empty constructor
public Parent(){
}
public Parent(String name, int age, String employment){
this.name = name;
this.age = age;
this.occupation = employment;
}
}
// You can have any additional constructors as you wish aka constructor overloading here in parent class.
If a super class does not have the no-argument constructor then you will get the compile-time error. Object does have such the constructor, so if Object is a only super class then there is no problem.
// then let's inherit
class Child extends Parent{
Child(String name, int age){
this.name = name;
this.age = age;
}
}
With super(), a super class no-argument constructor is called and with super(parameter list), a super class constructor with the matching parameter list is called.
Jquery .on('scroll') not firing the event while scrolling
I know that this is quite old thing, but I solved issue like that:
I had parent and child element was scrollable.
if ($('#parent > *').length == 0 ){
var wait = setInterval(function() {
if($('#parent > *').length != 0 ) {
$('#parent .child').bind('scroll',function() {
//do staff
});
clearInterval(wait);
},1000);
}
The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.
NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.
How to link to a <div> on another page?
You simply combine the ideas of a link to another page, as with href=foo.html
, and a link to an element on the same page, as with href=#bar
, so that the fragment like #bar
is written immediately after the URL that refers to another page:
<a href="foo.html#bar">Some nice link text</a>
The target is specified the same was as when linking inside one page, e.g.
<div id="bar">
<h2>Some heading</h2>
Some content
</div>
or (if you really want to link specifically to a heading only)
<h2 id="bar">Some heading</h2>
How to convert String to DOM Document object in java?
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) );
} catch (Exception e) {
e.printStackTrace();
}
}
pip install access denied on Windows
One additional thing that has not been covered in previous answers and that often cause issues on Windows and stopped me from installing some package despite running as admin is that you get the same permission denied error if there is another program that use some of the files you (or pip install
) try to access. This is a really stupid "feature" of Windows that pops up many times, e.g. when trying to move some files.
In addition I have no clue how to figure out which program locks a particular file, so the easiest ting to do is to reboot and do the installation before starting anything, in particular before running e.g. Spyder or any other Python-based software. You can also try to close all programs, but it can be tricky to know which one actually holds a file. For a directory for example, it is enough that you have an Explorer window open at that directory.
Calling a javascript function recursively
I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)
var fn = (function() {
var innerFn = function(counter) {
console.log(counter);
if(counter > 0) {
innerFn(counter-1);
}
};
return innerFn;
})();
console.log("running fn");
fn(3);
var copyFn = fn;
console.log("running copyFn");
copyFn(3);
fn = function() { console.log("done"); };
console.log("fn after reassignment");
fn(3);
console.log("copyFn after reassignment of fn");
copyFn(3);
Where is my m2 folder on Mac OS X Mavericks
You can try searching for local .m2 repository by using the command in the project directory.
mvn help:evaluate -Dexpression=settings.localRepository
your output will be similar to below and you can see local .m2 directory path as shown below: /Users/arai/.m2/repository
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
Downloaded from central: https://repo.maven.apache.org/maven2/net/sf/jtidy/jtidy/r938/jtidy-r938.jar (250 kB at 438 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar (335 kB at 530 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar (305 kB at 430 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar (500 kB at 595 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar (621 kB at 671 kB/s)
[INFO] No artifact parameter specified, using 'org.apache.maven:standalone-pom:pom:1' as project.
[INFO]
/Users/arai/.m2/repository
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.540 s
[INFO] Finished at: 2019-01-23T13:57:54-05:00
[INFO] ------------------------------------------------------------------------
How to add column if not exists on PostgreSQL?
Simply check if the query returned a column_name.
If not, execute something like this:
ALTER TABLE x ADD COLUMN y int;
Where you put something useful for 'x' and 'y' and of course a suitable datatype where I used int.
Android button with icon and text
To add an image to left, right, top or bottom, you can use attributes like this:
android:drawableLeft
android:drawableRight
android:drawableTop
android:drawableBottom
The sample code is given above. You can also achieve this using relative layout.
Update Git submodule to latest commit on origin
If you don't know the host branch, make this:
git submodule foreach git pull origin $(git rev-parse --abbrev-ref HEAD)
It will get a branch of the main Git repository and then for each submodule will make a pull of the same branch.
How to redirect DNS to different ports
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
Calling a parent window function from an iframe
The solution given by Ash Clarke for subdomains works great, but please note that you need to include the document.domain = "mydomain.com"; in both the head of the iframe page and the head of the parent page, as stated in the link same origin policy checks
An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name.
For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered same-origin for the purpose of DOM manipulation.
How to declare a constant in Java
final
means that the value cannot be changed after initialization, that's what makes it a constant. static
means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final
means only one instance of the variable no matter how many objects are created and the value of that variable can never change.
C#/Linq: Apply a mapping function to each element in an IEnumerable?
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
Java check to see if a variable has been initialized
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
- int:
0
- char:
\u0000
or 0
- double:
0.0
- boolean:
false
- reference:
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
Setting Authorization Header of HttpClient
static async Task<AccessToken> GetToken()
{
string clientId = "XXX";
string clientSecret = "YYY";
string credentials = String.Format("{0}:{1}", clientId, clientSecret);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
requestData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
var request = await client.PostAsync("https://accounts.spotify.com/api/token", requestBody);
var response = await request.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AccessToken>(response);
}
}
How do I perform an insert and return inserted identity with Dapper?
I was using .net core 3.1 with postgres 12.3. Building on the answer from Tadija Bagaric I ended up with:
using (var connection = new NpgsqlConnection(AppConfig.CommentFilesConnection))
{
string insertUserSql = @"INSERT INTO mytable(comment_id,filename,content)
VALUES( @commentId, @filename, @content) returning id;";
int newUserId = connection.QuerySingle<int>(
insertUserSql,
new
{
commentId = 1,
filename = "foobar!",
content = "content"
}
);
}
where AppConfig is my own class which simply gets a string set for my connection details. This is set within the Startup.cs ConfigureServices method.
How to read a file in Groovy into a string?
String fileContents = new File('/path/to/file').text
If you need to specify the character encoding, use the following instead:
String fileContents = new File('/path/to/file').getText('UTF-8')
Ansible playbook shell output
Expanding on what leucos said in his answer, you can also print information with Ansible's humble debug
module:
- hosts: all
gather_facts: no
tasks:
- shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
register: ps
# Print the shell task's stdout.
- debug: msg={{ ps.stdout }}
# Print all contents of the shell task's output.
- debug: var=ps
Flatten list of lists
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
Loop Through All Subfolders Using VBA
Just a simple folder drill down.
sub sample()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
Generate sha256 with OpenSSL and C++
std based
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
int main() {
cout << sha256("1234567890_1") << endl;
cout << sha256("1234567890_2") << endl;
cout << sha256("1234567890_3") << endl;
cout << sha256("1234567890_4") << endl;
return 0;
}
VBScript - How to make program wait until process has finished?
Probably something like this? (UNTESTED)
Sub Sample()
Dim strWB4, strMyMacro
strMyMacro = "Sheet1.my_macro_name"
'
'~~> Rest of Code
'
'loop through the folder and get the file names
For Each Fil In FLD.Files
Set x4WB = x1.Workbooks.Open(Fil)
x4WB.Application.Visible = True
x1.Run strMyMacro
x4WB.Close
Do Until IsWorkBookOpen(Fil) = False
DoEvents
Loop
Next
'
'~~> Rest of Code
'
End Sub
'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Dynamically create and submit form
Yes, it is possible. One of the solutions is below (jsfiddle as a proof).
HTML:
<a id="fire" href="#" title="submit form">Submit form</a>
(see, above there is no form)
JavaScript:
jQuery('#fire').click(function(event){
event.preventDefault();
var newForm = jQuery('<form>', {
'action': 'http://www.google.com/search',
'target': '_top'
}).append(jQuery('<input>', {
'name': 'q',
'value': 'stack overflow',
'type': 'hidden'
}));
newForm.submit();
});
The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options
, so I have set target
to _top
, which replaces the main window's content. Alternatively if you set _blank
, it can show within new window / tab.
How can I align the columns of tables in Bash?
It's easier than you wonder.
If you are working with a separated by semicolon file and header too:
$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t
If you are working with array (using tab as separator):
for((i=0;i<array_size;i++));
do
echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv
done;
cat file.csv | column -t
How to create a popup windows in javafx
The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.
See this Popup Window example.
Find all packages installed with easy_install/pip?
Start with:
$ pip list
To list all packages. Once you found the package you want, use:
$ pip show <package-name>
This will show you details about this package, including its folder. You can skip the first part if you already know the package name
Click here for more information on pip show and here for more information on pip list.
Example:
$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: [email protected]
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel
Convert .pem to .crt and .key
If you asked this question because you're using mkcert
then the trick is that the .pem
file is the cert and the -key.pem
file is the key.
(You don't need to convert, just run mkcert yourdomain.dev otherdomain.dev
)
Know relationships between all the tables of database in SQL Server
Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).
SELECT
fk.name 'FK Name',
tp.name 'Parent table',
cp.name, cp.column_id,
tr.name 'Refrenced table',
cr.name, cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY
tp.name, cp.column_id
Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.
I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....
Returning a file to View/Download in ASP.NET MVC
Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link
How to download files using asp.net core
[Route("api/[controller]")]
public class DownloadController : Controller
{
[HttpGet]
public async Task<IActionResult> Download()
{
var path = @"C:\Vetrivel\winforms.png";
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var ext = Path.GetExtension(path).ToLowerInvariant();
return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
...
};
}
}
Alter a SQL server function to accept new optional parameter
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
How can I use JSON data to populate the options of a select box?
zeusstl is right. it works for me too.
<select class="form-control select2" id="myselect">
<option disabled="disabled" selected></option>
<option>Male</option>
<option>Female</option>
</select>
$.getJSON("mysite/json1.php", function(json){
$('#myselect').empty();
$('#myselect').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
Map.Entry: How to use it?
Map.Entry interface helps us iterating a Map class
Check this simple example:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap();
map.put(1, "Kamran");
map.put(2, "Ali");
map.put(3, "From");
map.put(4, "Dir");
map.put(5, "Lower");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Android ListView Text Color
if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.
ADD android:theme="@style/AppTheme" in Android Manifest.
Convert Xml to Table SQL Server
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
1
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
2.
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html
http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx
Apk location in New Android Studio
I am on Android Studio 0.6 and the apk was generated in
MyApp/myapp/build/outputs/apk/myapp-debug.apk
It included all libraries so I could share it.
Update on Android Studio 0.8.3 Beta. The apk is now in
MyApp/myapp/build/apk/myapp-debug.apk
Update on Android Studio 0.8.6 - 2.0. The apk is now in
MyApp/myapp/build/outputs/apk/myapp-debug.apk
How do I find out if a column exists in a VB.Net DataRow
Another way to find out if a column exists is to check for Nothing
the value returned from the Columns
collection indexer when passing the column name to it:
If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
MsgBox("YAY")
End If
This approach might be preferred over the one that uses the Contains("ColumnName")
method when the following code will subsequently need to get that DataColumn
for further usage. For example, you may want to know which type has a value stored in the column:
Dim column = DataRow.Table.Columns("ColumnName")
If column IsNot Nothing Then
Dim type = column.DataType
End If
In this case this approach saves you a call to the Contains("ColumnName")
at the same time making your code a bit cleaner.
Equal height rows in a flex container
The answer is NO.
The reason is provided in the flexbox specification:
6. Flex Lines
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
Equal height rows, however, are possible in CSS Grid Layout:
Otherwise, consider a JavaScript alternative.
if, elif, else statement issues in Bash
Missing space between elif
and [
rest your program is correct. you need to correct it an check it out. here is fixed program:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
useful link related to this bash if else statement
How to start a background process in Python?
I found this here:
On windows (win xp), the parent process will not finish until the longtask.py
has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.
The solution is to pass DETACHED_PROCESS
Process Creation Flag to the underlying CreateProcess
function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen([sys.executable, "longtask.py"],
creationflags=DETACHED_PROCESS).pid
Use of the MANIFEST.MF file in Java
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header:
When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header:
Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers:
When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/}
Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
Check file size before upload
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
Test if something is not undefined in JavaScript
Just check if response[0]
is undefined:
if(response[0] !== undefined) { ... }
If you still need to explicitly check the title, do so after the initial check:
if(response[0] !== undefined && response[0].title !== undefined){ ... }
Fitting polynomial model to data in R
Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:
polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)
Notes
The validity of this approach will depend on your objectives, the assumptions of optimize()
and AIC()
and if AIC is the criterion that you want to use,
polyfit()
may not have a single minimum. check this with something like:
for (i in 2:length(x)-1) print(polyfit(i))
I used the as.integer()
function because it is not clear to me how I would interpret a non-integer polynomial.
for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here
Update
Also see the stepAIC
function (in the MASS package) to automate model selection.
PHP save image file
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
How to run DOS/CMD/Command Prompt commands from VB.NET?
You could try this method:
Public Class MyUtilities
Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean)
Dim p as Process = new Process()
Dim pi as ProcessStartInfo = new ProcessStartInfo()
pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments
pi.FileName = "cmd.exe"
p.StartInfo = pi
p.Start()
End Sub
End Class
call, for example, in this way:
MyUtilities.RunCommandCom("DIR", "/W", true)
EDIT: For the multiple command on one line the key are the & | && and || command connectors
- A & B → execute command A, then execute command B.
- A | B → execute command A, and redirect all it's output into the
input of command B.
- A && B → execute command A, evaluate the errorlevel after running
Command A, and if the exit code (errorlevel) is 0, only then execute
command B.
- A || B → execute Command A, evaluate the exit code of this command
and if it's anything but 0, only then execute command B.
Why do I need 'b' to encode a string with Base64?
If the string is Unicode the easiest way is:
import base64
a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))
# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'
b = base64.b64decode(a).decode("utf-8", "ignore")
print(b)
# b :complex string: ñáéíóúÑ
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Android Pop-up message
If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.
For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.
How to kill a process in MacOS?
I recently faced similar issue where the atom editor will not close. Neither was responding. Kill / kill -9 / force exit from Activity Monitor - didn't work. Finally had to restart my mac to close the app.
Syntax for a for loop in ruby
What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):
ar = [1,2,3,4,5,6]
for item in ar
puts item
end
How to select between brackets (or quotes or ...) in Vim?
To select between the single quotes I usually do a vi'
("select inner single quotes").
Inside a parenthesis block, I use vib
("select inner block")
Inside a curly braces block you can use viB
("capital B")
To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a
instead of i
.
You can read more about the Text object selections on the manual, or :help text-objects
within vim.
Get an object's class name at runtime
Solution using Decorators that survives minification/uglification
We use code generation to decorate our Entity classes with metadata like so:
@name('Customer')
export class Customer {
public custId: string;
public name: string;
}
Then consume with the following helper:
export const nameKey = Symbol('name');
/**
* To perserve class name though mangling.
* @example
* @name('Customer')
* class Customer {}
* @param className
*/
export function name(className: string): ClassDecorator {
return (Reflect as any).metadata(nameKey, className);
}
/**
* @example
* const type = Customer;
* getName(type); // 'Customer'
* @param type
*/
export function getName(type: Function): string {
return (Reflect as any).getMetadata(nameKey, type);
}
/**
* @example
* const instance = new Customer();
* getInstanceName(instance); // 'Customer'
* @param instance
*/
export function getInstanceName(instance: Object): string {
return (Reflect as any).getMetadata(nameKey, instance.constructor);
}
Extra info:
- You may need to install
reflect-metadata
reflect-metadata
is pollyfill written by members ot TypeScript for the proposed ES7 Reflection API
- The proposal for decorators in JS can be tracked here
C# with MySQL INSERT parameters
What I did is like this.
String person;
String address;
person = your value;
address =your value;
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES('"+person+"','"+address+"')";
comm.ExecuteNonQuery();
conn.Close();
Parse JSON from HttpURLConnection object
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Laravel is there a way to add values to a request array
Usually, you do not want to add anything to a Request object, it's better to use collection and put()
helper:
function store(Request $request)
{
// some additional logic or checking
User::create(array_merge($request->all(), ['index' => 'value']));
}
Or you could union arrays:
User::create($request->all() + ['index' => 'value']);
But, if you really want to add something to a Request object, do this:
$request->request->add(['variable' => 'value']); //add request
How to delete multiple values from a vector?
First we can define a new operator,
"%ni%" = Negate( "%in%" )
Then, its like x not in remove
x <- 1:10
remove <- c(2,3,5)
x <- x[ x %ni% remove ]
or why to go for remove, go directly
x <- x[ x %ni% c(2,3,5)]
Detect whether there is an Internet connection available on Android
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Console.log(); How to & Debugging javascript
console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.
It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.
To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.
Numbering rows within groups in a data frame
Another base R solution would be to split
the data frame per cat
, after that using lapply
: add a column with number 1:nrow(x)
. The last step is to have your final data frame back with do.call
, that is:
df_split <- split(df, df$cat)
df_lapply <- lapply(df_split, function(x) {
x$num <- seq_len(nrow(x))
return(x)
})
df <- do.call(rbind, df_lapply)
Auto start print html page using javascript
This script will run after the entire page has loaded.
<script type="text/javascript">
$(window).load(function() {
//This execute when entire finished loaded
window.print();
});
</script>
Adding asterisk to required fields in Bootstrap 3
This CSS worked for me:
.form-group.required.control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -10px;
}
and this HTML:
<div class="form-group required control-label">
<label for="emailField">Email</label>
<input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>
Get generic type of class at runtime
Here is working solution!!!
@SuppressWarnings("unchecked")
private Class<T> getGenericTypeClass() {
try {
String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
Class<?> clazz = Class.forName(className);
return (Class<T>) clazz;
} catch (Exception e) {
throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
}
}
NOTES:
Can be used only as superclass
1. Has to be extended with typed class (Child extends Generic<Integer>
)
OR
2. Has to be created as anonymous implementation (new Generic<Integer>() {};
)
Unmount the directory which is mounted by sshfs in Mac
You can always do this from finder. Simply navigate to the directory above where the mount is and hit the eject icon over the mounted folder, which will have SSHFS in the name (in the finder). A shortcut to open a folder in the finder from the terminal is
open .
which will open up the current directory in a new finder window. Replace "." with your directory of choice.
How can I convert tabs to spaces in every file of a directory?
Use the vim-way:
$ ex +'bufdo retab' -cxa **/*.*
- Make the backup! before executing the above command, as it can corrupt your binary files.
- To use
globstar
(**
) for recursion, activate by shopt -s globstar
.
- To specify specific file type, use for example:
**/*.c
.
To modify tabstop, add +'set ts=2'
.
However the down-side is that it can replace tabs inside the strings.
So for slightly better solution (by using substitution), try:
$ ex -s +'bufdo %s/^\t\+/ /ge' -cxa **/*.*
Or by using ex
editor + expand
utility:
$ ex -s +'bufdo!%!expand -t2' -cxa **/*.*
For trailing spaces, see: How to remove trailing whitespaces for multiple files?
You may add the following function into your .bash_profile
:
# Convert tabs to spaces.
# Usage: retab *.*
# See: https://stackoverflow.com/q/11094383/55075
retab() {
ex +'set ts=2' +'bufdo retab' -cxa $*
}
OS X cp command in Terminal - No such file or directory
In my case, I had accidentally named a folder 'samples '.
I couldn't see the space when I did 'ls -la'.
Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.
To fix this I ran
mv samples\ samples
Using Mockito, how do I verify a method was a called with a certain argument?
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
Java variable number or arguments for a method
Variable number of arguments
It is possible to pass a variable number of arguments to a method. However, there
are some restrictions:
- The variable number of parameters must all be the same type
- They are treated as an array within the method
- They must be the last parameter of the method
To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:
private static int largest(int... numbers) {
int currentLargest = numbers[0];
for (int number : numbers) {
if (number > currentLargest) {
currentLargest = number;
}
}
return currentLargest;
}
source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012
Trying to handle "back" navigation button action in iOS
The problem with didMoveToParentViewController
it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.
And it doesn't work with the driven animation gesture.
Using willMoveToParentViewController
works better.
Objective-c
- (void)willMoveToParentViewController:(UIViewController *)parent{
if (parent == NULL) {
// ...
}
}
Swift
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
// ...
}
}
What is the best way to measure execution time of a function?
Use a Profiler
Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.
The advantages they have is:
- You can even get a statement level
breakup
- No changes required in your codebase
- Instrumentions generally have very less overhead, hence very accurate results can be obtained.
There are many available open-source as well.
Python Selenium Chrome Webdriver
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
Reference: https://pypi.org/project/chromedriver-binary/
Get child node index
Use binary search algorithm to improve the performace when the node has large quantity siblings.
function getChildrenIndex(ele){
//IE use Element.sourceIndex
if(ele.sourceIndex){
var eles = ele.parentNode.children;
var low = 0, high = eles.length-1, mid = 0;
var esi = ele.sourceIndex, nsi;
//use binary search algorithm
while (low <= high) {
mid = (low + high) >> 1;
nsi = eles[mid].sourceIndex;
if (nsi > esi) {
high = mid - 1;
} else if (nsi < esi) {
low = mid + 1;
} else {
return mid;
}
}
}
//other browsers
var i=0;
while(ele = ele.previousElementSibling){
i++;
}
return i;
}
How to refer to Excel objects in Access VBA?
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
How to access the SMS storage on Android?
You are going to need to call the SmsManager
class. You are probably going to need to use the STATUS_ON_ICC_READ
constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through.
BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.
Here is the link that goes into depth on the Sms Manager
What exactly does big ? notation represent?
Theta(n): A function f(n)
belongs to Theta(g(n))
, if there exists positive constants c1
and c2
such that f(n)
can be sandwiched between c1(g(n))
and c2(g(n))
. i.e it gives both upper and as well as lower bound.
Theta(g(n)) = { f(n) : there exists positive constants c1,c2 and n1 such that
0<=c1(g(n))<=f(n)<=c2(g(n)) for all n>=n1 }
when we say f(n)=c2(g(n))
or f(n)=c1(g(n))
it represents asymptotically tight bound.
O(n): It gives only upper bound (may or may not be tight)
O(g(n)) = { f(n) : there exists positive constants c and n1 such that 0<=f(n)<=cg(n) for all n>=n1}
ex: The bound 2*(n^2) = O(n^2)
is asymptotically tight, whereas the bound 2*n = O(n^2)
is not asymptotically tight.
o(n): It gives only upper bound (never a tight bound)
the notable difference between O(n) & o(n) is f(n) is less than cg(n)
for all n>=n1 but not equal as in O(n).
ex: 2*n = o(n^2)
, but 2*(n^2) != o(n^2)
Test whether string is a valid integer
For portability to pre-Bash 3.1 (when the =~
test was introduced), use expr
.
if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
echo "String is a valid integer."
else
echo "String is not a valid integer."
fi
expr STRING : REGEX
searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \
. -\?
means "maybe -
", [0-9]\+
means "one or more digits", and $
means "end of string".
Bash also supports extended globs, though I don't recall from which version onwards.
shopt -s extglob
case "$string" of
@(-|)[0-9]*([0-9]))
echo "String is a valid integer." ;;
*)
echo "String is not a valid integer." ;;
esac
# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]
@(-|)
means "-
or nothing", [0-9]
means "digit", and *([0-9])
means "zero or more digits".
How to enable C# 6.0 feature in Visual Studio 2013?
It is possible to use full C# 6.0 features in Visual Studio 2013 if you have Resharper.
You have to enable Resharper Build and voilá!
In Resharper Options -> Build - enable Resharper Build and in "Use MSBuild.exe version" choose "Latest Installed"
This way Resharper is going to build your C# 6.0 Projects and will also not underline C# 6.0 code as invalid.
I am also using this although I have Visual Studio 2015 because:
- Unit Tests in Resharper don't work for me with Visual Studio 2015 for some reason
- VS 2015 uses a lot more memory than VS 2013.
I am putting this here, as I was looking for a solution for this problem for some time now and maybe it will help someone else.
MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query
As Ponies says in a comment, you cannot mix OLAP functions with aggregate functions.
Perhaps it's easier to get the last completion date for each employee, and join that to a dataset containing the last completion date for each of the three targeted courses.
This is an untested idea that should hopefully put you down the right path:
SELECT employee_number,
course_code,
MAX(course_completion_date) AS max_date,
lcc.LAST_COURSE_COMPLETED
FROM employee_course_completion ecc
LEFT JOIN (
SELECT employee_number,
MAX(course_completion_date) AS LAST_COURSE_COMPLETED
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
) lcc
ON lcc.employee_number = ecc.employee_number
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code, lcc.LAST_COURSE_COMPLETED
How to export data to an excel file using PHPExcel
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
Add Foreign Key relationship between two Databases
If you need rock solid integrity, have both tables in one database, and use an FK constraint. If your parent table is in another database, nothing prevents anyone from restoring that parent database from an old backup, and then you have orphans.
This is why FK between databases is not supported.
Split a string by another string in C#
string data = "THExxQUICKxxBROWNxxFOX";
return data.Replace("xx","|").Split('|');
Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!
J2ME/Android/BlackBerry - driving directions, route between two locations
J2ME Map Route Provider
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
BlackBerry
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
Android
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
How to open some ports on Ubuntu?
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
How to override maven property in command line?
See Introduction to the POM
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
Parse time of format hh:mm:ss
If you want to extract the hours, minutes and seconds, try this:
String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);
Removing duplicates from a String in Java
String input = "abbcccaabbddeessacccbbddefgaabbccddeeffggadscsda";
String output ="";
for (int i= 0; i<input.length();i++) {
if (!output.contains(input.substring(i, i+1)))
output = output+ input.substring(i, i+1);
}
System.out.println(output);
Ignore python multiple return value
You can use x = func()[0]
to return the first value, x = func()[1]
to return the second, and so on.
If you want to get multiple values at a time, use something like x, y = func()[2:4]
.
Formatting dates on X axis in ggplot2
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
How to change the height of a div dynamically based on another div using css?
The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table
properties:
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: table;
}
.div2, .div3 {
display: table-cell;
}
.div2 {
width:150px;
height:auto;
background-color: #F4A460;
}
.div3 {
width:150px;
height:auto;
background-color: #FFFFE0;
}
http://jsfiddle.net/E4Zgj/21/
Now, if your goal is to have .div2
so that it is only as tall as it needs to be to contain its content while .div3
is at least as tall as .div2
but still able to expand if its content makes it taller than .div2
, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: flex;
align-items: flex-start;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
align-self: stretch;
}
http://jsfiddle.net/E4Zgj/22/
Adding external library into Qt Creator project
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
How to filter rows containing a string pattern from a Pandas dataframe
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.