The static
block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}
In case anyone else comes across this in a search for an answer...
The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.
Go here and get a number generated. Use any expiry date and CVV
https://ppmts.custhelp.com/app/answers/detail/a_id/750/
It's worked every time for me so far...
try this...
public class Student
{
public int Grade { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name{0} : Grade{1}", Name, Grade);
}
}
class Program
{
static void Main(string[] args)
{
List<Student> listStudents = new List<Student>();
listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });
listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
}
}
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.
Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)
#container {
height:500px;
min-height:500px;
}
Method 1:
If the method DoSomethingBeta was static you need only call:
Beta.DoSomethingBeta();
Method 2:
If Alpha extends from Beta you could call DoSomethingBeta() directly.
public class Alpha extends Beta{
public void DoSomethingAlpha() {
DoSomethingBeta(); //?
}
}
Method 3:
Alternatively you need to have access to an instance of Beta to call the methods from it.
public class Alpha {
public void DoSomethingAlpha() {
Beta cbeta = new Beta();
cbeta.DoSomethingBeta(); //?
}
}
Incidentally is this homework?
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
// this works on all browsers.
$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));
$('#checkbox1').change(function(e) {
this.checked = $(this).is(":checked") && !!confirm("Are you sure?");
$('#textbox1').val(this.checked);
return true;
});
});
I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/
div {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
width: 100px;
height: 100px;
background-color: #ccc;
}
You used to be able to do this, but GitHub removed this feature at some point mid-2013. To achieve this locally, you can do:
git log -g --grep=STRING
(Use the -g
flag if you want to search other branches and dangling commits.)
-g, --walk-reflogs
Instead of walking the commit ancestry chain, walk reflog entries from
the most recent one to older ones.
And the version of @Thomas in Groovy with takes the desired units in a list instead of hardcoding the values. This implementation (which can easily ported to Java - I made the function declaration explicit) makes Thomas approach more reuseable.
def fromDateTime = LocalDateTime.of(1968, 6, 14, 0, 13, 0)
def toDateTime = LocalDateTime.now()
def listOfUnits = [
ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS,
ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS,
ChronoUnit.MILLIS]
println calcDurationInTextualForm(listOfUnits, fromDateTime, toDateTime)
String calcDurationInTextualForm(List<ChronoUnit> listOfUnits, LocalDateTime ts, LocalDateTime to)
{
def result = []
listOfUnits.each { chronoUnit ->
long amount = ts.until(to, chronoUnit)
ts = ts.plus(amount, chronoUnit)
if (amount) {
result << "$amount ${chronoUnit.toString()}"
}
}
result.join(', ')
}
At the time of this writing,the code above returns 47 Years, 8 Months, 9 Days, 22 Hours, 52 Minutes, 7 Seconds, 140 Millis
. And, for @Gennady Kolomoets input, the code returns 23 Hours
.
When you provide a list of units it must be sorted by size of the units (biggest first):
def listOfUnits = [ChronoUnit.WEEKS, ChronoUnit.DAYS, ChronoUnit.HOURS]
// returns 2495 Weeks, 3 Days, 8 Hours
You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print
statement would throw up a SyntaxError
before it ever prompted you for input.
The result is that you're using Python 2's input
, which tries to eval
your input (presumably sdas
), finds that it's invalid Python, and dies.
AFAIK you can simply use
iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
// do somthing interesting to handle this situation
}
even if it is NULL.
You can use ApexSQL Search, it's a free SSMS and Visual Studio add-in and it can list all objects that reference a specific table column. It can also find data stored in tables and views. You can easily filter the results to show a specific database object type that references the column
Disclaimer: I work for ApexSQL as a Support Engineer
Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.
This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution
Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.
// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request
var http = require('http');
var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'
var client = http.createClient(80, 'www.example.com');
var headers = {
'Host': 'www.example.com',
'Cookie': cookie,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data,'utf8')
};
var request = client.request('POST', '/', headers);
// listening to the response is optional, I suppose
request.on('response', function(response) {
response.on('data', function(chunk) {
// do what you do
});
response.on('end', function() {
// do what you do
});
});
// you'd also want to listen for errors in production
request.write(data);
request.end();
What you send in the Cookie
value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes
If you want help an object go away, set its reference to null.
String x = "sadfasdfasd";
// do stuff
x = null;
Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.
I found that running a string shell command (sh -c) works best, for example:
find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;
.btn.active
or .btn.focus
alone cannot override Bootstrap's styles. For default theme:
.btn.active.focus, .btn.active:focus,
.btn.focus, .btn:active.focus,
.btn:active:focus, .btn:focus {
outline: none;
}
I try to join the solutions mention here as there are some important points to it needed to list.
As mentioned in the @igorw's answer the URL to repository must be in that case specified in the composer.json file, however since in both cases the composer.json must exist (unlike the 2nd way @Mike Graf) publishing it on the Packagist is not that much different (furthermore also Github currently provides packages services as npm packages), only difference instead of literally inputting the URL at the packagist interface once being signed up.
Moreover, it has a shortcoming that it cannot rely on an external library that uses this approach as recursive repository definitions do not work in Composer. Furthermore, due to it, there seems to be a "bug" upon it, since the recursive definition failed at the dependency, respecifying the repositories explicitly in the root does not seem to be enough but also all the dependencies from the packages would have to be respecified.
With a composer file (answered Oct 18 '12 at 15:13 igorw)
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
Without a composer file (answered Jan 23 '13 at 17:28 Mike Graf)
"repositories": [
{
"type":"package",
"package": {
"name": "l3pp4rd/doctrine-extensions",
"version":"master",
"source": {
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git",
"reference":"master"
}
}
}
],
"require": {
"l3pp4rd/doctrine-extensions": "master"
}
I encountered this error because I converted my data to an np.array
. I fixed the problem by converting my data to an np.matrix
instead and taking the transpose.
ValueError:
regr.fit(np.array(x_list), np.array(y_list))
Correct:
regr.fit(np.transpose(np.matrix(x_list)), np.transpose(np.matrix(y_list)))
Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.
For managed resources, the garbage collector will know when this is, and you don't need to do anything.
For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)
If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)
This is possible with <textarea>
the only thing you need to do is use
Summernote WYSIWYG editor
it interprets HTML tags inside a textarea (namely <strong>
, <i>
, <u>
, <a>
)
setval('sequence_name', sequence_value)
BindingResult is used for validation..
Example:-
public @ResponseBody String nutzer(@ModelAttribute(value="nutzer") Nutzer nutzer, BindingResult ergebnis){
String ergebnisText;
if(!ergebnis.hasErrors()){
nutzerList.add(nutzer);
ergebnisText = "Anzahl: " + nutzerList.size();
}else{
ergebnisText = "Error!!!!!!!!!!!";
}
return ergebnisText;
}
Although you must still either explicitly compare an optional with nil
or use optional binding to additionally extract its value (i.e. optionals are not implicitly converted into Boolean values), it's worth noting that Swift 2 has added the guard
statement to help avoid the pyramid of doom when working with multiple optional values.
In other words, your options now include explicitly checking for nil
:
if xyz != nil {
// Do something with xyz
}
Optional binding:
if let xyz = xyz {
// Do something with xyz
// (Note that we can reuse the same variable name)
}
And guard
statements:
guard let xyz = xyz else {
// Handle failure and then exit this code block
// e.g. by calling return, break, continue, or throw
return
}
// Do something with xyz, which is now guaranteed to be non-nil
Note how ordinary optional binding can lead to greater indentation when there is more than one optional value:
if let abc = abc {
if let xyz = xyz {
// Do something with abc and xyz
}
}
You can avoid this nesting with guard
statements:
guard let abc = abc else {
// Handle failure and then exit this code block
return
}
guard let xyz = xyz else {
// Handle failure and then exit this code block
return
}
// Do something with abc and xyz
It's not automatic, but doxygen will produce dependency diagrams for #included
files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.
If you are an admin and if you want to see the Gitlab version (and more you didn't know about) click on the wrench/admin menu icon and under Components you can see a lot , especially if you are using Omnibus.
None of the above worked out for me until I changed the Action as [HttpPost]
.
and made the ajax type as POST
.
[HttpPost]
public JsonResult GetSelectedSignalData(string signal1,...)
{
JsonResult result = new JsonResult();
var signalData = GetTheData();
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
result.Data = serializer.Serialize(signalData);
return Json(result, JsonRequestBehavior.AllowGet);
..
..
...
}
And the ajax call as
$.ajax({
type: "POST",
url: some_url,
data: JSON.stringify({ signal1: signal1,.. }),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data !== null) {
setValue();
}
},
failure: function (data) {
$('#errMessage').text("Error...");
},
error: function (data) {
$('#errMessage').text("Error...");
}
});
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
<form>
cannot go inside <p>
, no. The browser is going to abruptly close your <p>
element when it hits the opening <form>
tag as it tries to handle what it thinks is an unclosed paragraph element:
<p>Read this sentence
</p><form style='display:inline;'>
The trick is to use useradd
instead of its interactive wrapper adduser
.
I usually create users with:
RUN useradd -ms /bin/bash newuser
which creates a home directory for the user and ensures that bash is the default shell.
You can then add:
USER newuser
WORKDIR /home/newuser
to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser
:
docker run -t -i image
newuser@131b7ad86360:~$
You might have to give newuser
the permissions to execute the programs you intend to run before invoking the user command.
Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.
I took a look at this and I found that a WebView
doesn't seem to send click events to an OnClickListener
. If anyone out there can prove me wrong or tell me why then I'd be interested to hear it.
What I did find is that a WebView
will send touch events to an OnTouchListener
. It does have its own onTouchEvent
method but I only ever seemed to get MotionEvent.ACTION_MOVE
using that method.
So given that we can get events on a registered touch event listener, the only problem that remains is how to circumvent whatever action you want to perform for a touch when the user clicks a URL.
This can be achieved with some fancy Handler
footwork by sending a delayed message for the touch and then removing those touch messages if the touch was caused by the user clicking a URL.
Here's an example:
public class WebViewClicker extends Activity implements OnTouchListener, Handler.Callback {
private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;
private final Handler handler = new Handler(this);
private WebView webView;
private WebViewClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view_clicker);
webView = (WebView)findViewById(R.id.web);
webView.setOnTouchListener(this);
client = new WebViewClient(){
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
handler.sendEmptyMessage(CLICK_ON_URL);
return false;
}
};
webView.setWebViewClient(client);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl("http://www.example.com");
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
}
return false;
}
@Override
public boolean handleMessage(Message msg) {
if (msg.what == CLICK_ON_URL){
handler.removeMessages(CLICK_ON_WEBVIEW);
return true;
}
if (msg.what == CLICK_ON_WEBVIEW){
Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
Hope this helps.
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.
That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.
You should be able to do this like (as you're using the query api):
Entrant.where("pincode").ne(null)
... which will result in a mongo query resembling:
entrants.find({ pincode: { $ne: null } })
A few links that might help:
git stash show -p | git apply --reverse
Warning, that would not in every case: "git apply -R
"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).
This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).
See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit c23cd78, 02 Nov 2020)
apply
: when-R
, also reverse list of sectionsHelped-by: Junio C Hamano
Signed-off-by: Jonathan Tan
A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.
When applying that patch with
-R
, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.
What we want is: (1) deletion of a file, then (2) creation of a symlink.
In the code, this is reflected in the behavior of
previous_patch()
when invoked fromcheck_preimage()
when the deletion is checked.
Creation then deletion means that when the deletion is checked,previous_patch()
returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.But deletion then creation means that when the deletion is checked,
previous_patch()
returnsNULL
, so the deletion mode is checked against lstat, which is what we want.There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("
git-apply
: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R
"(man) fails in the same way, and this commit makes this case succeed.Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when
-R
is passed.
A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true
or false
.
.attr("hidden", false)
will remove the attribute the same as using .removeAttr("hidden")
.
.attr("hidden", "false")
is incorrect and the tag remains hidden.
You should not be setting hidden
, checked
, selected
, or several others to any string value to toggle it.
You can use ->child
to get a child element named child.
This element will contain the text of the child element.
But if you try var_dump()
on that variable, you will see it is not actually a PHP string.
The easiest way around this is to perform a strval(xml->child);
That will convert it to an actual PHP string.
This is useful when debugging when looping your XML and using var_dump()
to check the result.
So $s = strval($xml->child);
.
You should have :
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application
ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.
If you are using angular5 and above, please include the below method in your ts file.
async delay(ms: number) {
await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}
then call this delay() method wherever you want.
e.g:
validateInputValues() {
if (null == this.id|| this.id== "") {
this.messageService.add(
{severity: 'error', summary: 'ID is Required.'});
this.delay(3000).then(any => {
this.messageService.clear();
});
}
}
This will disappear message growl after 3 seconds.
Here's an alternate
req.hostname
Read about it in the Express Docs.
Pressing the f
key (or ctrl+f
in 1.2rc1) when focussed on a plot will fullscreen a plot window. Not quite maximising, but perhaps better.
Other than that, to actually maximize, you will need to use GUI Toolkit specific commands (if they exist for your specific backend).
HTH
While currently not possible with CSS, there is a proposal to enable this functionality called Cascading Attribute Sheets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Google Map</title>
<style>
#map{
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h1>My Google Map`</h1>
<div id="map"></div>
<script>
function initMap(){
//Map options
var options = {
zoom:9,
center:{lat:42.3601, lng:-71.0589}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// customer marker
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png';
//array of Marrkeers
var markers = [
{
coords:{lat: 42.4668, lng: -70.9495},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.8584, lng: -70.9300},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.7762, lng: -71.0773},img:iconBase,con:'<h3> This Is your Content <h3>'
}
];
//loopthrough markers
for(var i = 0; i <markers.length; i++){
//add markeers
addMarker(markers[i]);
}
//function for the plotting markers on the map
function addMarker (props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
icon:props.img
});
var infoWindow = new google.maps.InfoWindow({
content:props.con,
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=**YourAPIKey**&callback=initMap"
defer
></script>
</body>
</html>
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
I read it somewhere and it worked for me.
First check in git bash what is the HOME location. Open git bash and run
echo $HOME
Now change the HOME path by opening cmd and run
setx HOME "path/to/.ssh/loc" (I gave C:\Users\aXXXX)
Now cross check by running the echo command in git bash.
Depending on your environment, you could use Rhino to do this, see Rhino website. This gives you access to all of the Java libraries from within JavaScript.
{
"preOrderData" : [
{
"pname": "xyz",
"quantity": "1",
"unit": "Peice",
"description": "xyz 100 gram",
"preferred_brand": "xyz",
"entry_date": "2020-10-05 11:11:27",
"creation_date": "2020-10-05 11:11:27",
"updated_date": "2020-10-05 11:11:27",
"user": "[email protected]",
"user_type": "individual"
},
{
"productname": "abc cream",
"quantity": "1",
"unit": "Peice",
"description": "abc 100 gram",
"preferred_brand": "abccream",
"entry_date": "2020-10-05 11:11:27",
"creation_date": "2020-10-05 11:11:27",
"updated_date": "2020-10-05 11:11:27",
"user": "[email protected]",
"user_type": "individual"
}
]
}
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
ctrl + mouse hover + click "Open Implementation"
On ctrl + hover
, you should see the following menu:
Tested on Eclipse Mars.2 (4.5.2)
Convert timeofday to string to use indexOf
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
// "" for typecasting to string
document.getElementById("oset").innerHTML = timeD2C(""+timeofday);
Solution 2
use toString()
to convert to string
document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());
I'm doing something like the following code. It works for USB-devices and also the stupid serial8250-devuices that we all have 30 of - but only a couple of them realy works.
Basically I use concept from previous answers. First enumerate all tty-devices in /sys/class/tty/. Devices that does not contain a /device subdir is filtered away. /sys/class/tty/console is such a device. Then the devices actually containing a devices in then accepted as valid serial-port depending on the target of the driver-symlink fx.
$ ls -al /sys/class/tty/ttyUSB0//device/driver
lrwxrwxrwx 1 root root 0 sep 6 21:28 /sys/class/tty/ttyUSB0//device/driver -> ../../../bus/platform/drivers/usbserial
and for ttyS0
$ ls -al /sys/class/tty/ttyS0//device/driver
lrwxrwxrwx 1 root root 0 sep 6 21:28 /sys/class/tty/ttyS0//device/driver -> ../../../bus/platform/drivers/serial8250
All drivers driven by serial8250 must be probes using the previously mentioned ioctl.
if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
// If device type is no PORT_UNKNOWN we accept the port
if (serinfo.type != PORT_UNKNOWN)
the_port_is_valid
Only port reporting a valid device-type is valid.
The complete source for enumerating the serialports looks like this. Additions are welcome.
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/serial.h>
#include <iostream>
#include <list>
using namespace std;
static string get_driver(const string& tty) {
struct stat st;
string devicedir = tty;
// Append '/device' to the tty-path
devicedir += "/device";
// Stat the devicedir and handle it if it is a symlink
if (lstat(devicedir.c_str(), &st)==0 && S_ISLNK(st.st_mode)) {
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
// Append '/driver' and return basename of the target
devicedir += "/driver";
if (readlink(devicedir.c_str(), buffer, sizeof(buffer)) > 0)
return basename(buffer);
}
return "";
}
static void register_comport( list<string>& comList, list<string>& comList8250, const string& dir) {
// Get the driver the device is using
string driver = get_driver(dir);
// Skip devices without a driver
if (driver.size() > 0) {
string devfile = string("/dev/") + basename(dir.c_str());
// Put serial8250-devices in a seperate list
if (driver == "serial8250") {
comList8250.push_back(devfile);
} else
comList.push_back(devfile);
}
}
static void probe_serial8250_comports(list<string>& comList, list<string> comList8250) {
struct serial_struct serinfo;
list<string>::iterator it = comList8250.begin();
// Iterate over all serial8250-devices
while (it != comList8250.end()) {
// Try to open the device
int fd = open((*it).c_str(), O_RDWR | O_NONBLOCK | O_NOCTTY);
if (fd >= 0) {
// Get serial_info
if (ioctl(fd, TIOCGSERIAL, &serinfo)==0) {
// If device type is no PORT_UNKNOWN we accept the port
if (serinfo.type != PORT_UNKNOWN)
comList.push_back(*it);
}
close(fd);
}
it ++;
}
}
list<string> getComList() {
int n;
struct dirent **namelist;
list<string> comList;
list<string> comList8250;
const char* sysdir = "/sys/class/tty/";
// Scan through /sys/class/tty - it contains all tty-devices in the system
n = scandir(sysdir, &namelist, NULL, NULL);
if (n < 0)
perror("scandir");
else {
while (n--) {
if (strcmp(namelist[n]->d_name,"..") && strcmp(namelist[n]->d_name,".")) {
// Construct full absolute file path
string devicedir = sysdir;
devicedir += namelist[n]->d_name;
// Register the device
register_comport(comList, comList8250, devicedir);
}
free(namelist[n]);
}
free(namelist);
}
// Only non-serial8250 has been added to comList without any further testing
// serial8250-devices must be probe to check for validity
probe_serial8250_comports(comList, comList8250);
// Return the lsit of detected comports
return comList;
}
int main() {
list<string> l = getComList();
list<string>::iterator it = l.begin();
while (it != l.end()) {
cout << *it << endl;
it++;
}
return 0;
}
As my first object is a native javascript object (used like a list of objects), push
didn't work in my escenario, but I resolved it by adding new key as following:
MyObjList['newKey'] = obj;
In addition to this, may be usefull to know how to delete same object inserted before:
delete MyObjList['newKey'][id];
Hope it helps someone as it helped me;
Here's how you can get the comprehensive full fledge difference of two dates.
function diffYMDHMS(date1, date2) {
let years = date1.diff(date2, 'year');
date2.add(years, 'years');
let months = date1.diff(date2, 'months');
date2.add(months, 'months');
let days = date1.diff(date2, 'days');
date2.add(days, 'days');
let hours = date1.diff(date2, 'hours');
date2.add(hours, 'hours');
let minutes = date1.diff(date2, 'minutes');
date2.add(minutes, 'minutes');
let seconds = date1.diff(date2, 'seconds');
console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + '
hours ' + minutes + ' minutes ' + seconds + ' seconds');
return { years, months, days, hours, minutes, seconds};
}
I started by using the answers here, but modified it to use YouTube's new iframe
embedding...
$('a.more').on('click', function(event) {
event.preventDefault();
$.fancybox({
'type' : 'iframe',
// hide the related video suggestions and autoplay the video
'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
'overlayShow' : true,
'centerOnScroll' : true,
'speedIn' : 100,
'speedOut' : 50,
'width' : 640,
'height' : 480
});
});
For GET parameters, you can grab them from document.location.search
:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST
object in JSON format into a <script>
tag:
<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["test"]);
</script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode
function.
Update: Here's a more generic implementation:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
Xcode 6.3 didn't see my iPhone running iOS 8.3 even after a computer restart. I then restarted my iPhone and everything worked again. Love buggy software!
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
Edit: With Internet Explorer, you also need this JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
That is the HTML code. Anyone can use this:
<div class="card-header">Contact Information</div>
<div class="card-body" formArrayName="funds">
<div class="row">
<div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row">
<div class="form-group col-6">
<label>Type of Contact</label>
<select class="form-control" formControlName="fundName" type="text">
<option value="01">Balance Fund</option>
<option value="02">Equity Fund</option>
</select>
</div>
<div class="form-group col-12">
<label>Allocation</label>
<input class="form-control" formControlName="allocation" type="number">
<span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched &&
getContactsFormGroup(i).controls['allocation'].hasError('required')">
Allocation % is required! </span>
</div>
<div class="form-group col-12 text-right">
<button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>
It depends on the tablix structure you are using. In a table, for example, you do not have column groups, so Reporting Services does not recognize which textboxes are the column headers and setting RepeatColumnHeaders property to True doesn't work.
Instead, you need to:
RepeatOnNewPage
property to True.
KeepWithGroup
property is set to After
.The KeepWithGroup
property specifies which group to which the static member needs to stick. If set to After
then the static member sticks with the group after it, or below it, acting as a group header. If set to Before
, then the static member sticks with the group before, or above it, acting as a group footer. If set to None
, Reporting Services decides where to put the static member.
Now when you view the report, the column headers repeat on each page of the tablix.
This video shows how to set it exactly as the answer described.
You can declare local variables in MySQL triggers, with the DECLARE
syntax.
Here's an example:
DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
i SERIAL PRIMARY KEY
);
DELIMITER //
DROP TRIGGER IF EXISTS bar //
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = NEW.i;
SET @a = x; -- set user variable outside trigger
END//
DELIMITER ;
SET @a = 0;
SELECT @a; -- returns 0
INSERT INTO foo () VALUES ();
SELECT @a; -- returns 1, the value it got during the trigger
When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row
".
You can use LIMIT
or MAX()
to make sure that the local variable is set to a single value.
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT age FROM users WHERE name = 'Bill');
-- ERROR 1242 if more than one row with 'Bill'
END//
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
-- OK even when more than one row with 'Bill'
END//
This can be done using the numeric_limits in C++:
http://www.cplusplus.com/reference/limits/numeric_limits/
These are the methods you probably want to look at:
infinity() T Representation of positive infinity, if available.
quiet_NaN() T Representation of quiet (non-signaling) "Not-a-Number", if available.
signaling_NaN() T Representation of signaling "Not-a-Number", if available.
If you want to use steffens21's approach with unittest.TestLoader
, you can modify the original test loader (see unittest.py
):
import unittest
from unittest import suite
class TestLoaderWithKwargs(unittest.TestLoader):
"""A test loader which allows to parse keyword arguments to the
test case class."""
def loadTestsFromTestCase(self, testCaseClass, **kwargs):
"""Return a suite of all tests cases contained in
testCaseClass."""
if issubclass(testCaseClass, suite.TestSuite):
raise TypeError("Test cases should not be derived from "\
"TestSuite. Maybe you meant to derive from"\
" TestCase?")
testCaseNames = self.getTestCaseNames(testCaseClass)
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
testCaseNames = ['runTest']
# Modification here: parse keyword arguments to testCaseClass.
test_cases = []
for test_case_name in testCaseNames:
test_cases.append(testCaseClass(test_case_name, **kwargs))
loaded_suite = self.suiteClass(test_cases)
return loaded_suite
# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)
Use:
function readObject($object) {
$name = get_class ($object);
$name = str_replace('\\', "\\\\", $name); // Outcomment this line, if you don't use
// class namespaces approach in your project
$raw = (array)$object;
$attributes = array();
foreach ($raw as $attr => $val) {
$attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val;
}
return $attributes;
}
It returns an array without special characters and class names.
After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in ==
versus ===
in JavaScript especially when it comes to issues of checking for undefined
and/or null
.
There's a really good article about the difference in two terms here. Basically, understand that if you use ==
instead of ===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
the library already have Java/Kotlin support, see github.
To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:
Add the gradle library:
compile 'se.simbio.encryption:library:2.0.0'
and use it:
Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);
if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here
Encryption.java
package se.simbio.encryption;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* A class to make more easy and simple the encrypt routines, this is the core of Encryption library
*/
public class Encryption {
/**
* The Builder used to create the Encryption instance and that contains the information about
* encryption specifications, this instance need to be private and careful managed
*/
private final Builder mBuilder;
/**
* The private and unique constructor, you should use the Encryption.Builder to build your own
* instance or get the default proving just the sensible information about encryption
*/
private Encryption(Builder builder) {
mBuilder = builder;
}
/**
* @return an default encryption instance or {@code null} if occur some Exception, you can
* create yur own Encryption instance using the Encryption.Builder
*/
public static Encryption getDefault(String key, String salt, byte[] iv) {
try {
return Builder.getDefaultBuilder(key, salt, iv).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* Encrypt a String
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
}
/**
* This is a sugar method that calls encrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*/
public String encryptOrNull(String data) {
try {
return encrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls encrypt method in background, it is a good idea to use this
* one instead the default method because encryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be encrypted
* @param callback the Callback to handle the results
*/
public void encryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String encrypt = encrypt(data);
if (encrypt == null) {
callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(encrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* Decrypt a String
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
return new String(dataBytesDecrypted);
}
/**
* This is a sugar method that calls decrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*/
public String decryptOrNull(String data) {
try {
return decrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls decrypt method in background, it is a good idea to use this
* one instead the default method because decryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be decrypted
* @param callback the Callback to handle the results
*/
public void decryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String decrypt = decrypt(data);
if (decrypt == null) {
callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(decrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* creates a 128bit salted aes key
*
* @param key encoded input key
*
* @return aes 128 bit salted key
*
* @throws NoSuchAlgorithmException if no installed provider that can provide the requested
* by the Builder secret key type
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws InvalidKeySpecException if the specified key specification cannot be used to
* generate a secret key
* @throws NullPointerException if the specified Builder secret key type is {@code null}
*/
private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
}
/**
* takes in a simple string and performs an sha1 hash
* that is 128 bits long...we then base64 encode it
* and return the char array
*
* @param key simple inputted string
*
* @return sha1 base64 encoded representation
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* @throws NullPointerException if the Builder digest algorithm is {@code null}
*/
private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
}
/**
* When you encrypt or decrypt in callback mode you get noticed of result using this interface
*/
public interface Callback {
/**
* Called when encrypt or decrypt job ends and the process was a success
*
* @param result the encrypted or decrypted String
*/
void onSuccess(String result);
/**
* Called when encrypt or decrypt job ends and has occurred an error in the process
*
* @param exception the Exception related to the error
*/
void onError(Exception exception);
}
/**
* This class is used to create an Encryption instance, you should provide ALL data or start
* with the Default Builder provided by the getDefaultBuilder method
*/
public static class Builder {
private byte[] mIv;
private int mKeyLength;
private int mBase64Mode;
private int mIterationCount;
private String mSalt;
private String mKey;
private String mAlgorithm;
private String mKeyAlgorithm;
private String mCharsetName;
private String mSecretKeyType;
private String mDigestAlgorithm;
private String mSecureRandomAlgorithm;
private SecureRandom mSecureRandom;
private IvParameterSpec mIvParameterSpec;
/**
* @return an default builder with the follow defaults:
* the default char set is UTF-8
* the default base mode is Base64
* the Secret Key Type is the PBKDF2WithHmacSHA1
* the default salt is "some_salt" but can be anything
* the default length of key is 128
* the default iteration count is 65536
* the default algorithm is AES in CBC mode and PKCS 5 Padding
* the default secure random algorithm is SHA1PRNG
* the default message digest algorithm SHA1
*/
public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
return new Builder()
.setIv(iv)
.setKey(key)
.setSalt(salt)
.setKeyLength(128)
.setKeyAlgorithm("AES")
.setCharsetName("UTF8")
.setIterationCount(1)
.setDigestAlgorithm("SHA1")
.setBase64Mode(Base64.DEFAULT)
.setAlgorithm("AES/CBC/PKCS5Padding")
.setSecureRandomAlgorithm("SHA1PRNG")
.setSecretKeyType("PBKDF2WithHmacSHA1");
}
/**
* Build the Encryption with the provided information
*
* @return a new Encryption instance with provided information
*
* @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
* @throws NullPointerException if the SecureRandomAlgorithm is {@code null} or if the
* IV byte array is null
*/
public Encryption build() throws NoSuchAlgorithmException {
setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
setIvParameterSpec(new IvParameterSpec(getIv()));
return new Encryption(this);
}
/**
* @return the charset name
*/
private String getCharsetName() {
return mCharsetName;
}
/**
* @param charsetName the new charset name
*
* @return this instance to follow the Builder patter
*/
public Builder setCharsetName(String charsetName) {
mCharsetName = charsetName;
return this;
}
/**
* @return the algorithm
*/
private String getAlgorithm() {
return mAlgorithm;
}
/**
* @param algorithm the algorithm to be used
*
* @return this instance to follow the Builder patter
*/
public Builder setAlgorithm(String algorithm) {
mAlgorithm = algorithm;
return this;
}
/**
* @return the key algorithm
*/
private String getKeyAlgorithm() {
return mKeyAlgorithm;
}
/**
* @param keyAlgorithm the keyAlgorithm to be used in keys
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyAlgorithm(String keyAlgorithm) {
mKeyAlgorithm = keyAlgorithm;
return this;
}
/**
* @return the Base 64 mode
*/
private int getBase64Mode() {
return mBase64Mode;
}
/**
* @param base64Mode set the base 64 mode
*
* @return this instance to follow the Builder patter
*/
public Builder setBase64Mode(int base64Mode) {
mBase64Mode = base64Mode;
return this;
}
/**
* @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
* are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*/
private String getSecretKeyType() {
return mSecretKeyType;
}
/**
* @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
* changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*
* @return this instance to follow the Builder patter
*/
public Builder setSecretKeyType(String secretKeyType) {
mSecretKeyType = secretKeyType;
return this;
}
/**
* @return the value used for salting
*/
private String getSalt() {
return mSalt;
}
/**
* @param salt the value used for salting
*
* @return this instance to follow the Builder patter
*/
public Builder setSalt(String salt) {
mSalt = salt;
return this;
}
/**
* @return the key
*/
private String getKey() {
return mKey;
}
/**
* @param key the key.
*
* @return this instance to follow the Builder patter
*/
public Builder setKey(String key) {
mKey = key;
return this;
}
/**
* @return the length of key
*/
private int getKeyLength() {
return mKeyLength;
}
/**
* @param keyLength the length of key
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyLength(int keyLength) {
mKeyLength = keyLength;
return this;
}
/**
* @return the number of times the password is hashed
*/
private int getIterationCount() {
return mIterationCount;
}
/**
* @param iterationCount the number of times the password is hashed
*
* @return this instance to follow the Builder patter
*/
public Builder setIterationCount(int iterationCount) {
mIterationCount = iterationCount;
return this;
}
/**
* @return the algorithm used to generate the secure random
*/
private String getSecureRandomAlgorithm() {
return mSecureRandomAlgorithm;
}
/**
* @param secureRandomAlgorithm the algorithm to generate the secure random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
mSecureRandomAlgorithm = secureRandomAlgorithm;
return this;
}
/**
* @return the IvParameterSpec bytes array
*/
private byte[] getIv() {
return mIv;
}
/**
* @param iv the byte array to create a new IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIv(byte[] iv) {
mIv = iv;
return this;
}
/**
* @return the SecureRandom
*/
private SecureRandom getSecureRandom() {
return mSecureRandom;
}
/**
* @param secureRandom the Secure Random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandom(SecureRandom secureRandom) {
mSecureRandom = secureRandom;
return this;
}
/**
* @return the IvParameterSpec
*/
private IvParameterSpec getIvParameterSpec() {
return mIvParameterSpec;
}
/**
* @param ivParameterSpec the IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
mIvParameterSpec = ivParameterSpec;
return this;
}
/**
* @return the message digest algorithm
*/
private String getDigestAlgorithm() {
return mDigestAlgorithm;
}
/**
* @param digestAlgorithm the algorithm to be used to get message digest instance
*
* @return this instance to follow the Builder patter
*/
public Builder setDigestAlgorithm(String digestAlgorithm) {
mDigestAlgorithm = digestAlgorithm;
return this;
}
}
}
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
Git can search diffs with the -S option (it's called pickaxe in the docs)
git log -S password
This will find any commit that added or removed the string password
. Here a few options:
-p
: will show the diffs. If you provide a file (-p file
), it will generate a patch for you.-G
: looks for differences whose added or removed line matches the given regexp, as opposed to -S
, which "looks for differences that introduce or remove an instance of string".--all
: searches over all branches and tags; alternatively, use --branches[=<pattern>]
or --tags[=<pattern>]
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
To add to other answers. For me it was helpful to delete .mvn
directory and then add build.gradle
. New versions of IntelliJ will then automatically notice that you use Gradle.
The first one catches all subclasses of Throwable
(this includes Exception
and Error
), the second one catches all subclasses of Exception
.
Error
is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception
is programmatically recoverable. Its subclass RuntimeException
indicates a programming error and is usually not to be caught as well.
What you're looking for is date --date='06/12/2012 07:21:22' +"%s"
. Keep in mind that this assumes you're using GNU coreutils, as both --date
and the %s
format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.
Consult the appropriate manual page for other versions of date
.
Note: bash --date
and -d
option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy
or yyyy-mm-dd
, not in UK, EU, or any other format.
Add border-collapse:collapse
to the table.
Example:
table.myTable{
border-collapse:collapse;
}
table.myTable tr{
border:1px solid red;
}
This worked for me.
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
First make sure you have the runat="server"
attribute in your textarea
tag like this
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
Then you can access the content via:
string body = TextArea1.value;
You can also overload the Function prototype:
// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
var func = this;
var slice = Array.prototype.slice;
var appliedArgs = slice.call( arguments, 0 );
return function( ) {
var leftoverArgs = slice.call( arguments, 0 );
return func.apply( this, appliedArgs.concat( leftoverArgs ) );
};
};
// can do other fancy things:
// flips the first two arguments of a function
Function.prototype.flip = function( ) {
var func = this;
return function( ) {
var first = arguments[0];
var second = arguments[1];
var rest = Array.prototype.slice.call( arguments, 2 );
var newArgs = [second, first].concat( rest );
return func.apply( this, newArgs );
};
};
/*
e.g.
var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey
var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/
If you have to use the:
myLabel.numberOfLines = 0;
property you can also use a standard line break ("\n")
, in code, to force a new line.
If checking for truth:
if foo
For false:
if not foo
For none:
if foo is None
For non-none:
if foo is not None
For getattr()
the correct behaviour is not to return None
, but raise an AttributError
error instead - unless your class is something like defaultdict
.
Different approach, to allow a Fragment to communicate up to its Activity:
1) Define a public interface in the fragment and create a variable for it
public OnFragmentInteractionListener mCallback;
public interface OnFragmentInteractionListener {
void onFragmentInteraction(int id);
}
2) Cast the activity to the mCallback variable in the fragment
try {
mCallback = (OnFragmentInteractionListener) getActivity();
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
3) Implement the listener in your activity
public class MainActivity extends AppCompatActivity implements DFragment.OnFragmentInteractionListener {
//your code here
}
4) Override the OnFragmentInteraction in the activity
@Override
public void onFragmentInteraction(int id) {
Log.d(TAG, "received from fragment: " + id);
}
More info on it: https://developer.android.com/training/basics/fragments/communicating.html
In your mysql command line do the following:
mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | OFF |
| log_timestamps | UTC |
+---------------------------------+-------+
2 rows in set (0.01 sec)
mysql> SET GLOBAL explicit_defaults_for_timestamp = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW GLOBAL VARIABLES LIKE '%timestamp%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| explicit_defaults_for_timestamp | ON |
| log_timestamps | UTC |
+---------------------------------+-------+
2 rows in set (0.00 sec)
I found that this works if wanting in a (123) - 456-7890 format.
UPDATE table
SET Phone_number = '(' +
SUBSTRING(Phone_number, 1, 3)
+ ') '
+ '- ' +
SUBSTRING(Phone_number, 4, 3)
+ '-' +
SUBSTRING(Phone_number, 7, 4)
try this:
first write this in your .h file of viewcontroller
UIButton *btn;
Now write this in your .m file of viewcontrollers viewDidLoad.
btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
[btn setTitle: @"My Button" forState:UIControlStateNormal];
[btn setTitleColor: [UIColor blueVolor] forState:UIControlStateNormal];
[btn.layer setBorderWidth:1.0f];
[btn.layer setBorderColor:[UIColor BlueVolor].CGColor];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
write this outside viewDidLoad method in .m file of your view controller
- (IBAction)btnClicked:(id)sender
{
//Write a code you want to execute on buttons click event
}
Try something like
find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)
and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.
For my case, my another team member included another version of jquery.js when he add in bootstrap.min.js. After remove the extra jquery.js, the problem is solved
To manually sign an Android APK file run these three commands:
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
Sign Your APK file using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
Align Signed APK using zipalign tool
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
keystore password : yourApp@123 key password : yourApp@123
D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
-alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: MySignedApp Sample
What is the name of your organizational unit?
[Unknown]: Information Technology
What is the name of your organization?
[Unknown]: MySignedApp Demo
What is the name of your City or Locality?
[Unknown]: Mumbai
What is the name of your State or Province?
[Unknown]: Maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
[no]: y
Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
C=IN
Enter key password for <MySignedApp>
(RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]
D:\ru\SignedBuilds\MySignedApp>
Sign your app with your private keystore using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id
D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
adding: META-INF/MANIFEST.MF
adding: META-INF/---.SF
adding: META-INF/---.RSA
signing: AndroidManifest.xml
.....
signing: classes.dex
signing: lib/commons-codec-1.6.jar
signing: lib/armeabi/libkonyjsvm.so
jar signed.
Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.
D:\ru\SignedBuilds\MySignedApp>
Verify that your APK is signed
jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH
jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
future revocation date.
D:\ru\SignedBuilds\MySignedApp>
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK
zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4528613 classes.dex (OK - compressed)
5656594 lib/commons-codec-1.6.jar (OK - compressed)
5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
Verify that your APK is Aligned successfully
zipalign -c -v 4 YOUR_APK_PATH
zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4453984 res/drawable/zoomout.png (OK)
4454772 res/layout/tabview.xml (OK - compressed)
4455243 res/layout/wheel_item.xml (OK - compressed)
4455608 resources.arsc (OK)
4470161 classes.dex (OK - compressed)
5597923 lib/commons-codec-1.6.jar (OK - compressed)
5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
The verify command is just to check whether APK is built and signed correctly!
I hope this will help one and all :)
If this code is in your .htaccess file (without the check for mod_rewrite.c)
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
and you can visit any page on your site with getting a 500 server error I think it's safe to say mod rewrite is switched on.
You're on the right track. Here's a corrected version:
char str[10];
int n;
printf("type a string: ");
scanf("%s %d", str, &n);
printf("%s\n", str);
printf("%d\n", n);
Let's talk through the changes:
n
) to store your number inscanf
to read in first a string and then a number (%d
means number, as you already knew from your printf
That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str
and start trampling your stack.
If someone interested to know how to work with 2 list and between dates
var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))
var someString = "(/n{})+++(/n{})---(/n{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
_x000D_
function removeLast(s, r){_x000D_
s = s.split(r)_x000D_
return s.slice(0,-1).join(r) + s.pop()_x000D_
}_x000D_
_x000D_
console.log(_x000D_
removeLast(someString, toRemove)_x000D_
)
_x000D_
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
You can also add prompt option like this.
<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
Well I would do it like this instead:
TimeSpan diff = expiryDate - DateTime.Today;
if (diff.Days > 30)
matchFound = true;
Compare only responds with an integer indicating weather the first is earlier, same or later...
Unfortunately the solution is flawed. There is a sort of bug with ScheduledThreadPoolExecutor
, also reported in this question: cancelling a submitted task does not fully release the memory resources associated with the task; the resources are released only when the task expires.
If you therefore create a TimeoutThreadPoolExecutor
with a fairly long expiration time (a typical usage), and submit tasks fast enough, you end up filling the memory - even though the tasks actually completed successfully.
You can see the problem with the following (very crude) test program:
public static void main(String[] args) throws InterruptedException {
ExecutorService service = new TimeoutThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), 10, TimeUnit.MINUTES);
//ExecutorService service = Executors.newFixedThreadPool(1);
try {
final AtomicInteger counter = new AtomicInteger();
for (long i = 0; i < 10000000; i++) {
service.submit(new Runnable() {
@Override
public void run() {
counter.incrementAndGet();
}
});
if (i % 10000 == 0) {
System.out.println(i + "/" + counter.get());
while (i > counter.get()) {
Thread.sleep(10);
}
}
}
} finally {
service.shutdown();
}
}
The program exhausts the available memory, although it waits for the spawned Runnable
s to complete.
I though about this for a while, but unfortunately I could not come up with a good solution.
EDIT: I found out this issue was reported as JDK bug 6602600, and appears to have been fixed very recently.
You can pass new value like this
setExampleState({...exampleState, masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}})
I had a similar situation where I needed to execute a controller function after the view was loaded and also after a particular 3rd-party component within the view was loaded, initialized, and had placed a reference to itself on $scope. What ended up working for me was to setup a watch on this scope property and firing my function only after it was initialized.
// $scope.myGrid property will be created by the grid itself
// The grid will have a loadedRows property once initialized
$scope.$watch('myGrid', function(newValue, oldValue) {
if (newValue && newValue.loadedRows && !oldValue) {
initializeAllTheGridThings();
}
});
The watcher is called a couple of times with undefined values. Then when the grid is created and has the expected property, the initialization function may be safely called. The first time the watcher is called with a non-undefined newValue, oldValue will still be undefined.
$('#tblNewAttendees tbody tr).each((index, tr)=> {
//console.log(tr);
$(tr).children('td').each ((index, td) => {
console.log(td);
});
});
You can use this tr and td parameter also.
Package auto-indent exists to apply auto-indent to entire file with this shortcuts :
ctrl+shift+i
or
cmd+shift+i
Package url : https://atom.io/packages/auto-indent
You don't need to use echo or grep. You could do this:
ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"
The OP wrote this comment:
I was trying to format a small JSON for some purposes, like this:
'{"all": false, "selected": "{}"}'.format(data)
to get something like{"all": false, "selected": "1,2"}
It's pretty common that the "escaping braces" issue comes up when dealing with JSON.
I suggest doing this:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
It's cleaner than the alternative, which is:
'{{"all": false, "selected": "{}"}}'.format(data)
Using the json
library is definitely preferable when the JSON string gets more complicated than the example.
There are couple of different solutions to achieve this:
1 - Native javascript for-in loop:
const result = {};
let key;
for (key in obj1) {
if(obj1.hasOwnProperty(key)){
result[key] = obj1[key];
}
}
for (key in obj2) {
if(obj2.hasOwnProperty(key)){
result[key] = obj2[key];
}
}
2 - Object.keys()
:
const result = {};
Object.keys(obj1)
.forEach(key => result[key] = obj1[key]);
Object.keys(obj2)
.forEach(key => result[key] = obj2[key]);
3 - Object.assign()
:
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)
const result = Object.assign({}, obj1, obj2);
4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):
Defined in several sections of the specification: Array Initializer, Argument Lists
Using this new syntax you could join/merge different objects into one object like this:
const result = {
...obj1,
...obj2,
};
5 - jQuery.extend(target, obj1, obj2)
:
Merge the contents of two or more objects together into the first object.
const target = {};
$.extend(target, obj1, obj2);
6 - jQuery.extend(true, target, obj1, obj2)
:
Run a deep merge of the contents of two or more objects together into the target. Passing false
for the first argument is not supported.
const target = {};
$.extend(true, target, obj1, obj2);
7 - Lodash _.assignIn(object, [sources])
: also named as _.extend
:
const result = {};
_.assignIn(result, obj1, obj2);
8 - Lodash _.merge(object, [sources])
:
const result = _.merge(obj1, obj2);
There are a couple of important differences between lodash's merge function and Object.assign
:
1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign
only merges the first level. For instance:
_.isEqual(_.merge({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
}), {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // true
BUT:
const result = Object.assign({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
});
_.isEqual(result, {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // false
// AND
_.isEqual(result, {
x: {
y: {
key2: 'value2',
},
},
}); // true
2- Another difference has to do with how Object.assign
and _.merge
interpret the undefined
value:
_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false
BUT:
_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true
Update 1:
When using for in
loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype
or even Object.prototype
.
To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key)
to mke sure the key is actually part of the object you are iterating over.
Update 2:
I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.
Update 3:
I added the difference between Object.assign
and _.merge
.
The simple example of using a property in an interface:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
the mySql blob class has the following function :
blob.getBytes
use it like this:
//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
//release the blob and free up memory. (since JDBC 4.0)
blob.free();
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include> **/*.properties</include>
</includes>
</resource>
</resources>
...
</build>
You have to construct a new string out of a byte array. The first element in your byteArray
should be 0x63
. If you want to add any more letters, make the byteArray
longer and add them to the next indices.
byte[] byteArray = new byte[1];
byteArray[0] = 0x63;
try {
System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO: Handle exception.
e.printStackTrace();
}
Note that specifying the encoding will eventually throw an UnsupportedEncodingException
and you must handle that accordingly.
just you pass this things in your select query. using CASE
CASE WHEN gender=0 then 'Female' WHEN gender=1 then 'Male' END as Genderdisp
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo()
and du.getUserInfo()
calls.
See Yosemite Update.
See Yosemite Update.
See Yosemite Update.
See Yosemite Update.
Just enter in gcc
or make
on the command line! OSX will know that you do not have the command line tools and prompt you to install them!
To check if they exist, xcode-select -p
will print the directory. Alternatively, the return value will be 2
if they do NOT exist, and 0
if they do. To just print the return value (thanks @Andy):
xcode-select -p 1>/dev/null;echo $?
Use pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
Option 1: Rob Napier suggested to use pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
, which is probably cleaner.
Option 2: Check inside /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
for a reference to com.apple.pkg.DeveloperToolsCLI
and it will list the version 4.5.0
.
[Mar 12 17:04] [jnovack@yourmom ~]$ defaults read /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
{
InstallDate = "2012-12-26 22:45:54 +0000";
InstallPrefixPath = "/";
InstallProcessName = Xcode;
PackageFileName = "DeveloperToolsCLI.pkg";
PackageGroups = (
"com.apple.FindSystemFiles.pkg-group",
"com.apple.DevToolsBoth.pkg-group",
"com.apple.DevToolsNonRelocatableShared.pkg-group"
);
PackageIdentifier = "com.apple.pkg.DeveloperToolsCLI";
PackageVersion = "4.5.0.0.1.1249367152";
PathACLs = {
Library = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
System = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
};
}
In my case, the svn relocate
command (as well as svn switch --relocate
) failed for some reason (maybe the repo was not moved correctly, or something else). I faced this error:
$ svn relocate NEW_SERVER
svn: E195009: The repository at 'NEW_SERVER' has uuid 'e7500204-160a-403c-b4b6-6bc4f25883ea', but the WC has '3a8c444c-5998-40fb-8cb3-409b74712e46'
I did not want to redownload the whole repository, so I found a workaround. It worked in my case, but generally I can imagine a lot of things can get broken (so either backup your working copy, or be ready to re-checkout the whole repo if something goes wrong).
The repo address and its UUID are saved in the .svn/wc.db
SQLite database file in your working copy. Just open the database (e.g. in SQLite Browser), browse table REPOSITORY, and change the root
and uuid
column values to the new ones. You can find the UUID of the new repo by issuing svn info NEW_SERVER
.
Again, treat this as a last resort method.
Directly from var/www/html
mysql -u username -p database_name < /path/to/file.sql
From within mysql:
mysql> use db_name;
mysql> source backup-file.sql
This answer is correct for old versions of iOS, but is now obsolete. You should use Micky Duncan's answer, which covers custom containers.
Don't do this! The intent of the UIViewController
is to drive the entire screen. It just isn't appropriate for this, and it doesn't really add anything you need.
All you need is an object that owns your custom view. Just use a subclass of UIView
itself, so it can be added to your window hierarchy and the memory management is fully automatic.
Point the subview NIB's owner a custom subclass of UIView
. Add a contentView
outlet to this custom subclass, and point it at the view within the nib. In the custom subclass do something like this:
- (id)initWithFrame: (CGRect)inFrame;
{
if ( (self = [super initWithFrame: inFrame]) ) {
[[NSBundle mainBundle] loadNibNamed: @"NibNameHere"
owner: self
options: nil];
contentView.size = inFrame.size;
// do extra loading here
[self addSubview: contentView];
}
return self;
}
- (void)dealloc;
{
self.contentView = nil;
// additional release here
[super dealloc];
}
(I'm assuming here you're using initWithFrame:
to construct the subview.)
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
you could use this formular to do the job -> get the CellValue for the specific row by typing: = indirect("$A&Cell()) depending on which column you have to check, you have to change the $A
For Example -> You could use a customized VBA Function in the Background:
Public Function IstDatum(Zelle) As Boolean IstDatum = False If IsDate(Zelle) Then IstDatum = True End Function
I need it to check for a date-entry in column A:
=IstDatum(INDIREKT("$A"&ZEILE()))
Short answer: download Linux Device Drivers and read the chapter on memory management.
Seriously, there are a lot of subtle issues related to kernel memory management that you need to understand - I spend a lot of my time debugging problems with it.
vmalloc() is very rarely used, because the kernel rarely uses virtual memory. kmalloc() is what is typically used, but you have to know what the consequences of the different flags are and you need a strategy for dealing with what happens when it fails - particularly if you're in an interrupt handler, like you suggested.
with logback.xml configuration files, you can do :
<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
That will log the request and the response like this (depending on your configuration for the log output) :
09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------
09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------
The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.
However, if you just had to do string interpolation, you can use:
const str = `My name is ${replacements.name} and my age is ${replacements.age}.`
Note the backticks delimiting the string, they are required.
For an answer suiting the particular OP's requirement, you could use String.prototype.replace()
for the replacements.
The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).
var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
str = 'My Name is %NAME% and my age is %AGE%.';
str = str.replace(/%\w+%/g, function(all) {
return replacements[all] || all;
});
If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in
operator to achieve this.
However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null
prototype, use Object.prototype.hasOwnProperty()
, unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.
Otherwise, if your replacement string was 'hasOwnProperty'
, you would get a resultant messed up string.
As a side note, you should be called replacements
an Object
, not an Array
.
I had the same problem.
The solution from depa is absolutely correct.
Just make sure that u have a user configured to use PostgreSQL.
Check the file:
$ ls /etc/postgresql/9.1/main/pg_hba.conf -l
The permission of this file should be given to the user you have registered your psql with.
Further. If you are good till now..
Update as per @depa's instructions.
i.e.
$ sudo nano /etc/postgresql/9.1/main/pg_hba.conf
and then make changes.
Your negative lookahead solution would e.g. be this:
\\(?:.(?!\\))+$
See it here on Regexr
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
may be this will help:
map.setCenter(window.markersArray[2].getPosition());
all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:
window.markersArray[2] = new google.maps.Marker({
position: new google.maps.LatLng(23.81927, 90.362349),
map: map,
title: 'your info '
});
Hope this will help.
You have to use this in your MainActivity
Intent intent = new Intent(context , yourActivity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(intent);
The flag will start multiple tasks that will keep your MainActivity, when you call finish it will kill the other activity and get you back to the MainActivity
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
Use String.valueOf():
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors
It is to mark the parameter as optional.
Best would be not using LinkedList
at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)
Use ArrayList
, and iterate with
int len = list.size();
for (int i = 0; i < len; i++) {
Element ele = list.get(i);
}
Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:
iter = list.listIterator();
(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)
I had a pesky "invisible" space at the end of my string and had to do this
$update_sql=rtrim(trim($update_sql),',');
But a solution above is better
$update_sql=rtrim($update_sql,', ');
\rm -f file
will never report not found.
1) Graphically intuitive way you can generate Gaussian random numbers is by using something similar to the Monte Carlo method. You would generate a random point in a box around the Gaussian curve using your pseudo-random number generator in C. You can calculate if that point is inside or underneath the Gaussian distribution using the equation of the distribution. If that point is inside the Gaussian distribution, then you have got your Gaussian random number as the x value of the point.
This method isn't perfect because technically the Gaussian curve goes on towards infinity, and you couldn't create a box that approaches infinity in the x dimension. But the Guassian curve approaches 0 in the y dimension pretty fast so I wouldn't worry about that. The constraint of the size of your variables in C may be more of a limiting factor to your accuracy.
2) Another way would be to use the Central Limit Theorem which states that when independent random variables are added, they form a normal distribution. Keeping this theorem in mind, you can approximate a Gaussian random number by adding a large amount of independent random variables.
These methods aren't the most practical, but that is to be expected when you don't want to use a preexisting library. Keep in mind this answer is coming from someone with little or no calculus or statistics experience.
Twitter Bootstrap is incompatible with jQuery UI styles at the moment.
https://github.com/twitter/bootstrap/issues/156
This might help you https://github.com/sferik/rails_admin ( http://rails-admin-tb.herokuapp.com/admin/drafts/new )
There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.
I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.
The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>
Install the Package Control first.
The simplest method of installation is through the Sublime Text console. The console is accessed via the Ctrl+` shortcut or the View > Show Console menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console.
Code for Sublime Text 3
import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())
Code for Sublime Text 2
import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')
For the up-to-date installation code, please check Package Control Installation Guide.
Manual
If for some reason the console installation instructions do not work for you (such as having a proxy on your network), perform the following steps to manually install Package Control:
Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+p (Win, Linux) or CMD+Shift+p (OSX). All Package Control commands begin with Package Control:, so start by typing Package.
Starting with v0.20.0
, the dtype
keyword argument in read_excel()
function could be used to specify the data types that needs to be applied to the columns just like it exists for read_csv()
case.
Using converters
and dtype
arguments together on the same column name would lead to the latter getting shadowed and the former gaining preferance.
1) Inorder for it to not interpret the dtypes
but rather pass all the contents of it's columns as they were originally in the file before, we could set this arg to str
or object
so that we don't mess up our data. (one such case would be leading zeros in numbers which would be lost otherwise)
pd.read_excel('file_name.xlsx', dtype=str) # (or) dtype=object
2) It even supports a dict mapping wherein the keys
constitute the column names and values
it's respective data type to be set especially when you want to alter the dtype
for a subset of all the columns.
# Assuming data types for `a` and `b` columns to be altered
pd.read_excel('file_name.xlsx', dtype={'a': np.float64, 'b': np.int32})
Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.
GraphicsDevice devices[];
devices = GraphicsEnvironment.
getLocalGraphicsEnvironment().
getScreenDevices();
return Stream.
of(devices).
map(GraphicsDevice::getDefaultConfiguration).
map(GraphicsConfiguration::getBounds).
mapToInt(bounds -> bounds.x + bounds.width).
max().
orElse(0);
Here are links to the JavaDoc.
GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()
you can use detox
by Doug Harple
detox -r <folder>
Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.
With the help of this post, I have made a script that will install via the app Installous for rapid deployment:
# compress application.
/bin/mkdir -p $CONFIGURATION_BUILD_DIR/Payload
/bin/cp -R $CONFIGURATION_BUILD_DIR/MyApp.app $CONFIGURATION_BUILD_DIR/Payload
/bin/cp iTunesCrap/logo_itunes.png $CONFIGURATION_BUILD_DIR/iTunesArtwork
/bin/cp iTunesCrap/iTunesMetadata.plist $CONFIGURATION_BUILD_DIR/iTunesMetadata.plist
cd $CONFIGURATION_BUILD_DIR
# zip up the HelloWorld directory
/usr/bin/zip -r MyApp.ipa Payload iTunesArtwork iTunesMetadata.plist
What Is missing in the post referenced above, is the iTunesMetadata. Without this, Installous will not install apps correctly. Here is an example of an iTunesMetadata:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>appleId</key>
<string></string>
<key>artistId</key>
<integer>0</integer>
<key>artistName</key>
<string>MYCOMPANY</string>
<key>buy-only</key>
<true/>
<key>buyParams</key>
<string></string>
<key>copyright</key>
<string></string>
<key>drmVersionNumber</key>
<integer>0</integer>
<key>fileExtension</key>
<string>.app</string>
<key>genre</key>
<string></string>
<key>genreId</key>
<integer>0</integer>
<key>itemId</key>
<integer>0</integer>
<key>itemName</key>
<string>MYAPP</string>
<key>kind</key>
<string>software</string>
<key>playlistArtistName</key>
<string>MYCOMPANY</string>
<key>playlistName</key>
<string>MYAPP</string>
<key>price</key>
<integer>0</integer>
<key>priceDisplay</key>
<string>nil</string>
<key>rating</key>
<dict>
<key>content</key>
<string></string>
<key>label</key>
<string>4+</string>
<key>rank</key>
<integer>100</integer>
<key>system</key>
<string>itunes-games</string>
</dict>
<key>releaseDate</key>
<string>Sunday, December 12, 2010</string>
<key>s</key>
<integer>143441</integer>
<key>softwareIcon57x57URL</key>
<string></string>
<key>softwareIconNeedsShine</key>
<false/>
<key>softwareSupportedDeviceIds</key>
<array>
<integer>1</integer>
</array>
<key>softwareVersionBundleId</key>
<string>com.mycompany.myapp</string>
<key>softwareVersionExternalIdentifier</key>
<integer>0</integer>
<key>softwareVersionExternalIdentifiers</key>
<array>
<integer>1466803</integer>
<integer>1529132</integer>
<integer>1602608</integer>
<integer>1651681</integer>
<integer>1750461</integer>
<integer>1930253</integer>
<integer>1961532</integer>
<integer>1973932</integer>
<integer>2026202</integer>
<integer>2526384</integer>
<integer>2641622</integer>
<integer>2703653</integer>
</array>
<key>vendorId</key>
<integer>0</integer>
<key>versionRestrictions</key>
<integer>0</integer>
</dict>
</plist>
Obviously, replace all instances of MyApp with the name of your app and MyCompany with the name of your company.
Basically, this will install on any jailbroken device with Installous installed. After it is set up, this results in very fast deployment, as it can be installed from anywhere, just upload it to your companies website, and download the file directly to the device, and copy / move it to ~/Documents/Installous/Downloads
.
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
This isn't specific to Android Studio, but a generic behaviour with Intellij's IDEA.
Go to: Preferences > Version Control > GitHub
Also note that you don't need the github integration: the standard git functions should be enough (VCS > Git, Tool Windows > Changes)
<html>
<script language="javascript" type="text/javascript">
var scrt_var = 10;
openPage = function() {
location.href = "2.html?Key="+scrt_var;
}
</script>
this is a <a href ="javascript:openPage()">Link </a>
</html>
There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.
That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.
More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.
On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.
Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.
Following is a dump of frameworks. It doesn't mean I actually used them:
Coeus. A traditional MVC web framework for Scala.
Unfiltered. A toolkit for servicing HTTP requests in Scala.
Amore. A Scala port of the Ruby web framework Sinatra
Scales XML. Flexible approach to XML handling and a simplified way of interacting with XML.
Belt. A Rack-like interface for web applications built on top of Scalaz-HTTP
MixedBits. A framework for the Scala progamming language to help build web sites
Circumflex. Unites several self-contained open source projects for application development using the Scala programming language.
Scala Webmachine. Port of Basho's webmachine in Scala, a REST-based system for building web applications
Bowler. A RESTful, multi-channel ready Scala web framework
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
As an alternative to the other answers, you can also use this code if you want to return an IActionResult
within an ASP.NET controller.
ASP.NET
return Content(HttpStatusCode.Unauthorized, "My error message");
Update: ASP.NET Core
Above code does not work in ASP.NET Core, you can use one of these instead:
return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
return StatusCode(401, "My error message");
Apparently the reason phrase is pretty optional (Can an HTTP response omit the Reason-Phrase?)
just in case you need to create thumb with a max width and a max height ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
There is also a descent solution which seems not to have any memory or performance overhead and be quite elegant:
string[] filters = new[]{"*.jpg", "*.png", "*.gif"};
string[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();
From New-style and classic classes:
Up to Python 2.1, old-style classes were the only flavour available to the user.
The concept of (old-style) class is unrelated to the concept of type: if
x
is an instance of an old-style class, thenx.__class__
designates the class ofx
, buttype(x)
is always<type 'instance'>
.This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.
If x is an instance of a new-style class, then
type(x)
is typically the same asx.__class__
(although this is not guaranteed – a new-style class instance is permitted to override the value returned forx.__class__
).The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.
It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.
For compatibility reasons, classes are still old-style by default.
New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed.
The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.
Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.
Python 3 only has new-style classes.
No matter if you subclass from
object
or not, classes are new-style in Python 3.
Use RGB values combined with opacity to get the transparency that you wish.
For instance,
<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;"> </div>
Similarly, with actual values without opacity, will give the below.
<div style=" background: rgb(243, 191, 189) ; "> </div>
<div style=" background: rgb(246, 143, 142) ; "> </div>
<div style=" background: rgb(249, 95 , 94) ; "> </div>
<div style=" background: rgb(252, 47, 47) ; "> </div>
<div style=" background: rgb(255, 0, 0) ; "> </div>
You can have a look at this WORKING EXAMPLE.
Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.
The HTML
<div class="social">
<img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>
The CSS:
social img{
opacity:0.5;
}
.social img:hover {
opacity:1;
background-color:black;
cursor:pointer;
background: rgb(255, 0, 0) ; opacity: 0.5;
}
Hope this helps Now.
SELECT * FROM user_cons_columns WHERE table_name = 'table_name';
The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame
, you could get the blue value at location (x
, y
) (from the top left) this way:
frame.data[frame.channels()*(frame.cols*y + x)];
Likewise, to get B, G, and R:
uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];
Note that this code assumes the stride is equal to the width of the image.
Try following code. It is working for me....
UPDATE TableOne
SET
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT TableTwo.id
FROM TableTwo
WHERE TableOne.id = TableTwo.id)
Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).
df <- data.frame(X=c(), R=c())
x <- x0
continue <- TRUE
while(continue)
{
xi <- (11 * x) %% 16
df <- rbind(df, data.frame(X=x, R=xi))
x <- xi
if(xi == x0)
{
continue <- FALSE
}
}
The NullReference Exception
for Visual Basic is no different from the one in C#. After all, they are both reporting the same exception defined in the .NET Framework which they both use. Causes unique to Visual Basic are rare (perhaps only one).
This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.
Note:
NullReferenceException
(NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:
Since the problem is an object reference which is Nothing
, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be Nothing
.
You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is Nothing
. This is what you want because it will identify the exact location of the problem, and allow you to identify the object causing it.
A MsgBox
in the Catch which displays Error while...
will be of little help. This method also leads to very bad Stack Overflow questions, because you can't describe the actual exception, the object involved or even the line of code where it happens.
You can also use the Locals Window
(Debug -> Windows -> Locals) to examine your objects.
Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.
See also:
Dim reg As CashRegister
...
TextBox1.Text = reg.Amount ' NRE
The problem is that Dim
does not create a CashRegister object; it only declares a variable named reg
of that Type. Declaring an object variable and creating an instance are two different things.
Remedy
The New
operator can often be used to create the instance when you declare it:
Dim reg As New CashRegister ' [New] creates instance, invokes the constructor
' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister
When it is only appropriate to create the instance later:
Private reg As CashRegister ' Declare
...
reg = New CashRegister() ' Create instance
Note: Do not use Dim
again in a procedure, including the constructor (Sub New
):
Private reg As CashRegister
'...
Public Sub New()
'...
Dim reg As New CashRegister
End Sub
This will create a local variable, reg
, which exists only in that context (sub). The reg
variable with module level Scope
which you will use everywhere else remains Nothing
.
Missing the
New
operator is the #1 cause ofNullReference Exceptions
seen in the Stack Overflow questions reviewed.Visual Basic tries to make the process clear repeatedly using
New
: Using theNew
Operator creates a new object and callsSub New
-- the constructor -- where your object can perform any other initialization.
To be clear, Dim
(or Private
) only declares a variable and its Type
. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public
defines the access level, not Scope.
For more information, see:
Arrays must also be instantiated:
Private arr as String()
This array has only been declared, not created. There are several ways to initialize an array:
Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}
' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}
Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer
, the As <Type>
and New
elements are optional:
Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}
The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type>
with Option Strict
:
Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}
Example: Array of class objects
Dim arrFoo(5) As Foo
For i As Integer = 0 To arrFoo.Count - 1
arrFoo(i).Bar = i * 10 ' Exception
Next
The array has been created, but the Foo
objects in it have not.
Remedy
For i As Integer = 0 To arrFoo.Count - 1
arrFoo(i) = New Foo() ' Create Foo instance
arrFoo(i).Bar = i * 10
Next
Using a List(Of T)
will make it quite difficult to have an element without a valid object:
Dim FooList As New List(Of Foo) ' List created, but it is empty
Dim f As Foo ' Temporary variable for the loop
For i As Integer = 0 To 5
f = New Foo() ' Foo instance created
f.Bar = i * 10
FooList.Add(f) ' Foo object added to list
Next
For more information, see:
.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also be instantiated or created.
Private myList As List(Of String)
..
myList.Add("ziggy") ' NullReference
You get the same exception for the same reason - myList
was only declared, but no instance created. The remedy is the same:
myList = New List(Of String)
' Or create an instance when declared:
Private myList As New List(Of String)
A common oversight is a class which uses a collection Type
:
Public Class Foo
Private barList As List(Of Bar)
Friend Function BarCount As Integer
Return barList.Count
End Function
Friend Sub AddItem(newBar As Bar)
If barList.Contains(newBar) = False Then
barList.Add(newBar)
End If
End Function
Either procedure will result in an NRE, because barList
is only declared, not instantiated. Creating an instance of Foo
will not also create an instance of the internal barList
. It may have been the intent to do this in the constructor:
Public Sub New ' Constructor
' Stuff to do when a new Foo is created...
barList = New List(Of Bar)
End Sub
As before, this is incorrect:
Public Sub New()
' Creates another barList local to this procedure
Dim barList As New List(Of Bar)
End Sub
For more information, see List(Of T)
Class.
Working with databases presents many opportunities for a NullReference because there can be many objects (Command
, Connection
, Transaction
, Dataset
, DataTable
, DataRows
....) in use at once. Note: It does not matter which data provider you are using -- MySQL, SQL Server, OleDB, etc. -- the concepts are the same.
Example 1
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim MaxRows As Integer
con.Open()
Dim sql = "SELECT * FROM tblfoobar_List"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "foobar")
con.Close()
MaxRows = ds.Tables("foobar").Rows.Count ' Error
As before, the ds
Dataset object was declared, but an instance was never created. The DataAdapter
will fill an existing DataSet
, not create one. In this case, since ds
is a local variable, the IDE warns you that this might happen:
When declared as a module/class level variable, as appears to be the case with con
, the compiler can't know if the object was created by an upstream procedure. Do not ignore warnings.
Remedy
Dim ds As New DataSet
Example 2
ds = New DataSet
da = New OleDBDataAdapter(sql, con)
da.Fill(ds, "Employees")
txtID.Text = ds.Tables("Employee").Rows(0).Item(1)
txtID.Name = ds.Tables("Employee").Rows(0).Item(2)
A typo is a problem here: Employees
vs Employee
. There was no DataTable
named "Employee" created, so a NullReferenceException
results trying to access it. Another potential problem is assuming there will be Items
which may not be so when the SQL includes a WHERE clause.
Remedy
Since this uses one table, using Tables(0)
will avoid spelling errors. Examining Rows.Count
can also help:
If ds.Tables(0).Rows.Count > 0 Then
txtID.Text = ds.Tables(0).Rows(0).Item(1)
txtID.Name = ds.Tables(0).Rows(0).Item(2)
End If
Fill
is a function returning the number of Rows
affected which can also be tested:
If da.Fill(ds, "Employees") > 0 Then...
Example 3
Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO,
TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN
FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con)
Dim ds As New DataSet
da.Fill(ds)
If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then
The DataAdapter
will provide TableNames
as shown in the previous example, but it does not parse names from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION")
references a non-existent table.
The Remedy is the same, reference the table by index:
If ds.Tables(0).Rows.Count > 0 Then
See also DataTable Class.
If myFoo.Bar.Items IsNot Nothing Then
...
The code is only testing Items
while both myFoo
and Bar
may also be Nothing. The remedy is to test the entire chain or path of objects one at a time:
If (myFoo IsNot Nothing) AndAlso
(myFoo.Bar IsNot Nothing) AndAlso
(myFoo.Bar.Items IsNot Nothing) Then
....
AndAlso
is important. Subsequent tests will not be performed once the first False
condition is encountered. This allows the code to safely 'drill' into the object(s) one 'level' at a time, evaluating myFoo.Bar
only after (and if) myFoo
is determined to be valid. Object chains or paths can get quite long when coding complex objects:
myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename")
It is not possible to reference anything 'downstream' of a null
object. This also applies to controls:
myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value"
Here, myWebBrowser
or Document
could be Nothing or the formfld1
element may not exist.
Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _
& "FROM Invoice where invoice_no = '" & _
Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _
Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _
Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _
Me.expiry.Text & "'", con)
Among other things, this code does not anticipate that the user may not have selected something in one or more UI controls. ListBox1.SelectedItem
may well be Nothing
, so ListBox1.SelectedItem.ToString
will result in an NRE.
Remedy
Validate data before using it (also use Option Strict
and SQL parameters):
Dim expiry As DateTime ' for text date validation
If (ComboBox5.SelectedItems.Count > 0) AndAlso
(ListBox1.SelectedItems.Count > 0) AndAlso
(ComboBox2.SelectedItems.Count > 0) AndAlso
(DateTime.TryParse(expiry.Text, expiry) Then
'... do stuff
Else
MessageBox.Show(...error message...)
End If
Alternatively, you can use (ComboBox5.SelectedItem IsNot Nothing) AndAlso...
Public Class Form1
Private NameBoxes = New TextBox(5) {Controls("TextBox1"), _
Controls("TextBox2"), Controls("TextBox3"), _
Controls("TextBox4"), Controls("TextBox5"), _
Controls("TextBox6")}
' same thing in a different format:
Private boxList As New List(Of TextBox) From {TextBox1, TextBox2, TextBox3 ...}
' Immediate NRE:
Private somevar As String = Me.Controls("TextBox1").Text
This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that Controls
does not exist in the current context, or "cannot reference non-static member". So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.
The arrays and collections cannot be initialized this way. This initialization code will run before the constructor creates the Form
or the Controls
. As a result:
somevar
assignment will result in an immediate NRE because Nothing doesn't have a .Text
propertyReferencing array elements later will result in an NRE. If you do this in Form_Load
, due to an odd bug, the IDE may not report the exception when it happens. The exception will pop up later when your code tries to use the array. This "silent exception" is detailed in this post. For our purposes, the key is that when something catastrophic happens while creating a form (Sub New
or Form Load
event), exceptions may go unreported, the code exits the procedure and just displays the form.
Since no other code in your Sub New
or Form Load
event will run after the NRE, a great many other things can be left uninitialized.
Sub Form_Load(..._
'...
Dim name As String = NameBoxes(2).Text ' NRE
' ...
' More code (which will likely not be executed)
' ...
End Sub
Note this applies to any and all control and component references making these illegal where they are:
Public Class Form1
Private myFiles() As String = Me.OpenFileDialog1.FileName & ...
Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..."
Private studentName As String = TextBox13.Text
Partial Remedy
It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New
as long as your code is after the InitializeComponent
call:
' Module level declaration
Private NameBoxes as TextBox()
Private studentName As String
' Form Load, Form Shown or Sub New:
'
' Using the OP's approach (illegal using OPTION STRICT)
NameBoxes = New TextBox() {Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...)
studentName = TextBox32.Text ' For simple control references
The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox
or Panel
) will not be found in Me.Controls
; they will be in the Controls collection of that Panel or GroupBox. Nor will a control be returned when the control name is misspelled ("TeStBox2"
). In such cases, Nothing
will again be stored in those array elements and an NRE will result when you attempt to reference it.
These should be easy to find now that you know what you are looking for:
"Button2" resides on a Panel
Remedy
Rather than indirect references by name using the form's Controls
collection, use the control reference:
' Declaration
Private NameBoxes As TextBox()
' Initialization - simple and easy to read, hard to botch:
NameBoxes = New TextBox() {TextBox1, TextBox2, ...)
' Initialize a List
NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...})
' or
NamesList = New List(Of TextBox)
NamesList.AddRange({TextBox1, TextBox2, TextBox3...})
Private bars As New List(Of Bars) ' Declared and created
Public Function BarList() As List(Of Bars)
bars.Clear
If someCondition Then
For n As Integer = 0 to someValue
bars.Add(GetBar(n))
Next n
Else
Exit Function
End If
Return bars
End Function
This is a case where the IDE will warn you that 'not all paths return a value and a NullReferenceException
may result'. You can suppress the warning, by replacing Exit Function
with Return Nothing
, but that does not solve the problem. Anything which tries to use the return when someCondition = False
will result in an NRE:
bList = myFoo.BarList()
For Each b As Bar in bList ' EXCEPTION
...
Remedy
Replace Exit Function
in the function with Return bList
. Returning an empty List
is not the same as returning Nothing
. If there is a chance that a returned object can be Nothing
, test before using it:
bList = myFoo.BarList()
If bList IsNot Nothing Then...
A badly implemented Try/Catch can hide where the problem is and result in new ones:
Dim dr As SqlDataReader
Try
Dim lnk As LinkButton = TryCast(sender, LinkButton)
Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow)
Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString()
ViewState("username") = eid
sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle,
Pager, mailaddress, from employees1 where username='" & eid & "'"
If connection.State <> ConnectionState.Open Then
connection.Open()
End If
command = New SqlCommand(sqlQry, connection)
'More code fooing and barring
dr = command.ExecuteReader()
If dr.Read() Then
lblFirstName.Text = Convert.ToString(dr("FirstName"))
...
End If
mpe.Show()
Catch
Finally
command.Dispose()
dr.Close() ' <-- NRE
connection.Close()
End Try
This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty Catch
.
There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader
. After the Catch
does nothing, Finally
tries to perform clean up, but since you cannot Close
a null DataReader
object, a brand new NullReferenceException
results.
An empty Catch
block is the devil's playground. This OP was baffled why he was getting an NRE in the Finally
block. In other situations, an empty Catch
may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)
Remedy
Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.
For Each row As DataGridViewRow In dgvPlanning.Rows
If Not IsDBNull(row.Cells(0).Value) Then
...
The IsDBNull
function is used to test if a value equals System.DBNull
: From MSDN:
The System.DBNull value indicates that the Object represents missing or non-existent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.
Remedy
If row.Cells(0) IsNot Nothing Then ...
As before, you can test for Nothing, then for a specific value:
If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then
Example 2
Dim getFoo = (From f In dbContext.FooBars
Where f.something = something
Select f).FirstOrDefault
If Not IsDBNull(getFoo) Then
If IsDBNull(getFoo.user_id) Then
txtFirst.Text = getFoo.first_name
Else
...
FirstOrDefault
returns the first item or the default value, which is Nothing
for reference types and never DBNull
:
If getFoo IsNot Nothing Then...
Dim chk As CheckBox
chk = CType(Me.Controls(chkName), CheckBox)
If chk.Checked Then
Return chk
End If
If a CheckBox
with chkName
can't be found (or exists in a GroupBox
), then chk
will be Nothing and be attempting to reference any property will result in an exception.
Remedy
If (chk IsNot Nothing) AndAlso (chk.Checked) Then ...
The DGV has a few quirks seen periodically:
dgvBooks.DataSource = loan.Books
dgvBooks.Columns("ISBN").Visible = True ' NullReferenceException
dgvBooks.Columns("Title").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Author").DefaultCellStyle.Format = "C"
dgvBooks.Columns("Price").DefaultCellStyle.Format = "C"
If dgvBooks
has AutoGenerateColumns = True
, it will create the columns, but it does not name them, so the above code fails when it references them by name.
Remedy
Name the columns manually, or reference by index:
dgvBooks.Columns(0).Visible = True
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To myDGV.RowCount - 1
For j = 0 To myDGV.ColumnCount - 1
For k As Integer = 1 To myDGV.Columns.Count
xlWorkSheet.Cells(1, k) = myDGV.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString()
Next
Next
Next
When your DataGridView
has AllowUserToAddRows
as True
(the default), the Cells
in the blank/new row at the bottom will all contain Nothing
. Most attempts to use the contents (for example, ToString
) will result in an NRE.
Remedy
Use a For/Each
loop and test the IsNewRow
property to determine if it is that last row. This works whether AllowUserToAddRows
is true or not:
For Each r As DataGridViewRow in myDGV.Rows
If r.IsNewRow = False Then
' ok to use this row
If you do use a For n
loop, modify the row count or use Exit For
when IsNewRow
is true.
Under certain circumstances, trying to use an item from My.Settings
which is a StringCollection
can result in a NullReference the first time you use it. The solution is the same, but not as obvious. Consider:
My.Settings.FooBars.Add("ziggy") ' foobars is a string collection
Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing
when there are no items in the Settings editor to add.
Remedy
Initialize the settings collection in the form's Load
event handler, if/when needed:
If My.Settings.FooBars Is Nothing Then
My.Settings.FooBars = New System.Collections.Specialized.StringCollection
End If
Typically, the Settings
collection will only need to be initialized the first time the application runs. An alternate remedy is to add an initial value to your collection in Project -> Settings | FooBars, save the project, then remove the fake value.
You probably forgot the New
operator.
or
Something yo
With SQL*PLUS you can also use the WHENEVER SQLERROR command:
WHENEVER SQLERROR CONTINUE NONE
DROP TABLE TABLE_NAME;
WHENEVER SQLERROR EXIT SQL.SQLCODE
DROP TABLE TABLE_NAME;
With CONTINUE NONE
an error is reported, but the script will continue. With EXIT SQL.SQLCODE
the script will be terminated in the case of an error.
see also: WHENEVER SQLERROR Docs
in fact for me just worked in ios disabling the scroll
<iframe src="//www.youraddress.com/" scrolling="no"></iframe>
and treating the OS via script.
To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.
This will allow you to follow the same pattern you have in other parts of your code with code such as...
const confirm = await ui.confirm('Are you sure you want to do this?');
if(confirm){
alert('yes clicked');
} else{
alert('no clicked');
}
See codepen for example, or run the snippet below.
https://codepen.io/larnott/pen/rNNQoNp
const ui = {_x000D_
confirm: async (message) => createConfirm(message)_x000D_
}_x000D_
_x000D_
const createConfirm = (message) => {_x000D_
return new Promise((complete, failed)=>{_x000D_
$('#confirmMessage').text(message)_x000D_
_x000D_
$('#confirmYes').off('click');_x000D_
$('#confirmNo').off('click');_x000D_
_x000D_
$('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });_x000D_
$('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });_x000D_
_x000D_
$('.confirm').show();_x000D_
});_x000D_
}_x000D_
_x000D_
const saveForm = async () => {_x000D_
const confirm = await ui.confirm('Are you sure you want to do this?');_x000D_
_x000D_
if(confirm){_x000D_
alert('yes clicked');_x000D_
} else{_x000D_
alert('no clicked');_x000D_
}_x000D_
}
_x000D_
body {_x000D_
margin: 0px;_x000D_
font-family: "Arial";_x000D_
}_x000D_
_x000D_
.example {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
input[type=button] {_x000D_
padding: 5px 10px;_x000D_
margin: 10px 5px;_x000D_
border-radius: 5px;_x000D_
cursor: pointer;_x000D_
background: #ddd;_x000D_
border: 1px solid #ccc;_x000D_
}_x000D_
input[type=button]:hover {_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.confirm {_x000D_
display: none;_x000D_
}_x000D_
.confirm > div:first-of-type {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
}_x000D_
.confirm > div:last-of-type {_x000D_
padding: 10px 20px;_x000D_
background: white;_x000D_
position: absolute;_x000D_
width: auto;_x000D_
height: auto;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
border-radius: 5px;_x000D_
border: 1px solid #333;_x000D_
}_x000D_
.confirm > div:last-of-type div:first-of-type {_x000D_
min-width: 150px;_x000D_
padding: 10px;_x000D_
}_x000D_
.confirm > div:last-of-type div:last-of-type {_x000D_
text-align: right;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="example">_x000D_
<input type="button" onclick="saveForm()" value="Save" />_x000D_
</div>_x000D_
_x000D_
<!-- Hidden confirm markup somewhere at the bottom of page -->_x000D_
_x000D_
<div class="confirm">_x000D_
<div></div>_x000D_
<div>_x000D_
<div id="confirmMessage"></div>_x000D_
<div>_x000D_
<input id="confirmYes" type="button" value="Yes" />_x000D_
<input id="confirmNo" type="button" value="No" />_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Based on an issue on Github of PhantomJS, the quit() does not terminate PhantomJS process. You should use:
import signal
driver = webdriver.PhantomJS(service_args=service_args)
# Do your work here
driver.service.process.send_signal(signal.SIGTERM)
driver.quit()
If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.
Lets say you have n as 8, and our numbers range from 0-8 for this example we can represent the binary representation of all 9 numbers as follows 0000 0001 0010 0011 0100 0101 0110 0111 1000
in the above sequence there is no missing numbers and in each column the number of zeros and ones match, however as soon as you remove 1 value lets say 3 we get a in balance in the number of 0's and 1's across the columns. If the number of 0's in a column is <= the number of 1's our missing number will have a 0 at this bit position, otherwise if the number of 0's > the number of 1's at this bit position then this bit position will be a 1. We test the bits left to right and at each iteration we throw away half of the array for the testing of the next bit, either the odd array values or the even array values are thrown away at each iteration depending on which bit we are deficient on.
The below solution is in C++
int getMissingNumber(vector<int>* input, int bitPos, const int startRange)
{
vector<int> zeros;
vector<int> ones;
int missingNumber=0;
//base case, assume empty array indicating start value of range is missing
if(input->size() == 0)
return startRange;
//if the bit position being tested is 0 add to the zero's vector
//otherwise to the ones vector
for(unsigned int i = 0; i<input->size(); i++)
{
int value = input->at(i);
if(getBit(value, bitPos) == 0)
zeros.push_back(value);
else
ones.push_back(value);
}
//throw away either the odd or even numbers and test
//the next bit position, build the missing number
//from right to left
if(zeros.size() <= ones.size())
{
//missing number is even
missingNumber = getMissingNumber(&zeros, bitPos+1, startRange);
missingNumber = (missingNumber << 1) | 0;
}
else
{
//missing number is odd
missingNumber = getMissingNumber(&ones, bitPos+1, startRange);
missingNumber = (missingNumber << 1) | 1;
}
return missingNumber;
}
At each iteration we reduce our input space by 2, i.e N, N/2,N/4 ... = O(log N), with space O(N)
//Test cases
[1] when missing number is range start
[2] when missing number is range end
[3] when missing number is odd
[4] when missing number is even
Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:
/* Function to add placeholders to form elements on IE 8 and below */_x000D_
function add_placeholders(fm) { _x000D_
for (var e = 0; e < document.fm.elements.length; e++) {_x000D_
if (fm.elements[e].placeholder != undefined &&_x000D_
document.createElement("input").placeholder == undefined) { // IE 8 and below _x000D_
fm.elements[e].style.background = "transparent";_x000D_
var el = document.createElement("span");_x000D_
el.innerHTML = fm.elements[e].placeholder;_x000D_
el.style.position = "absolute";_x000D_
el.style.padding = "2px;";_x000D_
el.style.zIndex = "-1";_x000D_
el.style.color = "#999999";_x000D_
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);_x000D_
fm.elements[e].onfocus = function() {_x000D_
this.style.background = "yellow"; _x000D_
}_x000D_
fm.elements[e].onblur = function() {_x000D_
if (this.value == "") this.style.background = "transparent";_x000D_
else this.style.background = "white"; _x000D_
} _x000D_
} _x000D_
}_x000D_
}_x000D_
_x000D_
add_placeholders(document.getElementById('fm'))
_x000D_
<form id="fm">_x000D_
<input type="text" name="email" placeholder="Email">_x000D_
<input type="password" name="password" placeholder="Password">_x000D_
<textarea name="description" placeholder="Description"></textarea>_x000D_
</form>
_x000D_
print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => í )
You can use the following
new java.sql.Timestamp(System.currentTimeMillis()).getTime()
Result : 1539594988651
Hope this will help. Just my suggestion and not for reward points.
I find the simple solution
pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))
Please don't throw stones at me for this solution.
This works but is a bit "hacky".
When you call requestPermissions
, register the current time.
mAskedPermissionTime = System.currentTimeMillis();
Then in onRequestPermissionsResult
if the result is not granted, check the time again.
if (System.currentTimeMillis() - mAskedPermissionTime < 100)
Since the user did cannot possibly click so fast on the deny button, we know that he selected "never ask again" because the callback is instant.
Use at your own risks.
Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:
domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ include:/\n/g' | \
tail -n+2)
for domain in $domainsToDig ; do
dig @8.8.8.8 $domain TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ ip.:/\n/g' | \
tail -n+2
done
It might be worth looking at a tutorial: MDN Canvas Tutorial
You can get the width and height of a canvas element simply by accessing those properties of the element. For example:
var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;
If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;
Or using the shorter object destructuring syntax:
const { width, height } = canvas.getBoundingClientRect();
The context
is an object you get from the canvas to allow you to draw into it. You can think of the context
as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.
I ran into this problem when trying to pull a third party package which was apparently including windows.h somewhere in it's mess of headers. Defining _WINSOCKAPI_
at the project level was much easier (not to mention more maintainable) than wading through their soup and fixing the problematic include.
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
here is the sample one
div{_x000D_
width: 200px;_x000D_
height:200px;_x000D_
border:solid_x000D_
}_x000D_
_x000D_
img{_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
object-fit: contain;_x000D_
}
_x000D_
<div>_x000D_
<img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png">_x000D_
</div>
_x000D_
you can use glob function to do this. see the example
import cv2
import glob
for img in glob.glob("path/to/folder/*.png"):
cv_img = cv2.imread(img)
Try brew install coreutils
.
I've hit this problem while rebuilding an aging sass/compass project that was recently updated to ruby 2.2.5 by a colleague. The project uses rvm and bundler. These were my commands
$ rvm install ruby-2.2.5
$ rvm use ruby-2.2.5
$ gem install bundler
$ bundle install
This caused me to hit the famed ffi
installation errors, that are reported around the StackOverflow environment:
An error occurred while installing ffi (1.9.14), and Bundler cannot continue.
Most of the suggestions to solve this problem are to install Xcode command line tools. However this was already installed in my environment:
$ xcode-select -p
/Library/Developer/CommandLineTools
Other suggestions said to install gcc... so I tried:
$ brew install gcc46
But this also failed due to a segmentation fault... ¯\_(?)_/¯
.
So, I then tried installing compass by hand, just to see if it would give the same ffi
error:
$ gem install compass
But to my surprise, I got a totally different error:
make: /usr/local/bin/gmkdir: No such file or directory
So I searched for that issue, and found this ancient blog post that said to install coreutils:
$ brew install coreutils
After installing coreutils
with Homebrew, bundler was able to finish and installed compass and dependencies successfully.
The End.
Imports
using Excel= Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
Here is the code to open an excel sheet using C#.
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
wbv.Close(true, Type.Missing, Type.Missing);
excel.Quit();
Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4
It's likely that your OS does not allow the number of threads you're trying to create, or you're hitting some limit in the JVM. Especially if it's such a round number as 32k, a limit of one kind or another is a very likely culprit.
Are you sure you truly need 32k threads? Most modern languages have some kind of support for pools of reusable threads - I'm sure Java has something in place too (like ExecutorService
, as user Jesper mentioned). Perhaps you could request threads from such a pool, instead of manually creating new ones.
I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.
Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support. However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.
So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private. I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.
public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);
private static string DoSomethingHelper<T>(this T input, ....)
{
// complex logic
}
This is my solution, i have the same issue and its seems like this solution work for me.
yourObj = [].concat(yourObj);
WARNING: @@ROWCOUNT
may return bogus data if the table being altered has triggers attached to it!
The @@ROWCOUNT
will return the number of records affected by the TRIGGER, not the actual statement!
You can write JavaScript code in your file .
Put following code in your client side file:
<script>
window.onload = function(){
window.open(url, "_blank"); // will open new tab on window.onload
}
</script>
using jQuery.ready
<script>
$(document).ready(function(){
window.open(url, "_blank"); // will open new tab on document ready
});
</script>
I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.
I had the following in my pom.xml
.
<build>
...
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<execution>
<id>generate-citrus-war</id>
<goals>
<goal>test-war</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
What I wanted, was to disable the execution of generate-citrus-war
for a specific profile and this was the solution:
<profile>
<id>it</id>
<build>
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<!-- disable generating the war for this profile -->
<execution>
<id>generate-citrus-war</id>
<phase/>
</execution>
<!-- do something else -->
<execution>
...
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.
This fails with the "select2 is not a function" error:
document.getElementById('e9').select2();
This works:
$("#e9").select2();
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}
Here's one I use:
$truncate = function( $str, $length ) {
if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
$str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
return htmlspecialchars($str[0]) . '…';
} else {
return htmlspecialchars($str);
}
};
return $truncate( $myStr, 50 );
Strings in Python are immutable meaning you cannot replace parts of them.
You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.
You could for instance write a function:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
And then for instance call it with:
new_string = replace_str_index(old_string,middle)
If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.
For instance:
replace_str_index('hello?bye',5)
will return 'hellobye'
; and:
replace_str_index('hello?bye',5,'good')
will return 'hellogoodbye'
.
What you want to do is actually again a groupby (on the result of the first groupby): sort and take the first three elements per group.
Starting from the result of the first groupby:
In [60]: df_agg = df.groupby(['job','source']).agg({'count':sum})
We group by the first level of the index:
In [63]: g = df_agg['count'].groupby('job', group_keys=False)
Then we want to sort ('order') each group and take the first three elements:
In [64]: res = g.apply(lambda x: x.sort_values(ascending=False).head(3))
However, for this, there is a shortcut function to do this, nlargest
:
In [65]: g.nlargest(3)
Out[65]:
job source
market A 5
D 4
B 3
sales E 7
C 6
B 4
dtype: int64
So in one go, this looks like:
df_agg['count'].groupby('job', group_keys=False).nlargest(3)
I used com.android.support.constraint:constraint-layout:1.0.0-alpha2 with classpath 'com.android.tools.build:gradle:2.1.0', it worked like charm.
Everybody seems to be suggesting that adding
using System.Configuration;
which is true.
But might I suggest that you think about installing ReSharper's Visual Studio extension?
With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.
The question is about doing this in bash and there's no need for python or perl as there is in fact a single command that does exactly what you want - "urlencode".
value=$(urlencode "${2}")
This is also much better, as the above perl answer, for example, doesn't encode all characters correctly. Try it with the long dash you get from Word and you get the wrong encoding.
Note, you need "gridsite-clients" installed to provide this command.
You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.
's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)
after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody
happy coding gl hf nerds
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html
I just want to add what worked for me, I added height and width to both divs and used bootstrap to make it responsive
<div class="col-lg-1 mapContainer">
<div id="map"></div>
</div>
#map{
height: 100%;
width:100%;
}
.mapContainer{
height:200px;
width:100%
}
in order for col-lg-1
to work add bootstrap reference located
Here
import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}
return this._http.get('http://url/login/' + email + '/' + password)
.map((res: Response) => {
return res.json();
}).catch(this._handleError);
If you are using NodeJs for your server side, just add these to your route and you will be Ok
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Your route will then look somehow like this
router.post('/odin', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.json({Name: req.body.name, Phone: req.body.phone});
});
Client side for Ajax call
var sendingData = {
name: "Odinfono Emmanuel",
phone: "1234567890"
}
<script>
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:3000/odin',
method: 'POST',
type: 'json',
data: sendingData,
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>
You should have something like this in your browser console as response
{ name: "Odinfono Emmanuel", phone: "1234567890"}
Enjoy coding....
What coobird and Gerald said.
Additionally, JPEG is the file format name. JPG is commonly used abbreviated file extension for this format, as you needed to have a 3-letter file extension for earlier Windows systems. Likewise with TIFF and TIF.
Web browsers at the moment only display JPEG, PNG and GIF files - so those are the ones that can be shown on web pages.
If you can use a simple delimiter, a very simple oneliner is this:
for i in a,b c_s,d ; do
KEY=${i%,*};
VAL=${i#*,};
echo $KEY" XX "$VAL;
done
Hereby i
is filled with character sequences like "a,b"
and "c_s,d"
. each separated by spaces. After the do
we use parameter substitution to extract the part before the comma ,
and the part after it.
Suppose you made changes to multiple files, like:
But you want to commit only changes of File1 and File3.
There are two ways for doing this:
1.Stage only these two files, using:
git add file1 file2
then, commit
git commit -m "your message"
then push,
git push
2.Direct commit
git commit file1 file3 -m "my message"
then push,
git push
Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects
I just made a getter method.
public int getNumberRows(){
try{
statement = connection.creatStatement();
resultset = statement.executeQuery("your query here");
if(resultset.last()){
return resultset.getRow();
} else {
return 0; //just cus I like to always do some kinda else statement.
}
} catch (Exception e){
System.out.println("Error getting row count");
e.printStackTrace();
}
return 0;
}
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)
Step 1: Install NuGet Package by "Install-Package reCAPTCH.MVC"
Step 2: Add your Public and Private key to your web.config file in appsettings section
<appSettings>
<add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
<add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>
You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page
Step 3: Modify your form to include reCaptcha
@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
@Html.Recaptcha()
@Html.ValidationMessage("ReCaptcha")
<input type="submit" value="Register" />
}
Step 4: Implement the Controller Action that will handle the form submission and Captcha validation
[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
if (ModelState.IsValid) //this will take care of captcha
{
}
}
OR
public ActionResult MyAction(myVM model, bool captchaValid)
{
if (captchaValid) //manually check for captchaValid
{
}
}