Java String import
Java compiler imports 3 packages by default.
1. The package without name
2. The java.lang package(That's why you can declare String, Integer, System classes without import)
3. The current package (current file's package)
That's why you don't need to declare import statement for the java.lang
package.
How to make Visual Studio copy a DLL file to the output directory?
Add builtin COPY in project.csproj file:
<Project>
...
<Target Name="AfterBuild">
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Debug\bin" SkipUnchangedFiles="false" />
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Release\bin" SkipUnchangedFiles="false" />
</Target>
</Project>
HTML5 Canvas: Zooming
Just try this out:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type =
"button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();
context.restore();
}
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt){
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt){
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt){
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function(){
$("#wrapper").mouseover(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down
Njoy!!!
Here is fiddle for this Fiddle
How can I pass a parameter to a Java Thread?
To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.
class MyThread implements Runnable{
private int a;
private String b;
private double c;
public MyThread(int a, String b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public void run(){
doSomething(a, b, c);
}
}
How to properly export an ES6 class in Node 4?
class expression can be used for simplicity.
// Foo.js
'use strict';
// export default class Foo {}
module.exports = class Foo {}
-
// main.js
'use strict';
const Foo = require('./Foo.js');
let Bar = new class extends Foo {
constructor() {
super();
this.name = 'bar';
}
}
console.log(Bar.name);
Get local IP address in Node.js
Based on a comment, here's what's working for the current version of Node.js:
var os = require('os');
var _ = require('lodash');
var ip = _.chain(os.networkInterfaces())
.values()
.flatten()
.filter(function(val) {
return (val.family == 'IPv4' && val.internal == false)
})
.pluck('address')
.first()
.value();
The comment on one of the answers above was missing the call to values()
. It looks like os.networkInterfaces()
now returns an object instead of an array.
Initial bytes incorrect after Java AES/CBC decryption
Online Editor Runnable version:-
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
public class Encryptor {
public static String encrypt(String key, String initVector, String value) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
//System.out.println("encrypted string: "
// + Base64.encodeBase64String(encrypted));
//return Base64.encodeBase64String(encrypted);
String s = new String(Base64.getEncoder().encode(encrypted));
return s;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
System.out.println(encrypt(key, initVector, "Hello World"));
System.out.println(decrypt(key, initVector, encrypt(key, initVector, "Hello World")));
}
}
How to write/update data into cells of existing XLSX workbook using xlsxwriter in python
Note that openpyxl does not have a large toolbox for manipulating and editing images. Xlsxwriter has methods for images, but on the other hand cannot import existing worksheets...
I have found that this works for rows...
I'm sure there's a way to do it for columns...
import openpyxl
oxl = openpyxl.load_workbook('File Loction Here')
xl = oxl.['SheetName']
x=0
col = "A"
row = x
while (row <= 100):
y = str(row)
cell = col + row
xl[cell] = x
row = row + 1
x = x + 1
The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception
This weird error happens, when you play around with different versions of EntityFramework versions in Nuget Packages like I did.
First, Uninstall your Entity Framework DLL from NuGet packages and then Clean up app.config. By removing the entry from configSections and entity framework element.
Next, install the desired version. This should fix the problem.
How can I perform a str_replace in JavaScript, replacing text in JavaScript?
In JavaScript, you call the replace
method on the String object, e.g. "this is some sample text that i want to replace".replace("want", "dont want")
, which will return the replaced string.
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched
How to determine the Boost version on a system?
Boost installed on OS X using homebrew has desired version.hpp
file in /usr/local/Cellar/boost/<version>/include/boost/version.hpp
(note, that the version is already mentioned in path).
I guess the fastest way to determine version on any UNIX-like system will be to search for boost
in /usr
:
find /usr -name "boost"
Splitting a string into separate variables
An array is created with the -split
operator. Like so,
$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago
When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,
$arr[2] # 3rd element
and
$arr[4] # 5th element
years
Can I fade in a background image (CSS: background-image) with jQuery?
So.. I was also looking into this matter and saw that most of the answers here are asking to fade the container element, not the actual background-image.
Then a hack crossed my mind. We can give multiple background right? what if we overlay other color and make it transparent, like code below-
background: url("//unsplash.it/500/400") rgb(255, 255, 255, 0.5) no-repeat center;
This code actually works stand alone. Try it. We gave a bg image and asked other white color with transparency on top of the image and Voila.
TIP- we can give different colors and transparencies to get different filter kind of effect.
How to get current SIM card number in Android?
Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.
=================================================================================
Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.
As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.
Permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Code:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
String acname = ac.name;
String actype = ac.type;
// Take your time to look at all available accounts
System.out.println("Accounts : " + acname + ", " + actype);
}
Check actype for whatsapp account
if(actype.equals("com.whatsapp")){
String phoneNumber = ac.name;
}
Of course you may not get it if user did not install Whatsapp, but its worth to try anyway.
And remember you should always ask user for confirmation.
How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?
This script generates insert statements of your existing data. This is a stored procedure which you need to run once and then it is tailor made for you.
I tried to find this kind of stuff for a while but wasn't satisfied with the results, so I wrote this stored procedure.
Example:
Exec [dbo].[INS] 'Dbo.test where 1=1'
(1) Here dbo
is schema and test is tablename and 1=1
is condition.
Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
(2) Here dbo
is schema and test is tablename and name='neeraj'
is condition.
Here is the stored procedure
/*
Authore : neeraj prasad sharma (please dont remove this :))
Example (1) Exec [dbo].[INS] 'Dbo.test where 1=1'
(2) Exec [dbo].[INS] 'Dbo.test where name =''neeraj''' * for string
here Dbo is schema and test is tablename and 1=1 is condition
*/
CREATE procedure [dbo].[INS]
(
@Query Varchar(MAX)
)
AS
SET nocount ON
DECLARE @WithStrINdex as INT
DECLARE @WhereStrINdex as INT
DECLARE @INDExtouse as INT
DECLARE @SchemaAndTAble VArchar(270)
DECLARE @Schema_name varchar(30)
DECLARE @Table_name varchar(240)
DECLARE @Condition Varchar(MAX)
SET @WithStrINdex=0
SELECT @WithStrINdex=CHARINDEX('With',@Query )
, @WhereStrINdex=CHARINDEX('WHERE', @Query)
IF(@WithStrINdex!=0)
SELECT @INDExtouse=@WithStrINdex
ELSE
SELECT @INDExtouse=@WhereStrINdex
SELECT @SchemaAndTAble=Left (@Query,@INDExtouse-1)
SELECT @SchemaAndTAble=Ltrim (Rtrim( @SchemaAndTAble))
SELECT @Schema_name= Left (@SchemaAndTAble, CharIndex('.',@SchemaAndTAble )-1)
, @Table_name = SUBSTRING( @SchemaAndTAble , CharIndex('.',@SchemaAndTAble )+1,LEN(@SchemaAndTAble) )
, @CONDITION=SUBSTRING(@Query,@WhereStrINdex+6,LEN(@Query))--27+6
DECLARE @COLUMNS table (Row_number SmallINT , Column_Name VArchar(Max) )
DECLARE @CONDITIONS as varchar(MAX)
DECLARE @Total_Rows as SmallINT
DECLARE @Counter as SmallINT
DECLARE @ComaCol as varchar(max)
SELECT @ComaCol=''
SET @Counter=1
SET @CONDITIONS=''
INSERT INTO @COLUMNS
SELECT Row_number()Over (Order by ORDINAL_POSITION ) [Count], Column_Name
FROM INformation_schema.columns
WHERE Table_schema=@Schema_name AND table_name=@Table_name
SELECT @Total_Rows= Count(1)
FROM @COLUMNS
SELECT @Table_name= '['+@Table_name+']'
SELECT @Schema_name='['+@Schema_name+']'
While (@Counter<=@Total_Rows )
begin
--PRINT @Counter
SELECT @ComaCol= @ComaCol+'['+Column_Name+'],'
FROM @COLUMNS
WHERE [Row_number]=@Counter
SELECT @CONDITIONS=@CONDITIONS+ ' + Case When ['+Column_Name+'] is null then ''Null'' Else '''''''' + Replace( Convert(varchar(Max),['+Column_Name+'] ) ,'''''''','''' ) +'''''''' end+'+''','''
FROM @COLUMNS
WHERE [Row_number]=@Counter
SET @Counter=@Counter+1
End
SELECT @CONDITIONS=Right(@CONDITIONS,LEN(@CONDITIONS)-2)
SELECT @CONDITIONS=LEFT(@CONDITIONS,LEN(@CONDITIONS)-4)
SELECT @ComaCol= substring (@ComaCol,0, len(@ComaCol) )
SELECT @CONDITIONS= '''INSERT INTO '+@Schema_name+'.'+@Table_name+ '('+@ComaCol+')' +' Values( '+'''' + '+'+@CONDITIONS
SELECT @CONDITIONS=@CONDITIONS+'+'+ ''')'''
SELECT @CONDITIONS= 'Select '+@CONDITIONS +'FRom ' +@Schema_name+'.'+@Table_name+' With(NOLOCK) ' + ' Where '+@Condition
print(@CONDITIONS)
Exec(@CONDITIONS)
"unable to locate adb" using Android Studio
I had the same problem, and I solved it by doing:
- (You should be connected to the internet)
- click the logo of the SDK Manager
- click Launch StandAlone SDK Manager (wait a moment)
- if the dialog of the SDK manager shows, you click cexbox [Tools] and Install all packages
- if the download is finished, you restart android studio and boot again..
After that, it should work.
What does "#pragma comment" mean?
The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment
to send a command to the linker at link time for example
#pragma comment(linker,"/ENTRY:Entry")
tell the linker to change the entry point form WinMain()
to Entry()
after that the CRTStartup
going to transfer controll to Entry()
Getting the array length of a 2D array in Java
There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.
You could easy create your own class to abstract the functionality you need.
If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.
Why is enum class preferred over plain enum?
C++ has two kinds of enum
:
enum class
es
- Plain
enum
s
Here are a couple of examples on how to declare them:
enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum
What is the difference between the two?
enum class
es - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum
or int
)
Plain enum
s - where enumerator names are in the same scope as the enum and their
values implicitly convert to integers and other types
Example:
enum Color { red, green, blue }; // plain enum
enum Card { red_card, green_card, yellow_card }; // another plain enum
enum class Animal { dog, deer, cat, bird, human }; // enum class
enum class Mammal { kangaroo, deer, human }; // another enum class
void fun() {
// examples of bad use of plain enums:
Color color = Color::red;
Card card = Card::green_card;
int num = color; // no problem
if (color == Card::red_card) // no problem (bad)
cout << "bad" << endl;
if (card == Color::green) // no problem (bad)
cout << "bad" << endl;
// examples of good use of enum classes (safe)
Animal a = Animal::deer;
Mammal m = Mammal::deer;
int num2 = a; // error
if (m == a) // error (good)
cout << "bad" << endl;
if (a == Mammal::deer) // error (good)
cout << "bad" << endl;
}
Conclusion:
enum class
es should be preferred because they cause fewer surprises that could potentially lead to bugs.
How to convert a JSON string to a dictionary?
Swift 5
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = data(using: .utf8) {
return try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
}
return nil
}
}
How do I remove quotes from a string?
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Get class name of object as string in Swift
In my case String(describing: self) returned something like:
< My_project.ExampleViewController: 0x10b2bb2b0>
But I'd like to have something like getSimpleName
on Android.
So I've created a little extension:
extension UIViewController {
func getSimpleClassName() -> String {
let describing = String(describing: self)
if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
let afterDotIndex = describing.index(after: dotIndex)
if(afterDotIndex < commaIndex) {
return String(describing[afterDotIndex ..< commaIndex])
}
}
return describing
}
}
And now it returns:
ExampleViewController
Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)
How to add buttons at top of map fragment API v2 layout
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
"Find next" in Vim
When I was beginning I needed to watch a demo.
How to search in Vim
- type
/
- type search term e.g. "var"
- press enter
- for next instance press n (for previous N)
How to use mysql JOIN without ON condition?
There are several ways to do a cross join or cartesian product:
SELECT column_names FROM table1 CROSS JOIN table2;
SELECT column_names FROM table1, table2;
SELECT column_names FROM table1 JOIN table2;
Neglecting the on condition in the third case is what results in a cross join.
Disabling Chrome Autofill
The method of hiding it by adding "display: none;" to the input didn’t work for me if the form is generated through javascript.
So instead I made them invisible by placing them out of sight:
<input style="width:0;height:0;opacity:0;position:absolute;left:-10000px;overflow:hidden;" type="text" name="fakeusernameremembered"/>
<input style="width:0;height:0;opacity:0;position:absolute;left:-10000px;overflow:hidden;" type="password" name="fakepasswordremembered"/>
C# Linq Group By on multiple columns
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
Specifying java version in maven - differences between properties and compiler plugin
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
Output data with no column headings using PowerShell
Joey mentioned that Format-*
is for human consumption. If you're writing to a file for machine consumption, maybe you want to use Export-*
? Some good ones are
Export-Csv
- Comma separated value. Great for when you know what the columns are going to be
Export-Clixml
- You can export whole objects and collections. This is great for serialization.
If you want to read back in, you can use Import-Csv
and Import-Clixml
. I find that I like this better than inventing my own data formats (also it's pretty easy to whip up an Import-Ini
if that's your preference).
How to set the authorization header using curl
Be careful that when you using:
curl -H "Authorization: token_str" http://www.example.com
token_str
and Authorization
must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION
environment.
Cannot set content-type to 'application/json' in jQuery.ajax
I got the solution to send the JSON data by POST request through jquery ajax. I used below code
var data = new Object();
data.p_clientId = 4;
data = JSON.stringify(data);
$.ajax({
method: "POST",
url: "http://192.168.1.141:8090/api/Client_Add",
data: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
I used 'Content-Type': 'text/plain'
in header to send the raw json data.
Because if we use Content-Type: 'application/json'
the request methods converted to OPTION, but using Content-Type: 'test/plain'
the method does not get converted and remain as POST.
Hopefully this will help some one.
Windows batch files: .bat vs .cmd?
No - it doesn't matter in the slightest. On NT the .bat and .cmd extension both cause the cmd.exe processor to process the file in exactly the same way.
Additional interesting information about command.com vs. cmd.exe on WinNT-class systems from MS TechNet (http://technet.microsoft.com/en-us/library/cc723564.aspx):
This behavior reveals a quite subtle
feature of Windows NT that is very
important. The 16-bit MS-DOS shell
(COMMAND.COM) that ships with Windows
NT is specially designed for Windows
NT. When a command is entered for
execution by this shell, it does not
actually execute it. Instead, it
packages the command text and sends it
to a 32-bit CMD.EXE command shell for
execution. Because all commands are
actually executed by CMD.EXE (the
Windows NT command shell), the 16-bit
shell inherits all the features and
facilities of the full Windows NT
shell.
What exactly is node.js used for?
Node.js is a runtime that compiles and executes javaScript. It can be used to develop application that runs end-to-end in JavaScript i..e both client side and server side uses javascript code unlike most of todays' application with rich client framework (angularJs, extJs) and RESTful server side APIs
COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
Bottom Line
Use either COUNT(field)
or COUNT(*)
, and stick with it consistently, and if your database allows COUNT(tableHere)
or COUNT(tableHere.*)
, use that.
In short, don't use COUNT(1)
for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)
Use count(*)
for counting
Use *
for all your queries that need to count everything, even for joins, use *
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But don't use COUNT(*)
for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Don't be fooled by those advising that when using *
in COUNT, it fetches entire row from your table, saying that *
is slow. The *
on SELECT COUNT(*)
and SELECT *
has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *
.
An alternate syntax
In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere)
the same semantics as COUNT(*)
. Example:
For counting rows we could have this:
SELECT COUNT(emp) FROM emp
And they could make it simpler:
SELECT COUNT() FROM emp
And for LEFT JOINs, we could have this:
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But they cannot do that (COUNT(tableNameHere)
) since SQL standard permits naming a field with the same name as its table name:
CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name,
and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)
Counting with null
And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit
field. This will not count all rows, it will only yield 3, not 4
SELECT count(fruit) FROM fruit
Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate
field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But that could cause confusion later if we will add a subordinate
field in the table, as it will count the field(which could be nullable), not the table rows.
So to be on the safe side, use:
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
count(1)
: The one-trick pony
In particular to COUNT(1)
, it is a one-trick pony, it works well only on one table query:
SELECT COUNT(1) FROM tbl
But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
So what's the meaning of COUNT(1) here?
SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Is it this...?
-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Or this...?
-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
By careful thought, you can infer that COUNT(1)
is the same as COUNT(*)
, regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1)
to work as: COUNT(subordinate.boss_id)
, COUNT(subordinate.*)
So just use either of the following:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Works on Postgresql, it's clear that you want to count the cardinality of the set
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7
select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You cannot do this: http://www.sqlfiddle.com/#!1/98515/8
select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9
select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
git stash apply version
Just making simple to understand for beginners.
Check your git stash list with below command :
git stash list
And then apply with below command:
git stash apply stash@{n}
For example: I am applying my latest stash(latest is always index {0} on top of the stash list).
git stash apply stash@{0}
PHP - add 1 day to date format mm-dd-yyyy
Actually I wanted same alike thing,
To get one year backward date, for a given date! :-)
With the hint of above answer from @mohammad mohsenipur
I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-)
I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!
jQuery datepicker years shown
$("#DateOfBirth").datepicker({
yearRange: "-100:+0",
changeMonth: true,
changeYear: true,
});
yearRange: '1950:2013', // specifying a hard coded year range
or this way
yearRange: "-100:+0", // last hundred years
It will help to show drop down for year and month selection.
How to install .MSI using PowerShell
After some trial and tribulation, I was able to find all .msi files in a given directory and install them.
foreach($_msiFiles in
($_msiFiles = Get-ChildItem $_Source -Recurse | Where{$_.Extension -eq ".msi"} |
Where-Object {!($_.psiscontainter)} | Select-Object -ExpandProperty FullName))
{
msiexec /i $_msiFiles /passive
}
center MessageBox in parent form
I have changed a little bit previous answer and compose WPF version of the MessageBoxEx. This code works for me great. Feel free to notify about issues of the code.
Please note:
I use GeneralObjects.MainWindowInstance
at ctor to initialize class with my main window, but actually I use it for any window due to some kind of cache for last parent window. Therefore you can simple remove out everything from ctor.
public class MessageBoxEx
{
private static HwndSource source_ = null;
private static HwndSourceHook hook_ = null;
static MessageBoxEx()
{
try
{
// create cached
createHwndSource_(GeneralObjects.MainWindowInstance);
hook_ = new HwndSourceHook(HwndSourceHook);
}
finally
{
if (null == source_ ||
null == hook_)
{
source_ = null;
hook_ = null;
}
}
}
private static void createHwndSource_(Window owner)
{
source_ = (HwndSource)PresentationSource.FromVisual(owner);
}
public static void Initialize_(Window owner = null)
{
try
{
if (null != owner)
{
if(source_.RootVisual != owner)
{
createHwndSource_(owner);
}
}
}
finally
{
if (null == source_ ||
null == hook_)
{
source_ = null;
hook_ = null;
}
}
if (null != source_ &&
null != hook_)
{
source_.AddHook(hook_);
}
}
public static MessageBoxResult Show(string messageBoxText)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText);
}
public static MessageBoxResult Show(string messageBoxText, string caption)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption);
}
public static MessageBoxResult Show(Window owner, string messageBoxText)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
{
Initialize_();
return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult);
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
{
Initialize_(owner);
return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options);
}
private enum WM : int
{
WM_ACTIVATE = 0x0006
}
private static IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if ((int)WM.WM_ACTIVATE == msg &&
source_.Handle == hwnd &&
0 == (int)wParam)
{
try
{
CenterWindow(lParam);
}
finally
{
// remove hook at once after moved message box window.
source_.RemoveHook(hook_);
}
}
return IntPtr.Zero;
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
private static void CenterWindow(IntPtr hChildWnd)
{
System.Drawing.Rectangle recChild = new System.Drawing.Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
System.Drawing.Rectangle recParent = new System.Drawing.Rectangle(0, 0, 0, 0);
success = GetWindowRect(source_.Handle, ref recParent);
System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
System.Drawing.Point ptStart = new System.Drawing.Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
// I have commented this code because of I have 2 monitors
// so If application located at 1st monitor
// message box can appear at second one.
/*
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
*/
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Delete/Reset all entries in Core Data?
There seems to be two approaches:
Say you have a typical singleton for your core data stack.
import CoreData
public let core = Core.shared
public final class Core {
static let shared = Core()
var container: NSPersistentContainer!
private init() {
container = NSPersistentContainer(name: "stuff")
//deleteSql()
container.loadPersistentStores { storeDescription, error in
if let error = error { print("Error loading... \(error)") }
}
//deleteAll()
}
func saveContext() { // typical save helper
if container.viewContext.hasChanges {
do { try container.viewContext.save()
} catch { print("Error saving... \(error)") }
}
}
then ...
func deleteSql() {
let url = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask)[0].appendingPathComponent( "stuff.sqlite" )
guard FileManager.default.fileExists(atPath: url.path) else {
print("nothing to delete!")
return
}
do {
try container.persistentStoreCoordinator.destroyPersistentStore(
at: url, ofType: "sqlite", options: nil)
print("totally scorched the sql file. you DO now have to LOAD again")
}
catch {
print("there was no sql file there!")
}
}
func deleteAll() { // courtesy @Politta
for e in container.persistentStoreCoordinator.managedObjectModel.entities {
let r = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest(entityName: e.name ?? ""))
let _ = try? container.viewContext.execute(r)
}
saveContext()
print("conventionally deleted everything from within core data. carry on")
}
}
.
1. scorch the sql file
Courtesy the excellent @J.Doe answer. You completely destroy the sql file.
You must to do this
- before loading core data, ie, after creating the container, but
- before actually loading the stores.)
(Notice the example line of code "//deleteSql()" is just before initialization.)
2. delete everything one by one within core data
Courtesy the excellent @Politta answer. You could do this at any time once core data is up and running.
(Notice the example line of code "//deleteAll()" is after initialization.)
Approach one is probably more useful during development. Approach two is probably more useful in production (in the relatively unusual case that for some reason you need to wipe everything).
How do you add an ActionListener onto a JButton in Java
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this);
Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e)
. However, doing this for multiple buttons can be confusing, because the actionPerformed
method will have to check the source of each event (e.getSource()
) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed()
.
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed()
if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()
).
When to use IMG vs. CSS background-image?
I would add another two arguments:
An img tag is good if you need to resize the image. E.g. if the original image is 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width and height of the img tag. I don't know of any good way to do this using background-image. EDIT: This can now also be done with a background-image, using the background-size
CSS3 attribute.
Using background-image is good when you need to dynamically switch between sprites. E.g. if you have a button image, and you want a separate image displayed when the cursor is hovering over the element, you can use a background image containing both the normal and hover sprites, and dynamically change the background-position.
In MS DOS copying several files to one file
filenames must sort correctly to combine correctly!
file1.bin file2.bin ... file10.bin
wont work properly
file01.bin file02.bin ... file10.bin
will work properly
c:>for %i in (file*.bin) do type %i >> onebinary.bin
Works for ascii or binary files.
What does __FILE__ mean in Ruby?
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
SmartGit Installation and Usage on Ubuntu
What it correct way of installing SmartGit on Ubuntu? Thus I can have
normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
Xcode/Simulator: How to run older iOS version?
The simulator CANNOT be downloaded from:
Xcode -> Preferences -> Downloads
Only the iOS devices symbols. As this option says:
This package includes information and symbols that Xcode needs for
debugging your app on iOS devices running versions of iOS prior to iOS
4.2. If you intend to debug your app on a device running one of these versions of iOS you should install this package.
That is, you need an iOS 4.2 device to test an iOS 4.2 application
Javascript - removing undefined fields from an object
Mhh.. I think @Damian asks for remove undefined field (property) from an JS object
.
Then, I would simply do :
for (const i in myObj)
if (typeof myObj[i] === 'undefined')
delete myObj[i];
Short and efficient solution, in (vanilla) JS !
Example :
_x000D_
_x000D_
const myObj = {_x000D_
a: 1,_x000D_
b: undefined,_x000D_
c: null, _x000D_
d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj) _x000D_
if (typeof myObj[i] === 'undefined') _x000D_
delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
_x000D_
_x000D_
Python to print out status bar and percentage
There's a Python module that you can get from PyPI called progressbar
that implements such functionality. If you don't mind adding a dependency, it's a good solution. Otherwise, go with one of the other answers.
A simple example of how to use it:
import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
bar.update(i+1)
sleep(0.1)
bar.finish()
To install it, you can use easy_install progressbar
, or pip install progressbar
if you prefer pip.
Convert a string representation of a hex dump to a byte array using Java?
I've always used a method like
public static final byte[] fromHexString(final String s) {
String[] v = s.split(" ");
byte[] arr = new byte[v.length];
int i = 0;
for(String val: v) {
arr[i++] = Integer.decode("0x" + val).byteValue();
}
return arr;
}
this method splits on space delimited hex values but it wouldn't be hard to make it split the string on any other criteria such as into groupings of two characters.
Right Align button in horizontal LinearLayout
As mentioned a couple times before: To switch from LinearLayout to RelativeLayout works, but you can also solve the problem instead of avoiding it. Use the tools a LinearLayout provides: Give the TextView a weight=1 (see code below), the weight for your button should remain 0 or none. In this case the TextView will take all the remaining space, which is not used to display the content of your TextView or ButtonView and pushes your button to the right.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"
**android:layout_weight="1"**
/>
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
how to get multiple checkbox value using jquery
try this one.. (guys I am a new bee.. so if I wrong then I am really sorry. But I found a solution by this way.)
var suggestion = [];
$('#health_condition_name:checked').each(function (j, ob) {
var odata = {
health_condition_name: $(ob).val()
};
health.push(odata);
});
Transpose a data frame
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
How do I change Bootstrap 3 column order on mobile layout?
In Bootstrap 4, if you want to do something like this:
Mobile | Desktop
-----------------------------
A | A
C | B C
B | D
D |
You need to reverse the order of B then C then apply order-{breakpoint}-first
to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:
Like this
<div class='row no-gutters'>
<div class='col-12'>
A
</div>
<div class='col-12'>
<div class='row no-gutters'>
<div class='col-12 col-md-6'>
C
</div>
<div class='col-12 col-md-6 order-md-first'>
B
</div>
</div>
</div>
<div class='col-12'>
D
</div>
</div>
Demo: https://codepen.io/anon/pen/wXLGKa
Undefined Symbols for architecture x86_64: Compiling problems
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
How to concatenate two numbers in javascript?
I'd prefer the concat
way :
const numVar1 = 5;
const numVar2 = 6;
const value = "".concat(numVar1, numVar2);
// or directly with values
const value2 = "".concat(5, 6);
You can also use an array which can help in some use cases :
const value3 = [5, 6, numVar1].join('');
Most efficient way to check for DBNull and then assign to a variable?
I feel only very few approaches here doesn't risk the prospect OP the most worry (Marc Gravell, Stevo3000, Richard Szalay, Neil, Darren Koppand) and most are unnecessarily complex. Being fully aware this is useless micro-optimization, let me say you should basically employ these:
1) Don't read the value from DataReader/DataRow twice - so either cache it before null checks and casts/conversions or even better directly pass your record[X]
object to a custom extension method with appropriate signature.
2) To obey the above, do not use built in IsDBNull
function on your DataReader/DataRow since that calls the record[X]
internally, so in effect you will be doing it twice.
3) Type comparison will be always slower than value comparison as a general rule. Just do record[X] == DBNull.Value
better.
4) Direct casting will be faster than calling Convert
class for converting, though I fear the latter will falter less.
5) Lastly, accessing record by index rather than column name will be faster again.
I feel going by the approaches of Szalay, Neil and Darren Koppand will be better. I particularly like Darren Koppand's extension method approach which takes in IDataRecord
(though I would like to narrow it down further to IDataReader
) and index/column name.
Take care to call it:
record.GetColumnValue<int?>("field");
and not
record.GetColumnValue<int>("field");
in case you need to differentiate between 0
and DBNull
. For example, if you have null values in enum fields, otherwise default(MyEnum)
risks first enum value being returned. So better call record.GetColumnValue<MyEnum?>("Field")
.
Since you're reading from a DataRow
, I would create extension method for both DataRow
and IDataReader
by DRYing common code.
public static T Get<T>(this DataRow dr, int index, T defaultValue = default(T))
{
return dr[index].Get<T>(defaultValue);
}
static T Get<T>(this object obj, T defaultValue) //Private method on object.. just to use internally.
{
if (obj.IsNull())
return defaultValue;
return (T)obj;
}
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null || obj == DBNull.Value;
}
public static T Get<T>(this IDataReader dr, int index, T defaultValue = default(T))
{
return dr[index].Get<T>(defaultValue);
}
So now call it like:
record.Get<int>(1); //if DBNull should be treated as 0
record.Get<int?>(1); //if DBNull should be treated as null
record.Get<int>(1, -1); //if DBNull should be treated as a custom value, say -1
I believe this is how it should have been in the framework (instead of the record.GetInt32
, record.GetString
etc methods) in the first place - no run-time exceptions and gives us the flexibility to handle null values.
From my experience I had less luck with one generic method to read from the database. I always had to custom handle various types, so I had to write my own GetInt
, GetEnum
, GetGuid
, etc. methods in the long run. What if you wanted to trim white spaces when reading string from db by default, or treat DBNull
as empty string? Or if your decimal should be truncated of all trailing zeroes. I had most trouble with Guid
type where different connector drivers behaved differently that too when underlying databases can store them as string or binary. I have an overload like this:
static T Get<T>(this object obj, T defaultValue, Func<object, T> converter)
{
if (obj.IsNull())
return defaultValue;
return converter == null ? (T)obj : converter(obj);
}
With Stevo3000's approach, I find the calling a bit ugly and tedious, and it will be harder to make a generic function out of it.
Of Countries and their Cities
I was comparing worldcitiesdatabae.info with www.worldcitiesdatabase.com and it appears the latter one to be more resourceful. However, maxmind has a free database so then why buy a cities database. Just get the free one and there is lot of help available on internet about maxmind db. If you put in extra efforts then you can save those few bucks :)
Android appcompat v7:23
Original answer:
I too tried to change the support library to "23". When I changed the targetSdkVersion
to 23, Android Studio reported the following error:
This support library should not use a lower version (22) than the targetSdkVersion
(23)
I simply changed:
compile 'com.android.support:appcompat-v7:23.0.0'
to
compile 'com.android.support:appcompat-v7:+'
Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1
.
Pro tip:
You can use double quotes and create a ${supportLibVersion}
variable for simplicity. Example:
ext {
supportLibVersion = '23.1.1'
}
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"
source: https://twitter.com/manidesto/status/669195097947377664
How can I display a tooltip on an HTML "option" tag?
I just tried doing this on Chrome:
var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});
However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:
- You could fake a select box by using radio boxes that look like dropdowns. So for example, have a radio box absolute positioned and opacity set to 0 placed over the styled box that is pretending to be the option.
- Or you could use pure javascript and have a series of boxes and adding javascript onclick events to recreate the dropbox yourself - so you will update a hidden value with whichever box was clicked using javascript.
- Or use one of the non standard libraries already out there. (If there are any?)
Plotting lines connecting points
You can just pass a list of the two points you want to connect to plt.plot
. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5, 1, -0.5, -1]
plt.plot(x,y, 'ro')
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connectpoints(x,y,0,1)
connectpoints(x,y,2,3)
plt.axis('equal')
plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point i
to point i+1
, we can just put it in a for loop:
import numpy as np
for i in np.arange(0,len(x),2):
connectpoints(x,y,i,i+1)
In that case of always connecting point i
to point i+1
, you could simply do:
for i in np.arange(0,len(x),2):
plt.plot(x[i:i+2],y[i:i+2],'k-')
pandas DataFrame: replace nan values with average of columns
Although, the below code does the job, BUT its performance takes a big hit, as you deal with a DataFrame with # records 100k or more:
df.fillna(df.mean())
In my experience, one should replace NaN values (be it with Mean or Median), only where it is required, rather than applying fillna() all over the DataFrame.
I had a DataFrame with 20 variables, and only 4 of them required NaN values treatment (replacement). I tried the above code (Code 1), along with a slightly modified version of it (code 2), where i ran it selectively .i.e. only on variables which had a NaN value
#------------------------------------------------
#----(Code 1) Treatment on overall DataFrame-----
df.fillna(df.mean())
#------------------------------------------------
#----(Code 2) Selective Treatment----------------
for i in df.columns[df.isnull().any(axis=0)]: #---Applying Only on variables with NaN values
df[i].fillna(df[i].mean(),inplace=True)
#---df.isnull().any(axis=0) gives True/False flag (Boolean value series),
#---which when applied on df.columns[], helps identify variables with NaN values
Below is the performance i observed, as i kept on increasing the # records in DataFrame
DataFrame with ~100k records
- Code 1: 22.06 Seconds
- Code 2: 0.03 Seconds
DataFrame with ~200k records
- Code 1: 180.06 Seconds
- Code 2: 0.06 Seconds
DataFrame with ~1.6 Million records
- Code 1: code kept running endlessly
- Code 2: 0.40 Seconds
DataFrame with ~13 Million records
- Code 1: --did not even try, after seeing performance on 1.6 Mn records--
- Code 2: 3.20 Seconds
Apologies for a long answer ! Hope this helps !
Image re-size to 50% of original size in HTML
You can use the x
descriptor of the srcset
attribute as such:
_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_
Currently supported by all browsers except IE. (caniuse)
MDN documentation
Accessing member of base class
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
Using python's mock patch.object to change the return value of a method called within another method
Let me clarify what you're talking about: you want to test Foo
in a testcase, which calls external method uses_some_other_method
. Instead of calling the actual method, you want to mock the return value.
class Foo:
def method_1():
results = uses_some_other_method()
def method_n():
results = uses_some_other_method()
Suppose the above code is in foo.py
and uses_some_other_method
is defined in module bar.py
. Here is the unittest:
import unittest
import mock
from foo import Foo
class TestFoo(unittest.TestCase):
def setup(self):
self.foo = Foo()
@mock.patch('foo.uses_some_other_method')
def test_method_1(self, mock_method):
mock_method.return_value = 3
self.foo.method_1(*args, **kwargs)
mock_method.assert_called_with(*args, **kwargs)
If you want to change the return value every time you passed in different arguments, mock
provides side_effect
.
Compare given date with today
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
post checkbox value
There are many links that lets you know how to handle post values from checkboxes in php.
Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Single check box
HTML code:
<form action="checkbox-form.php" method="post">
Do you need wheelchair access?
<input type="checkbox" name="formWheelchair" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
PHP Code:
<?php
if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes')
{
echo "Need wheelchair access.";
}
else
{
echo "Do not Need wheelchair access.";
}
?>
Check box group
<form action="checkbox-form.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
<input type="submit" name="formSubmit" value="Submit" />
/form>
<?php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
}
?>
HTML/JavaScript: Simple form validation on submit
The simplest validation is as follows:
_x000D_
_x000D_
<form name="ff1" method="post">
<input type="email" name="email" id="fremail" placeholder="[email protected]" />
<input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
<input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
<input type="submit" name="Submit" value="Continue" />
</form>
_x000D_
_x000D_
_x000D_
It uses HTML5 attributes (like as pattern
).
JavaScript: none.
Not receiving Google OAuth refresh token
Setting this will cause the refresh token to be sent every time:
$client->setApprovalPrompt('force');
an example is given below (php):
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("email");
$client->addScope("profile");
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
How to sort an object array by date property?
I personally use following approach to sort dates.
let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];
array.sort(function(date1, date2) {
date1 = new Date(date1);
date2 = new Date(date2);
if (date1 > date2) return 1;
if (date1 < date2) return -1;
})
SharePoint : How can I programmatically add items to a custom list instance
This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:
using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
{
SPList oList = oWeb.Lists["Announcements"];
// You may also use
// SPList oList = oWeb.GetList("/Lists/Announcements");
// to avoid querying all of the sites' lists
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = "My Item";
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem["Author"] = 3;
oListItem["Editor"] = 3;
oListItem.Update();
}
}
Source:
SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.
How can I backup a Docker-container with its data-volumes?
The following command will run tar in a container with all named data volumes mounted, and redirect the output into a file:
docker run --rm `docker volume list -q | egrep -v '^.{64}$' | awk '{print "-v " $1 ":/mnt/" $1}'` alpine tar -C /mnt -cj . > data-volumes.tar.bz2
Make sure to test the resulting archive in case something went wrong:
tar -tjf data-volumes.tar.bz2
How to redirect a url in NGINX
Similar to another answer here, but change the http in the rewrite to to $scheme like so:
server {
listen 80;
server_name test.com;
rewrite ^ $scheme://www.test.com$request_uri? permanent;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
I had to do this to redirect www.test.com to test.com.
Remove substring from the string
If I'm interpreting right, this question seems to ask for something like a minus (-) operation between strings, i.e. the opposite of the built-in plus (+) operation (concatenation).
Unlike the previous answers, I'm trying to define such an operation that must obey the property:
IF c = a + b THEN c - a = b AND c - b = a
We need only three built-in Ruby methods to achieve this:
'abracadabra'.partition('abra').values_at(0,2).join == 'cadabra'
.
I won't explain how it works because it can be easily understood running one method at a time.
Here is a proof of concept code:
# minus_string.rb
class String
def -(str)
partition(str).values_at(0,2).join
end
end
# Add the following code and issue 'ruby minus_string.rb' in the console to test
require 'minitest/autorun'
class MinusString_Test < MiniTest::Test
A,B,C='abra','cadabra','abracadabra'
def test_C_eq_A_plus_B
assert C == A + B
end
def test_C_minus_A_eq_B
assert C - A == B
end
def test_C_minus_B_eq_A
assert C - B == A
end
end
One last word of advice if you're using a recent Ruby version (>= 2.0): use Refinements instead of monkey-patching String like in the previous example.
It is as easy as:
module MinusString
refine String do
def -(str)
partition(str).values_at(0,2).join
end
end
end
and add using MinusString
before the blocks where you need it.
How to get a substring of text?
Use String#slice
, also aliased as []
.
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
How to check if all of the following items are in a list?
This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.
>>> case = "caseCamel"
>>> label = "Case Camel"
>>> list = ["apple", "banana"]
>>>
>>> (case or label) in list
False
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
True
>>> (case and label) in list
False
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list
True
>>>
and if you have a looong list of variables held in a sublist variable
>>>
>>> list = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case = "caseCamel"
>>>
>>> sublist = ["unique banana", "very unique banana"]
>>>
>>> # example for if any (at least one) item contained in superset (or statement)
...
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
False
>>>
>>> sublist[0] = label
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>> # example for whether a subset (all items) contained in superset (and statement)
...
>>> # a bit of demorgan's law
...
>>> next((False for item in sublist if item not in list), True)
False
>>>
>>> sublist[1] = case
>>>
>>> next((False for item in sublist if item not in list), True)
True
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>>
Auto-Submit Form using JavaScript
A simple solution for a delayed auto submit:
<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
<form action="https://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?
ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.
It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.
I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.
Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.
phantomjs not waiting for "full" page load
You could try a combination of the waitfor and rasterize examples:
/**
* See https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
*
* Wait until the test condition is true or a timeout occurs. Useful for waiting
* on a server response or for a ui change (fadeIn, etc.) to occur.
*
* @param testFx javascript condition that evaluates to a boolean,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param onReady what to do when testFx condition is fulfilled,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
*/
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()), //< defensive code
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
};
var page = require('webpage').create(), system = require('system'), address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
size = system.args[3].split('*');
page.paperSize = size.length === 2 ? {
width : size[0],
height : size[1],
margin : '0px'
} : {
format : system.args[3],
orientation : 'portrait',
margin : {
left : "5mm",
top : "8mm",
right : "5mm",
bottom : "9mm"
}
};
}
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
var resources = [];
page.onResourceRequested = function(request) {
resources[request.id] = request.stage;
};
page.onResourceReceived = function(response) {
resources[response.id] = response.stage;
};
page.open(address, function(status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
waitFor(function() {
// Check in the page if a specific element is now visible
for ( var i = 1; i < resources.length; ++i) {
if (resources[i] != 'end') {
return false;
}
}
return true;
}, function() {
page.render(output);
phantom.exit();
}, 10000);
}
});
}
What's the Kotlin equivalent of Java's String[]?
To create an empty Array of Strings in Kotlin you should use one of the following six approaches:
First approach:
val empty = arrayOf<String>()
Second approach:
val empty = arrayOf("","","")
Third approach:
val empty = Array<String?>(3) { null }
Fourth approach:
val empty = arrayOfNulls<String>(3)
Fifth approach:
val empty = Array<String>(3) { "it = $it" }
Sixth approach:
val empty = Array<String>(0, { _ -> "" })
How to populate options of h:selectOneMenu from database?
Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.
In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:
<p:selectOneListbox id="adminEvents" value="#{testBean.selectedEvent}">
... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}
, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.
Invalid column name sql error
Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:
Also make sure that your table has column name matches to Name
, PhoneNo
,Address
.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
How to Troubleshoot Intermittent SQL Timeout Errors
Bit of a long shot, but on a lab a while back, we had a situation where a SQL Server appeared unresponsive, not because we had spiked the CPU or anything we could track within SQL Server, it appeared operational to all tests but connections failed under some load.
The issue turned out to be due to the volume of traffic against the server meant we were triggering the in built windows Syn Attack Flood Protection within Windows. Annoyingly when you hit this, there is no logged message within windows server, or within SQL - you only see the symtpoms which are connections failing to be made - this is because windows slows down on accepting the messages and let's a queue build. From the connection standpoint, the server appears to not respond when it should (it doesn't even acknowledge the message arrived)
http://msdn.microsoft.com/en-us/library/ee377084(v=bts.10).aspx
Scroll down to SynAttackProtect and you will see the default in windows server 2003 sp1 onwards was to enable this feature by default. It is a DDOS protection mechanism in effect, and the lack of logging that it is triggering makes it incredibly difficult to detect when your server does this.
It took 3 days within the MS lab before it was figured out.
You mentioned 100 conenctions, we had an app that constantly connected, ran queries and then disconnected, it did not hold the connections open. This meant that we had multiple threads on each machine connectiong doing this, 10 machines, multiple threads per machine, and it was considered enough different connections consistently being made / dropped to trigger the defense.
Whether you are at that level (since it is not a clearly defined threshold by MS) is hard to say.
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)
Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.
You can either disable it by editing web.config to include the following:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
Or better yet properly configure it by modifying the Application_Start method in global.asax:
void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition
{
Path = "/~Scripts/jquery-2.1.1.min.js"
}
);
}
Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.
For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace @default
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
}
ASP.NET Web API session or something?
Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.
The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".
So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.
With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1
Code (though I wouldn't really recommend that):
public class MyHttpControllerHandler
: HttpControllerHandler, IRequiresSessionState
{
public MyHttpControllerHandler(RouteData routeData): base(routeData)
{ }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHttpControllerHandler(requestContext.RouteData);
}
}
public class ValuesController : ApiController
{
public string GET(string input)
{
var session = HttpContext.Current.Session;
if (session != null)
{
if (session["Time"] == null)
{
session["Time"] = DateTime.Now;
}
return "Session Time: " + session["Time"] + input;
}
return "Session is not availabe" + input;
}
}
and then add the HttpControllerHandler to your API route:
route.RouteHandler = new MyHttpControllerRouteHandler();
Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"
I think its related with jdbc.
I have a similar problem (missing param) when I have a where condition like this:
a = :namedparameter and b = :namedparameter
It's ok, When I have like this:
a = :namedparameter and b = :namedparameter2 (the two param has the same value)
So it's a problem with named parameters.
I think there is a bug around named parameter handling, it looks like if only the first parameter get the right value, the second is not set by driver classes. Maybe its not a bug, only I don't know something, but anyway I guess that's the reason for the difference between the SQL dev and the sqlplus running for you, because as far as I know SQL developer uses jdbc driver.
How to validate IP address in Python?
I think this would do it...
def validIP(address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
if not 0 <= int(item) <= 255:
return False
return True
Spring Boot not serving static content
I'm using Spring Boot 2.2 and not getting any of my static content. I discovered two solutions that worked for me:
Option #1 - Stop using @EnableWebMvc
annotation
This annotation disables some automatic configuration, including the part that automatically serves static content from commonly-used locations like /src/main/resources/static
. If you don't really need @EnableWebMvc
, then just remove it from your @Configuration
class.
Option #2 - Implement WebMvcConfigurer
in your @EnableWebMvc
annotated class and implementaddResourceHandlers()
Do something like this:
@EnableWebMvc
@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/vendor/**").addResourceLocations("classpath:/static/vendor/");
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
Just remember that your code is now in charge of managing all static resource paths.
MySQL - Make an existing Field Unique
The easiest and fastest way would be with phpmyadmin structure table.
There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.
How to call two methods on button's onclick method in HTML or JavaScript?
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
Read a file line by line assigning the value to a variable
If you need to process both the input file and user input (or anything else from stdin), then use the following solution:
#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
read -p "> $line (Press Enter to continue)"
done
Based on the accepted answer and on the bash-hackers redirection tutorial.
Here, we open the file descriptor 3 for the file passed as the script argument and tell read
to use this descriptor as input (-u 3
). Thus, we leave the default input descriptor (0) attached to a terminal or another input source, able to read user input.
How to convert An NSInteger to an int?
I'm not sure about the circumstances where you need to convert an NSInteger
to an int
.
NSInteger is just a typedef:
NSInteger
Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
You can use NSInteger
any place you use an int
without converting it.
Pip Install not installing into correct directory?
Virtualenv is your friend
Even if you want to add a package to your primary install, it's still best to do it in a virtual environment first, to ensure compatibility with your other packages. However, if you get familiar with virtualenv, you'll probably find there's really no reason to install anything in your base install.
How can I use interface as a C# generic type constraint?
For some time now I've been thinking about near-compile-time constraints, so this is a perfect opportunity to launch the concept.
The basic idea is that if you cannot do a check compile time, you should do it at the earliest possible point in time, which is basically the moment the application starts. If all checks are okay, the application will run; if a check fails, the application will fail instantly.
Behavior
The best possible outcome is that our program doesn't compile if the constraints are not met. Unfortunately that's not possible in the current C# implementation.
Next best thing is that the program crashes the moment it's started.
The last option is that the program will crash the moment the code is hit. This is the default behavior of .NET. For me, this is completely unacceptable.
Prerequirements
We need to have a constraint mechanism, so for the lack of anything better... let's use an attribute. The attribute will be present on top of a generic constraint to check if it matches our conditions. If it doesn't, we give an ugly error.
This enables us to do things like this in our code:
public class Clas<[IsInterface] T> where T : class
(I've kept the where T:class
here, because I always prefer compile-time checks to run-time checks)
So, that only leaves us with 1 problem, which is checking if all the types that we use match the constraint. How hard can it be?
Let's break it up
Generic types are always either on a class (/struct/interface) or on a method.
Triggering a constraint requires you to do one of the following things:
- Compile-time, when using a type in a type (inheritance, generic constraint, class member)
- Compile-time, when using a type in a method body
- Run-time, when using reflection to construct something based on the generic base class.
- Run-time, when using reflection to construct something based on RTTI.
At this point, I would like to state that you should always avoid doing (4) in any program IMO. Regardless, these checks won't support it, since it would effectively mean solving the halting problem.
Case 1: using a type
Example:
public class TestClass : SomeClass<IMyInterface> { ... }
Example 2:
public class TestClass
{
SomeClass<IMyInterface> myMember; // or a property, method, etc.
}
Basically this involves scanning all types, inheritance, members, parameters, etc, etc, etc. If a type is a generic type and has a constraint, we check the constraint; if it's an array, we check the element type.
At this point I must add that this will break the fact that by default .NET loads types 'lazy'. By scanning all the types, we force the .NET runtime to load them all. For most programs this shouldn't be a problem; still, if you use static initializers in your code, you might encounter problems with this approach... That said, I wouldn't advice anyone to do this anyways (except for things like this :-), so it shouldn't give you a lot of problems.
Case 2: using a type in a method
Example:
void Test() {
new SomeClass<ISomeInterface>();
}
To check this we have only 1 option: decompile the class, check all member tokens that are used and if one of them is the generic type - check the arguments.
Case 3: Reflection, runtime generic construction
Example:
typeof(CtorTest<>).MakeGenericType(typeof(IMyInterface))
I suppose it's theoretically possible to check this with similar tricks as case (2), but the implementation of it is much harder (you need to check if MakeGenericType
is called in some code path). I won't go into details here...
Case 4: Reflection, runtime RTTI
Example:
Type t = Type.GetType("CtorTest`1[IMyInterface]");
This is the worst case scenario and as I explained before generally a bad idea IMHO. Either way, there's no practical way to figure this out using checks.
Testing the lot
Creating a program that tests case (1) and (2) will result in something like this:
[AttributeUsage(AttributeTargets.GenericParameter)]
public class IsInterface : ConstraintAttribute
{
public override bool Check(Type genericType)
{
return genericType.IsInterface;
}
public override string ToString()
{
return "Generic type is not an interface";
}
}
public abstract class ConstraintAttribute : Attribute
{
public ConstraintAttribute() {}
public abstract bool Check(Type generic);
}
internal class BigEndianByteReader
{
public BigEndianByteReader(byte[] data)
{
this.data = data;
this.position = 0;
}
private byte[] data;
private int position;
public int Position
{
get { return position; }
}
public bool Eof
{
get { return position >= data.Length; }
}
public sbyte ReadSByte()
{
return (sbyte)data[position++];
}
public byte ReadByte()
{
return (byte)data[position++];
}
public int ReadInt16()
{
return ((data[position++] | (data[position++] << 8)));
}
public ushort ReadUInt16()
{
return (ushort)((data[position++] | (data[position++] << 8)));
}
public int ReadInt32()
{
return (((data[position++] | (data[position++] << 8)) | (data[position++] << 0x10)) | (data[position++] << 0x18));
}
public ulong ReadInt64()
{
return (ulong)(((data[position++] | (data[position++] << 8)) | (data[position++] << 0x10)) | (data[position++] << 0x18) |
(data[position++] << 0x20) | (data[position++] << 0x28) | (data[position++] << 0x30) | (data[position++] << 0x38));
}
public double ReadDouble()
{
var result = BitConverter.ToDouble(data, position);
position += 8;
return result;
}
public float ReadSingle()
{
var result = BitConverter.ToSingle(data, position);
position += 4;
return result;
}
}
internal class ILDecompiler
{
static ILDecompiler()
{
// Initialize our cheat tables
singleByteOpcodes = new OpCode[0x100];
multiByteOpcodes = new OpCode[0x100];
FieldInfo[] infoArray1 = typeof(OpCodes).GetFields();
for (int num1 = 0; num1 < infoArray1.Length; num1++)
{
FieldInfo info1 = infoArray1[num1];
if (info1.FieldType == typeof(OpCode))
{
OpCode code1 = (OpCode)info1.GetValue(null);
ushort num2 = (ushort)code1.Value;
if (num2 < 0x100)
{
singleByteOpcodes[(int)num2] = code1;
}
else
{
if ((num2 & 0xff00) != 0xfe00)
{
throw new Exception("Invalid opcode: " + num2.ToString());
}
multiByteOpcodes[num2 & 0xff] = code1;
}
}
}
}
private ILDecompiler() { }
private static OpCode[] singleByteOpcodes;
private static OpCode[] multiByteOpcodes;
public static IEnumerable<ILInstruction> Decompile(MethodBase mi, byte[] ildata)
{
Module module = mi.Module;
BigEndianByteReader reader = new BigEndianByteReader(ildata);
while (!reader.Eof)
{
OpCode code = OpCodes.Nop;
int offset = reader.Position;
ushort b = reader.ReadByte();
if (b != 0xfe)
{
code = singleByteOpcodes[b];
}
else
{
b = reader.ReadByte();
code = multiByteOpcodes[b];
b |= (ushort)(0xfe00);
}
object operand = null;
switch (code.OperandType)
{
case OperandType.InlineBrTarget:
operand = reader.ReadInt32() + reader.Position;
break;
case OperandType.InlineField:
if (mi is ConstructorInfo)
{
operand = module.ResolveField(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
}
else
{
operand = module.ResolveField(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
}
break;
case OperandType.InlineI:
operand = reader.ReadInt32();
break;
case OperandType.InlineI8:
operand = reader.ReadInt64();
break;
case OperandType.InlineMethod:
try
{
if (mi is ConstructorInfo)
{
operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
}
else
{
operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
}
}
catch
{
operand = null;
}
break;
case OperandType.InlineNone:
break;
case OperandType.InlineR:
operand = reader.ReadDouble();
break;
case OperandType.InlineSig:
operand = module.ResolveSignature(reader.ReadInt32());
break;
case OperandType.InlineString:
operand = module.ResolveString(reader.ReadInt32());
break;
case OperandType.InlineSwitch:
int count = reader.ReadInt32();
int[] targetOffsets = new int[count];
for (int i = 0; i < count; ++i)
{
targetOffsets[i] = reader.ReadInt32();
}
int pos = reader.Position;
for (int i = 0; i < count; ++i)
{
targetOffsets[i] += pos;
}
operand = targetOffsets;
break;
case OperandType.InlineTok:
case OperandType.InlineType:
try
{
if (mi is ConstructorInfo)
{
operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes);
}
else
{
operand = module.ResolveMember(reader.ReadInt32(), mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments());
}
}
catch
{
operand = null;
}
break;
case OperandType.InlineVar:
operand = reader.ReadUInt16();
break;
case OperandType.ShortInlineBrTarget:
operand = reader.ReadSByte() + reader.Position;
break;
case OperandType.ShortInlineI:
operand = reader.ReadSByte();
break;
case OperandType.ShortInlineR:
operand = reader.ReadSingle();
break;
case OperandType.ShortInlineVar:
operand = reader.ReadByte();
break;
default:
throw new Exception("Unknown instruction operand; cannot continue. Operand type: " + code.OperandType);
}
yield return new ILInstruction(offset, code, operand);
}
}
}
public class ILInstruction
{
public ILInstruction(int offset, OpCode code, object operand)
{
this.Offset = offset;
this.Code = code;
this.Operand = operand;
}
public int Offset { get; private set; }
public OpCode Code { get; private set; }
public object Operand { get; private set; }
}
public class IncorrectConstraintException : Exception
{
public IncorrectConstraintException(string msg, params object[] arg) : base(string.Format(msg, arg)) { }
}
public class ConstraintFailedException : Exception
{
public ConstraintFailedException(string msg) : base(msg) { }
public ConstraintFailedException(string msg, params object[] arg) : base(string.Format(msg, arg)) { }
}
public class NCTChecks
{
public NCTChecks(Type startpoint)
: this(startpoint.Assembly)
{ }
public NCTChecks(params Assembly[] ass)
{
foreach (var assembly in ass)
{
assemblies.Add(assembly);
foreach (var type in assembly.GetTypes())
{
EnsureType(type);
}
}
while (typesToCheck.Count > 0)
{
var t = typesToCheck.Pop();
GatherTypesFrom(t);
PerformRuntimeCheck(t);
}
}
private HashSet<Assembly> assemblies = new HashSet<Assembly>();
private Stack<Type> typesToCheck = new Stack<Type>();
private HashSet<Type> typesKnown = new HashSet<Type>();
private void EnsureType(Type t)
{
// Don't check for assembly here; we can pass f.ex. System.Lazy<Our.T<MyClass>>
if (t != null && !t.IsGenericTypeDefinition && typesKnown.Add(t))
{
typesToCheck.Push(t);
if (t.IsGenericType)
{
foreach (var par in t.GetGenericArguments())
{
EnsureType(par);
}
}
if (t.IsArray)
{
EnsureType(t.GetElementType());
}
}
}
private void PerformRuntimeCheck(Type t)
{
if (t.IsGenericType && !t.IsGenericTypeDefinition)
{
// Only check the assemblies we explicitly asked for:
if (this.assemblies.Contains(t.Assembly))
{
// Gather the generics data:
var def = t.GetGenericTypeDefinition();
var par = def.GetGenericArguments();
var args = t.GetGenericArguments();
// Perform checks:
for (int i = 0; i < args.Length; ++i)
{
foreach (var check in par[i].GetCustomAttributes(typeof(ConstraintAttribute), true).Cast<ConstraintAttribute>())
{
if (!check.Check(args[i]))
{
string error = "Runtime type check failed for type " + t.ToString() + ": " + check.ToString();
Debugger.Break();
throw new ConstraintFailedException(error);
}
}
}
}
}
}
// Phase 1: all types that are referenced in some way
private void GatherTypesFrom(Type t)
{
EnsureType(t.BaseType);
foreach (var intf in t.GetInterfaces())
{
EnsureType(intf);
}
foreach (var nested in t.GetNestedTypes())
{
EnsureType(nested);
}
var all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
foreach (var field in t.GetFields(all))
{
EnsureType(field.FieldType);
}
foreach (var property in t.GetProperties(all))
{
EnsureType(property.PropertyType);
}
foreach (var evt in t.GetEvents(all))
{
EnsureType(evt.EventHandlerType);
}
foreach (var ctor in t.GetConstructors(all))
{
foreach (var par in ctor.GetParameters())
{
EnsureType(par.ParameterType);
}
// Phase 2: all types that are used in a body
GatherTypesFrom(ctor);
}
foreach (var method in t.GetMethods(all))
{
if (method.ReturnType != typeof(void))
{
EnsureType(method.ReturnType);
}
foreach (var par in method.GetParameters())
{
EnsureType(par.ParameterType);
}
// Phase 2: all types that are used in a body
GatherTypesFrom(method);
}
}
private void GatherTypesFrom(MethodBase method)
{
if (this.assemblies.Contains(method.DeclaringType.Assembly)) // only consider methods we've build ourselves
{
MethodBody methodBody = method.GetMethodBody();
if (methodBody != null)
{
// Handle local variables
foreach (var local in methodBody.LocalVariables)
{
EnsureType(local.LocalType);
}
// Handle method body
var il = methodBody.GetILAsByteArray();
if (il != null)
{
foreach (var oper in ILDecompiler.Decompile(method, il))
{
if (oper.Operand is MemberInfo)
{
foreach (var type in HandleMember((MemberInfo)oper.Operand))
{
EnsureType(type);
}
}
}
}
}
}
}
private static IEnumerable<Type> HandleMember(MemberInfo info)
{
// Event, Field, Method, Constructor or Property.
yield return info.DeclaringType;
if (info is EventInfo)
{
yield return ((EventInfo)info).EventHandlerType;
}
else if (info is FieldInfo)
{
yield return ((FieldInfo)info).FieldType;
}
else if (info is PropertyInfo)
{
yield return ((PropertyInfo)info).PropertyType;
}
else if (info is ConstructorInfo)
{
foreach (var par in ((ConstructorInfo)info).GetParameters())
{
yield return par.ParameterType;
}
}
else if (info is MethodInfo)
{
foreach (var par in ((MethodInfo)info).GetParameters())
{
yield return par.ParameterType;
}
}
else if (info is Type)
{
yield return (Type)info;
}
else
{
throw new NotSupportedException("Incorrect unsupported member type: " + info.GetType().Name);
}
}
}
Using the code
Well, that's the easy part :-)
// Create something illegal
public class Bar2 : IMyInterface
{
public void Execute()
{
throw new NotImplementedException();
}
}
// Our fancy check
public class Foo<[IsInterface] T>
{
}
class Program
{
static Program()
{
// Perform all runtime checks
new NCTChecks(typeof(Program));
}
static void Main(string[] args)
{
// Normal operation
Console.WriteLine("Foo");
Console.ReadLine();
}
}
Ajax request returns 200 OK, but an error event is fired instead of success
I have the similar problem but when I tried to remove the datatype:'json'
I still have the problem.
My error is executing instead of the Success
function cmd(){
var data = JSON.stringify(display1());
$.ajax({
type: 'POST',
url: '/cmd',
contentType:'application/json; charset=utf-8',
//dataType:"json",
data: data,
success: function(res){
console.log('Success in running run_id ajax')
//$.ajax({
// type: "GET",
// url: "/runid",
// contentType:"application/json; charset=utf-8",
// dataType:"json",
// data: data,
// success:function display_runid(){}
// });
},
error: function(req, err){ console.log('my message: ' + err); }
});
}
How can you run a Java program without main method?
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.
Default port for SQL Server
SQL Server default port is 1434.
To allow remote access I had to release those ports on my firewall:
Protocol | Port
---------------------
UDP | 1050
TCP | 1050
TCP | 1433
UDP | 1434
Const in JavaScript: when to use it and is it necessary?
In my experience I use const when I want to set something I may want to change later without having to hunt through the code looking for bits that have been hard coded e.g. A file path or server name.
The error in your testing is another thing though, you are tring to make another variable called x, this would be a more accurate test.
const x = 'const';
x = 'not-const';
Getting multiple selected checkbox values in a string in javascript and PHP
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
Default password of mysql in ubuntu server 16.04
I think another place to look is /var/lib
.
If you go there you can see three mysql folders with 'interesting' permissions:
user group
mysql mysql
Here is what I did to solve my problem with root password:
after running
sudo apt-get purge mysql*
sudo rm -rf /etc/mysql
I also ran the following (instead of my_username put yours):
cd /var/lib
sudo chown --from=mysql <my_username> mysql* -R
sudo rm -rf mysql*
And then:
sudo apt-get install mysql-server
which prompted me to select a new root password.
I hope it helps
How to center body on a page?
Also apply text-align: center; on the html element like so:
html {
text-align: center;
}
A better approach though is to have an inner container div, which will be centralized, and not the body.
Setting a JPA timestamp column to be generated by the database?
If you are doing development in Java 8 and Hibernate 5 Or Spring Boot JPA then use following annotation directly
in your Entity class. Hibernate gets the current timestamp from the VM and will insert date and time in database.
public class YourEntity {
@Id
@GeneratedValue
private Long id;
private String name;
@CreationTimestamp
private LocalDateTime createdDateTime;
@UpdateTimestamp
private LocalDateTime updatedDateTime;
…
}
XPath to fetch SQL XML value
Update
My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:
select x.value(N'../../../../@stepId', N'int') as StepID
, x.value(N'../../@id', N'int') as ComponentID
, x.value(N'@nom',N'nvarchar(100)') as Nom
, x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)
However, if you must use an XPath that retrieves exactly the value of interest:
select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled"]') t(x)
If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.
And finaly if all you need is to check for existance you can use the exist() XML method:
select @x.exist(
N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled" and @valeur="Yes"]')
How to make background of table cell transparent
What is this? :)
background-color: #D8F0DA;
Try
background: none
And override works only if property is exactly the same.
background doesn't override background-color.
If you want alpha transparency, then use something like this
background: rgba(100, 100, 100, 0.5);
The type is defined in an assembly that is not referenced, how to find the cause?
For me the reason why the error appeared was that the WebForm where the error was reported has been moved from another folder, but the name of its codefile class remained unchanged and didn't correspond to the actual path.
Initial state:
Original file path: /Folder1/Subfolder1/MyWebForm.aspx.cs
Original codefile class name: Folder1_Subfolder1_MyWebForm
After the file was moved:
File path: /Folder1/MyWebForm.aspx.cs
Codefile class name (unchanged, with the error shown): Folder1_Subfolder1_MyWebForm
The solution:
Rename your codefile class Folder1_Subfolder1_MyWebForm
to one corresponding with the new path: Folder1_MyWebForm
All at once - problem solved, no errors reporting..
How do I access an access array item by index in handlebars?
In my case I wanted to access an array inside a custom helper like so,
{{#ifCond arr.[@index] "foo" }}
Which did not work, but the answer suggested by @julesbou worked.
Working code:
{{#ifCond (lookup arr @index) "" }}
Hope this helps! Cheers.
Open Facebook page from Android app?
Here's the way to do it in 2016. It works great, and is very simple to use.
I discovered this after looking into how emails sent by Facebook opened the Facebook app.
// e.g. if your URL is https://www.facebook.com/EXAMPLE_PAGE, you should
// put EXAMPLE_PAGE at the end of this URL, after the ?
String YourPageURL = "https://www.facebook.com/n/?YOUR_PAGE_NAME";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(YourPageURL));
startActivity(browserIntent);
Could not load the Tomcat server configuration
I had the same problem in Eclipse Oxygen with Tomcat 8 in ubuntu 16.04 LTS.
Solution:
1. Give permission to entire tomcat folder (chmod 777 -R /Tomcat)
2. Delete and re-add the server in eclipse
3. Restart eclipse
4. Start the tomcat server. It will work..........
Connection refused on docker container
You need to publish the exposed ports by using the following options:
-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.
-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.
The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo
and check which random ports are being used from your host at the Ports section.
Just run the following command:
docker run -it -p 8080:8080 demo
After that your url will work.
How to check if a variable is a dictionary in Python?
How would you check if a variable is a dictionary in Python?
This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict
.
(Note that you should also not use dict
as a variable name - it's the name of the builtin object.)
If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.
I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.
is
is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.
So I will provide several options that do.
Supporting inheritance:
This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict
, defaultdict
, or Counter
from the collections module:
if isinstance(any_object, dict):
But there are even more flexible options.
Supporting abstractions:
from collections.abc import Mapping
if isinstance(any_object, Mapping):
This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict
, and still get the correct behavior.
Use the interface
You commonly hear the OOP advice, "program to an interface".
This strategy takes advantage of Python's polymorphism or duck-typing.
So just attempt to access the interface, catching the specific expected errors (AttributeError
in case there is no .items
and TypeError
in case items
is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems()
is gone in Python 3):
try:
items = any_object.items()
except (AttributeError, TypeError):
non_items_behavior(any_object)
else: # no exception raised
for item in items: ...
Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.
Conclusion
Don't use is
to check types for standard control flow. Use isinstance
, consider abstractions like Mapping
or MutableMapping
, and consider avoiding type-checking altogether, using the interface directly.
add string to String array
you would have to write down some method to create a temporary array and then copy it like
public String[] increaseArray(String[] theArray, int increaseBy)
{
int i = theArray.length;
int n = ++i;
String[] newArray = new String[n];
for(int cnt=0;cnt<theArray.length;cnt++)
{
newArray[cnt] = theArray[cnt];
}
return newArray;
}
or The ArrayList would be helpful to resolve your problem.
Having services in React application
I also came from Angular.js area and the services and factories in React.js are more simple.
You can use plain functions or classes, callback style and event Mobx like me :)
_x000D_
_x000D_
// Here we have Service class > dont forget that in JS class is Function_x000D_
class HttpService {_x000D_
constructor() {_x000D_
this.data = "Hello data from HttpService";_x000D_
this.getData = this.getData.bind(this);_x000D_
}_x000D_
_x000D_
getData() {_x000D_
return this.data;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
// Making Instance of class > it's object now_x000D_
const http = new HttpService();_x000D_
_x000D_
_x000D_
// Here is React Class extended By React_x000D_
class ReactApp extends React.Component {_x000D_
state = {_x000D_
data: ""_x000D_
};_x000D_
_x000D_
componentDidMount() {_x000D_
const data = http.getData();_x000D_
_x000D_
this.setState({_x000D_
data: data_x000D_
});_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <div>{this.state.data}</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<ReactApp />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Here is simple example :
Calling async method on button click
This is what's killing you:
task.Wait();
That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...
There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:
private async void Button_Click(object sender, RoutedEventArgs
{
Task<List<MyObject>> task = GetResponse<MyObject>("my url");
var items = await task;
// Presumably use items here
}
Or just:
private async void Button_Click(object sender, RoutedEventArgs
{
var items = await GetResponse<MyObject>("my url");
// Presumably use items here
}
Now instead of blocking until the task has completed, the Button_Click
method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)
Note that I would also rename GetResponse
to GetResponseAsync
for clarity.
Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
The recommended solution is to enable innodb_large_prefix
option of MySQL so you won't be getting into subsequent problems. And here is how to do that:
Open the my.ini
MySQL configuration file and add the below lines under the [mysqld]
line like this.
[mysqld]
innodb_file_format = Barracuda
innodb_large_prefix = 1
innodb_file_per_table = ON
After that, save your changes and restart your MySQL service.
Rollback if you need to and then re-run your migration.
Just in case your problem still persists, go to your database configuration file and set
'engine' => null,
to 'engine' => 'innodb row_format=dynamic'
Hope it helps!
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
What Is It?
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.
When It Is Thrown
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException
to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1
(where Length
is total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can't use Array.Length
for both dimension, you have to use Array.GetLength()
:
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color
. Each item represents a pixel, indices are from (0, 0)
to (imageWidth - 1, imageHeight - 1)
.
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]
:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException
for this code (for example if you're using GetPixel
method on a Bitmap
class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>()
, this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don't forget that valid indices are from 0
to Length - 1
. If you simply try to assign an item at Length
you'll get IndexOutOfRangeException
(this behavior may confuse you if you think they may increase with a syntax similar to Insert
method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray
will satisfy search condition because Array.IndexOf()
will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum
.
How it applies to List<T>
?
Same cases as array - range of valid indexes - 0 (List
's indexes always start with 0) to list.Count
- accessing elements outside of this range will cause the exception.
Note that List<T>
throws ArgumentOutOfRangeException
for the same cases where arrays use IndexOutOfRangeException
.
Unlike arrays, List<T>
starts empty - so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>
) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you're trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString()
will throw IndexOutOfRangeException
because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader
implementations (SqlDataReader
, OleDbDataReader
and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".
Others
There is another (documented) case when this exception is thrown: if, in DataView
, data column name being supplied to the DataViewSort
property is not valid.
How to Avoid
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0
with GetLowerBound(0)
and .Length
with GetUpperBound(0)
(of course if you have parameters of type System.Arra
y, it doesn't apply for T[]
). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it'll throw InvalidCastException
), that's why if your parameters are T[]
you're safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException
or ArgumentOutOfRangeException
). In the next example, wrong parameters may cause IndexOutOfRangeException
, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if
logic with Debug.Assert()
:
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert()
, throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf()
return value. If we know it may fail then it's better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
How to Debug
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:
array[index] = newValue;
You found your error, check how index
increases. Is it right? Check how array is allocated, is coherent with how index
increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.
If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).
The VB.NET side of the story
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
The VB.NET rule
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
Why are elementwise additions much faster in separate loops than in a combined loop?
OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.
There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.
@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.
That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.
The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.
Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:
It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)
It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)
The result using initialized data:
The result using uninitialized data (this is what Mysticial tested):
And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:
Proposal
Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.
Removing duplicates from a SQL query (not just "use distinct")
You need to tell the query what value to pick for the other columns, MIN
or MAX
seem like suitable choices.
SELECT
U.NAME, MIN(P.PIC_ID)
FROM
USERS U,
PICTURES P,
POSTINGS P1
WHERE
U.EMAIL_ID = P1.EMAIL_ID AND
P1.PIC_ID = P.PIC_ID AND
P.CAPTION LIKE '%car%'
GROUP BY
U.NAME;
Excel VBA Open a Folder
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
Foreach loop, determine which is the last iteration of the loop
As Shimmy has pointed out, using Last() can be a performance problem, for instance if your collection is the live result of a LINQ expression. To prevent multiple iterations, you could use a "ForEach" extension method like this:
var elements = new[] { "A", "B", "C" };
elements.ForEach((element, info) => {
if (!info.IsLast) {
Console.WriteLine(element);
} else {
Console.WriteLine("Last one: " + element);
}
});
The extension method looks like this (as an added bonus, it will also tell you the index and if you're looking at the first element):
public static class EnumerableExtensions {
public delegate void ElementAction<in T>(T element, ElementInfo info);
public static void ForEach<T>(this IEnumerable<T> elements, ElementAction<T> action) {
using (IEnumerator<T> enumerator = elements.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
action(current, new ElementInfo(index, isFirst, !hasNext));
isFirst = false;
index++;
}
}
}
public struct ElementInfo {
public ElementInfo(int index, bool isFirst, bool isLast)
: this() {
Index = index;
IsFirst = isFirst;
IsLast = isLast;
}
public int Index { get; private set; }
public bool IsFirst { get; private set; }
public bool IsLast { get; private set; }
}
}
How to add a footer to the UITableView?
These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate
.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if (section == 0)
{
// to hide footer for section 0
return 0.0;
}
else
{
// show footer for every section except section 0
return HEIGHT_YOU_WANT;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *footerView = [[UIView alloc] init];
footerView.backgroundColor = [UIColor blackColor];
return footerView;
}
Swift
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = UIColor.black
return footerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
// to hide footer for section 0
return 0.0
} else {
// show footer for every section except section 0
return HEIGHT_YOU_WANT
}
}
Can you remove elements from a std::list while iterating through it?
Iterating backwards avoids the effect of erasing an element on the remaining elements to be traversed:
typedef list<item*> list_t;
for ( list_t::iterator it = items.end() ; it != items.begin() ; ) {
--it;
bool remove = <determine whether to remove>
if ( remove ) {
items.erase( it );
}
}
PS: see this, e.g., regarding backward iteration.
PS2: I did not thoroughly tested if it handles well erasing elements at the ends.
Using array map to filter results with if conditional
You're looking for the .filter()
function:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
});
That'll produce an array that contains only those objects whose "selected" property is true
(or truthy).
edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
}).map(function(obj) { return obj.id; });
Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck()
function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.
How do I configure git to ignore some files locally?
From the relevant Git documentation:
Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the $GIT_DIR/info/exclude
file.
The .git/info/exclude
file has the same format as any .gitignore
file. Another option is to set core.excludesFile
to the name of a file containing global patterns.
Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:
git update-index --assume-unchanged <file-list>
Note on $GIT_DIR
: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.
Edit: Another way is to use:
git update-index --skip-worktree <file-list>
Reverse it by:
git update-index --no-skip-worktree <file-list>
AngularJS - Access to child scope
Yes, we can assign variables from child controller to the variables in parent controller. This is one possible way:
Overview: The main aim of the code, below, is to assign child controller's $scope.variable to parent controller's $scope.assign
Explanation: There are two controllers. In the html, notice that the parent controller encloses the child controller. That means the parent controller will be executed before child controller. So, first setValue() will be defined and then the control will go to the child controller. $scope.variable will be assigned as "child". Then this child scope will be passed as an argument to the function of parent controller, where $scope.assign will get the value as "child"
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('child',function($scope){
$scope.variable = "child";
$scope.$parent.setValue($scope);
});
app.controller('parent',function($scope){
$scope.setValue = function(childscope) {
$scope.assign = childscope.variable;
}
});
</script>
<body ng-app="myApp">
<div ng-controller="parent">
<p>this is parent: {{assign}}</p>
<div ng-controller="child">
<p>this is {{variable}}</p>
</div>
</div>
</body>
</html>
Going to a specific line number using Less in Unix
To open at a specific line straight from the command line, use:
less +320123 filename
If you want to see the line numbers too:
less +320123 -N filename
You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:
less +320123 -j 10 filename
Apply CSS rules to a nested class inside a div
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text
with the class name title
. If you use >
instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
Axios having CORS issue
May help to someone:
I'm sending data from react
application to golang
server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*")
. Error has fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
JavaScript set object key by variable
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
_x000D_
_x000D_
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
_x000D_
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
_x000D_
_x000D_
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
_x000D_
_x000D_
Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)
Short answer
For those who are already familiar with setting up a RecyclerView
to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager
instead of a LinearLayoutManager
when you set the RecyclerView
up.
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
If you need more help than that, then check out the following example.
Full example
The following is a minimal example that will look like the image below.
Start with an empty activity. You will perform the following tasks to add the RecyclerView
grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.
- Add dependencies to gradle
- Add the xml layout files for the activity and for the grid cell
- Make the RecyclerView adapter
- Initialize the RecyclerView in your activity
Update Gradle dependencies
Make sure the following dependencies are in your app gradle.build
file:
compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'
You can update the version numbers to whatever is the most current.
Create activity layout
Add the RecyclerView
to your xml layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rvNumbers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Create grid cell layout
Each cell in our RecyclerView
grid is only going to have a single TextView
. Create a new layout resource file.
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="5dp"
android:layout_width="50dp"
android:layout_height="50dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@color/colorAccent"/>
</LinearLayout>
Create the adapter
The RecyclerView
needs an adapter to populate the views in each cell with your data. Create a new java file.
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private String[] mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myTextView.setText(mData[position]);
}
// total number of cells
@Override
public int getItemCount() {
return mData.length;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.info_text);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return mData[id];
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Notes
- Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old
GridView
and is a common need. You can remove this code if you don't need it.
Initialize RecyclerView in Activity
Add the following code to your main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvNumbers);
int numberOfColumns = 6;
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
adapter = new MyRecyclerViewAdapter(this, data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
}
}
Notes
- Notice that the activity implements the
ItemClickListener
that we defined in our adapter. This allows us to handle cell click events in onItemClick
.
Finished
That's it. You should be able to run your project now and get something similar to the image at the top.
Going on
Rounded corners
Auto-fitting columns
Further study
Possible to make labels appear when hovering over a point in matplotlib?
The other answers did not address my need for properly showing tooltips in a recent version of Jupyter inline matplotlib figure. This one works though:
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
np.random.seed(42)
fig, ax = plt.subplots()
ax.scatter(*np.random.random((2, 26)))
ax.set_title("Mouse over a point")
crs = mplcursors.cursor(ax,hover=True)
crs.connect("add", lambda sel: sel.annotation.set_text(
'Point {},{}'.format(sel.target[0], sel.target[1])))
plt.show()
Leading to something like the following picture when going over a point with mouse:
Where's my invalid character (ORA-00911)
If you use the string literal exactly as you have shown us, the problem is the ;
character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT
should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL
. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();