Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
<script>
var today = new Date;
document.getElementById('date').innerHTML= today.toDateString();
</script>
string str1, str2, str3;
cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;
From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:
string str1 = "the dog jumped over the fence",
str2 = "the",
str3 = "that";
cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
Be careful, when you register by
LocalBroadcastManager.getInstance(this).registerReceiver()
you can't unregister by
unregisterReceiver()
you must use
LocalBroadcastManager.getInstance(this).unregisterReceiver()
or app will crash, log as follow:
09-30 14:00:55.458 19064-19064/com.jialan.guangdian.view E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jialan.guangdian.view, PID: 19064 java.lang.RuntimeException: Unable to stop service com.google.android.exoplayer.demo.player.PlayService@141ba331: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.ActivityThread.handleStopService(ActivityThread.java:2941) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:769) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1794) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:510) at com.google.android.exoplayer.demo.player.PlayService.onDestroy(PlayService.java:542) at android.app.ActivityThread.handleStopService(ActivityThread.java:2924) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback.
I am assuming that you have used height attribute at both so i am comparing it with a height left do it with JavaScript.
var right=document.getElementById('rightdiv').style.height;
var left=document.getElementById('leftdiv').style.height;
if(left>right)
{
document.getElementById('rightdiv').style.height=left;
}
else
{
document.getElementById('leftdiv').style.height=right;
}
Another idea can be found here HTML/CSS: Making two floating divs the same height.
Use \n
for a line break and \t
if you want to insert a tab.
You can also use some XML tags for basic formatting: <b>
for bold text, <i>
for italics, and <u>
for underlined text.
Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();
//if List not empty
if (!(sList.size() ==0)) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.
I just thought I'd mention something here which I had to spent a long time experimenting with before I finally realised what was going on. This may be so obvious to everyone here that they haven't bothered mentioning it. But it would've helped me if they had, so on that principle...!
NB: I am using Jython specifically, v 2.7, so just possibly this may not apply to CPython...
NB2: the first two lines of my .py file here are:
# -*- coding: utf-8 -*-
from __future__ import print_function
The "%" (AKA "interpolation operator") string construction mechanism causes ADDITIONAL problems too... If the default encoding of the "environment" is ASCII and you try to do something like
print( "bonjour, %s" % "fréd" ) # Call this "print A"
You will have no difficulty running in Eclipse... In a Windows CLI (DOS window) you will find that the encoding is code page 850 (my Windows 7 OS) or something similar, which can handle European accented characters at least, so it'll work.
print( u"bonjour, %s" % "fréd" ) # Call this "print B"
will also work.
If, OTOH, you direct to a file from the CLI, the stdout encoding will be None, which will default to ASCII (on my OS anyway), which will not be able to handle either of the above prints... (dreaded encoding error).
So then you might think of redirecting your stdout by using
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
and try running in the CLI piping to a file... Very oddly, print A above will work... But print B above will throw the encoding error! The following will however work OK:
print( u"bonjour, " + "fréd" ) # Call this "print C"
The conclusion I have come to (provisionally) is that if a string which is specified to be a Unicode string using the "u" prefix is submitted to the %-handling mechanism it appears to involve the use of the default environment encoding, regardless of whether you have set stdout to redirect!
How people deal with this is a matter of choice. I would welcome a Unicode expert to say why this happens, whether I've got it wrong in some way, what the preferred solution to this, whether it also applies to CPython, whether it happens in Python 3, etc., etc.
C2DM: your app-users must have the gmail account.
MQTT: when your connection reached to 1024, it will stop work because of it used "select model " of linux.
There is a free push service and api for android, you can try it: http://push-notification.org
You need a table variable and it can be this simple.
declare @ID table (ID int)
insert into MyTable2(ID)
output inserted.ID into @ID
values (1)
INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;
Yes, on a 32bit machine the maximum amount of memory usable is around 4GB. Actually, depending on the OS it might be less due to parts of the address space being reserved: On Windows you can only use 3.5GB for example.
On 64bit you can indeed address 2^64 bytes of memory. Not that you'll ever have those - but then again, a long time ago the same thing was said about ever needing more than 640kb of memory...
From the Javadoc for Character#getNumericValue
:
If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.
The character +
does not have a numeric value, so you're getting -1.
Update:
The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.
you should make out two period time which are compile time and runtime time.for example:
//example 1
"test" == "test" // --> true
"test" == "te" + "st" // --> true
//example 2
"test" == "!test".substring(1) // --> false
"test" == "!test".substring(1).intern() // --> true
in the one hand,in the example 1,we find the results are all return true,because in the compile time,the jvm will put the "test" to the pool of literal strings,if the jvm find "test" exists,then it will use the exists one,in example 1,the "test" strings are all point to the same memory address,so the example 1 will return true. in the other hand,in the example 2,the method of substring() execute in the runtime time, in the case of "test" == "!test".substring(1),the pool will create two string object,"test" and "!test",so they are different reference objects,so this case will return false,in the case of "test" == "!test".substring(1).intern(),the method of intern() will put the ""!test".substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.
Here is a neat trick which lets the system deal with leap years automagically. It gives an accurate answer for all date combinations.
DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);
DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
years++;
tmp = tmp.AddYears(1);
}
Console.WriteLine("{0}", years);
I faced the same problem today, please check for the path of the image as mentioned by cybseccrypt. After imread, try printing the image and see. If you get a value, it means the file is open.
Code:
img_src = cv2.imread('/home/deepak/python-workout/box2.jpg',0)
print img_src
Hope this helps!
This worked in my case, in both Firefox and Chrome:
td {
max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
}
HTML5 is supported on both Google (android) phones such as Galaxy S, and iPhone. iPhone however doesn't support Flash, which Google phones do support.
Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return confirm("Do you really want to close?");
});
});
For simple follow following steps:
It should show following picture:
The answer (I hope) no one ever wanted
Eval like behavior
getattr(locals().get("foo") or globals().get("foo"), "bar")()
Why not add auto-importing
getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
In case we have extra dictionaries we want to check
getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
We need to go deeper
getattr(next((x for x in (f("foo") for f in
([locals().get, globals().get, self.__dict__.get] +
[d.get for d in (list(dd.values()) for dd in
[locals(),globals(),self.__dict__]
if isinstance(dd,dict))
if isinstance(d,dict)] +
[__import__]))
if x)),
"bar")()
Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
} else {
//do something
}
} else {
//do something
}
To remove spaces... please use LTRIM
/RTRIM
LTRIM(String)
RTRIM(String)
The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.
SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers
Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi
I was faced with the same challenge, especially when importing multiple files, this is how I managed to overcome it.
import os, sys
from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))
from root_folder import file_name
You can do something like this:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
The above answers are wrong, respectively aren't answering why you're having troubles viewing the demo-content prod-mode.
Here's the correct answer: clear your "prod"-cache:
php app/console cache:clear --env prod
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-"
for a red line, or by explicitely stating the color
argument.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
See also the plot command's documentation.
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
If you want to change this color later on, you can do so by
plt.gca().get_lines()[0].set_color("black")
This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
and if you have more lines you can loop over them as well.
For Dockerfile, this works for me:
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
How to install locale-gen?
It seems that display: block
elements do not inherit opacity from display: inline
parents.
Maybe because it's invalid markup and the browser is secretly separating them? Because source doesn't show that happening. Am I missing something?
Try this
<input type="button" onClick="return click();">button text</input>
I replaced all the single quotes ['] to double quotes ["] and then it worked perfectly. Thanks for the input by @LogicalKip.
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
The accepted answer works, but I don't like much the idea to paste secure tokens into the package.json
I have found it elsewhere, just run this one-time command as documented in the git-config manpage.
git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf [email protected]:
GITHUB_TOKEN
may be setup as environmnet variable or pasted directly
and then I install private github repos like: npm install user/repo --save
works also in Heroku, just setup the above git config ...
command as heroku-prebuild
script in package.json
and setup GITHUB_TOKEN
as Heroku config variable.
In todays JavaScript, this will work as well..
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
_x000D_
I wrote a reallllllllllllllllly simple plugin for myself several years ago:
To add to your page all you need to do is put this in the head:
<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">
Then in JS:
jconsole.color.red.log('hellllooo world');
The framework has code for:
jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();
as well as:
jconsole.css.log("hello world","color:red;");
for any other css. The above is designed with the following syntax:
jconsole.css.log(message to log,css code to style the logged message)
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
Great Start. Here's what I came up with:
$('img.resize').each(function(){
$(this).load(function(){
var maxWidth = $(this).width(); // Max width for the image
var maxHeight = $(this).height(); // Max height for the image
$(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
$(this).removeAttr("width").removeAttr("height"); // Remove HTML attributes
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > height) {
// Check if the current width is larger than the max
if(width > maxWidth){
var ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
} else {
// Check if current height is larger than max
if(height > maxHeight){
var ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
}
});
});
This has the benefit of allowing you to specify both width and height while allowing the image to still scale proportionally.
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
getDateFromFormat(val,format);
Also see this: Parse DateTime string in JavaScript
If your panel is 'not opaque' (transparent) you wont see your background color.
Generic Webhook Trigger Plugin can be configured with filters to achieve this.
When configured with
ref
and expression $.ref
.$ref
and filter expression like ^refs/heads/master$
.Then that job will trigger for every push to master
. No polling.
You probably want more values from the webhook to actually perform the build. Just add more variables, with JSONPath, to pick what you need.
There are some use cases here: https://github.com/jenkinsci/generic-webhook-trigger-plugin/tree/master/src/test/resources/org/jenkinsci/plugins/gwt/bdd
In my case, I was setting "Embed Without Signing" on some frameworks in "Project -> General -> Frameworks, Libraries, and Embedded Content" tab, which causes unknown conflicts in the project.
It finally works when I set "Embed and Sign" to those frameworks which needed to be embedded.
To extend user Zen's answer, you could add the following line in your ~/.vimrc
file to allow quick toggling between Bash and Vim:
noremap <C-d> :sh<cr>
There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la
make -j4
Or you can use pmake or similar parallel make systems.
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
Here is a quick way to do it in 2021 using the Anaconda Navigator. This is the most reliable way to do it, unless you want to create environments programmatically which I don't think is the case for most users:
There are still a few minor bugs when setting up your environment, most of them should be solved by restarting the Navigator.
If you find a bug, please help us posting it in the Anaconda Issues bug-tracker too! If you run into trouble creating the environment or if the environment was not correctly created you can double check what got installed: Clicking the "Environments" opens a management window showing installed packages. Search and select Spyder-related packages and then click on "Apply" to install them.
You could check this if you like. :)
Use this code if SavedFamilyCode is in the Report Filter:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").CurrentPage = _
"K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
But if the SavedFamilyCode is in the Column or Row Labels use this code:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").PivotFilters. _
Add Type:=xlCaptionEquals, Value1:="K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
Hope this helps you.
Try this, it works for both node and the browser.
isNode = (typeof exports !== 'undefined') &&
(typeof module !== 'undefined') &&
(typeof module.exports !== 'undefined') &&
(typeof navigator === 'undefined' || typeof navigator.appName === 'undefined') ? true : false,
asyncIt = (isNode ? function (func) {
process.nextTick(function () {
func();
});
} : function (func) {
setTimeout(func, 5);
});
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse()
and fromstring()
methods.
@kajetons' answer is fully functional.
You can also pass multiple variables by passing them like: use($var1, $var2)
DB::table('users')->where(function ($query) use ($activated,$var2) {
$query->where('activated', '=', $activated);
$query->where('var2', '>', $var2);
})->get();
Set the auto complete:
$("#searchBox").autocomplete({
source: queryDB
});
The source function that gets the data:
function queryDB(request, response) {
var query = request.term;
var data = getDataFromDB(query);
response(data); //puts the results on the UI
}
I think you can also execute this command:
select (sysdate-1) PREVIOUS_DATE from dual;
I try to contribute my code collaboration with my friend . modification from this forum.
$('#upload').on('click', function() {
var fd = new FormData();
var c=0;
var file_data,arr;
$('input[type="file"]').each(function(){
file_data = $('input[type="file"]')[c].files; // get multiple files from input file
console.log(file_data);
for(var i = 0;i<file_data.length;i++){
fd.append('arr[]', file_data[i]); // we can put more than 1 image file
}
c++;
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
});
this my html file
<form name="form" id="form" method="post" enctype="multipart/form-data">
<input type="file" name="file[]"multiple>
<input type="button" name="submit" value="upload" id="upload">
this php code file
<?php
$count = count($_FILES['arr']['name']); // arr from fd.append('arr[]')
var_dump($count);
echo $count;
var_dump($_FILES['arr']);
if ( $count == 0 ) {
echo 'Error: ' . $_FILES['arr']['error'][0] . '<br>';
}
else {
$i = 0;
for ($i = 0; $i < $count; $i++) {
move_uploaded_file($_FILES['arr']['tmp_name'][$i], 'uploads/' . $_FILES['arr']['name'][$i]);
}
}
?>
I hope people with same problem , can fast solve this problem. i got headache because multiple upload image.
How to convert decimal to hexadecimal in JavaScript
I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.
function DecToHex(decimal) { // Data (decimal)
length = -1; // Base string length
string = ''; // Source 'string'
characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array
do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift
string += characters[decimal & 0xF]; // Mask byte, get that character
++length; // Increment to length of string
} while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0
decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'
do
decimal += string[length];
while (length--); // Flip string forwards, with the prefixed '0x'
return (decimal); // return (hexadecimal);
}
/* Original: */
D = 3678; // Data (decimal)
C = 0xF; // Check
A = D; // Accumulate
B = -1; // Base string length
S = ''; // Source 'string'
H = '0x'; // Destination 'string'
do {
++B;
A& = C;
switch(A) {
case 0xA: A='A'
break;
case 0xB: A='B'
break;
case 0xC: A='C'
break;
case 0xD: A='D'
break;
case 0xE: A='E'
break;
case 0xF: A='F'
break;
A = (A);
}
S += A;
D >>>= 0x04;
A = D;
} while(D)
do
H += S[B];
while (B--)
S = B = A = C = D; // Zero out variables
alert(H); // H: holds hexadecimal equivalent
You need text()
or html()
for label not val()
The function should not be called for label instead it is used to get values of input like text or checkbox etc.
Change
value = $("#telefon").val();
To
value = $("#telefon").text();
I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList
.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList
It's worth reading Oracle Java Tutorial - Getting and Setting Field Values
Field#set(Object object, Object value) sets the field represented by this Field
object on the specified object argument to the specified new value.
It should be like this
f.set(objectOfTheClass, new ConcurrentHashMap<>());
You can't set any value in null
Object If tried then it will result in NullPointerException
Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.
string referrer = HttpContext.Current.Request.UrlReferrer.ToString();
In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:
public static string GetSha256FromString(string strData)
{
var message = Encoding.ASCII.GetBytes(strData);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
var hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
From Ian Bicking's own introduction to pip:
pip was originally written to improve on easy_install in the following ways
- All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
- Care is taken to present useful output on the console.
- The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
- Error messages should be useful.
- The code is relatively concise and cohesive, making it easier to use programmatically.
- Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
- Native support for other version control systems (Git, Mercurial and Bazaar)
- Uninstallation of packages.
- Simple to define fixed sets of requirements and reliably reproduce a set of packages.
If you try joining C on a field from B before joining B, i.e.:
SELECT A.x,
A.y,
A.z
FROM A
INNER JOIN C
on B.x = C.x
INNER JOIN B
on A.x = B.x
your query will fail, so in this case the order matters.
Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator"
to your form element.
<form role="form" data-toggle="validator">
...
</form>
Or activate validation via JavaScript:
$('#myForm').validator()
and you need to use required flag in input field
For more details Click Here
The getimagesize() should be the most definite way of working out whether the file is an image:
if(@is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
because this is a sample getimagesize() output:
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params
.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params
param)
For me:
.ui-jqgrid .ui-jqgrid-bdiv {
position: relative;
margin: 0;
padding: 0;
overflow-y: auto; <------
overflow-x: hidden; <-----
text-align: left;
}
Of course remove the arrows
What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.
One way (which I've been doing) is to setup manually :
refs: {
[string: string]: any;
stepInput:any;
}
then you can even wrap this up in a nicer getter function (e.g. here):
stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);
Another fix for those who have IIS Installed:
Create a path on the IIS Server, and allocate your website/app there.
Go to propieties of the solution of the explorer, then in front of using the iisexpress from visual studio, make that vs uses your personal own IIS.
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
What you are trying to achieve should be done in the web browser because javascript simply doesn't work with html email design. The various email clients that are out there e.g. gmail, outlook, yahoo strip scripts put of the code for security reasons.
It is best to just use HTML and CSS to style your emails. Maybe you could have a call to action (cta) in your html email that sends the user to a web page with your expanding and collapsing content feature.
I did a similar solution. I've created a snippet to replace 'vardump' with this:
foreach ($variable as $key => $reg) {
echo "<pre>{$key} => '{$reg}'</pre>";
}
var_dump($variable);die;
Ps: I'm repeating the data with the last var_dump to get the filename and line
Let me know if this will help you.
follow http://support.microsoft.com/kb/896456
To start a 32-bit command prompt, follow these steps:
* Click Start, click Run, type %windir%\SysWoW64\cmd.exe, and then click OK.
Then type
cscript vbscriptfile.vbs
$(this.parentNode).addClass('newClass');
Change the line where you print the output to:
printf("\nmaximum of %d and %d is = %d",a,b,c);
See the docs here
You can try with:
display: inline-table;
For me it works fine.
As you discovered, in VS11 the compiler will disallow an async Main
method. This was allowed (but never recommended) in VS2010 with the Async CTP.
I have recent blog posts about async/await and asynchronous console programs in particular. Here's some background info from the intro post:
If "await" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method. Await will also capture the current context when it passes the remainder of the method to the awaitable.
Later on, when the awaitable completes, it will execute the remainder of the async method (within the captured context).
Here's why this is a problem in Console programs with an async Main
:
Remember from our intro post that an async method will return to its caller before it is complete. This works perfectly in UI applications (the method just returns to the UI event loop) and ASP.NET applications (the method returns off the thread but keeps the request alive). It doesn't work out so well for Console programs: Main returns to the OS - so your program exits.
One solution is to provide your own context - a "main loop" for your console program that is async-compatible.
If you have a machine with the Async CTP, you can use GeneralThreadAffineContext
from My Documents\Microsoft Visual Studio Async CTP\Samples(C# Testing) Unit Testing\AsyncTestUtilities. Alternatively, you can use AsyncContext
from my Nito.AsyncEx NuGet package.
Here's an example using AsyncContext
; GeneralThreadAffineContext
has almost identical usage:
using Nito.AsyncEx;
class Program
{
static void Main(string[] args)
{
AsyncContext.Run(() => MainAsync(args));
}
static async void MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
Alternatively, you can just block the main Console thread until your asynchronous work has completed:
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
Note the use of GetAwaiter().GetResult()
; this avoids the AggregateException
wrapping that happens if you use Wait()
or Result
.
Update, 2017-11-30: As of Visual Studio 2017 Update 3 (15.3), the language now supports an async Main
- as long as it returns Task
or Task<T>
. So you can now do this:
class Program
{
static async Task Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
The semantics appear to be the same as the GetAwaiter().GetResult()
style of blocking the main thread. However, there's no language spec for C# 7.1 yet, so this is only an assumption.
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Merge object2 into object1
$.extend( object1, object2 );
I had an inversion problem, but a neat solution.
Motivation was that the XAML designer would show an empty control e.g. when there was no datacontext / no MyValues
(itemssource).
Initial code: hide control when MyValues
is empty.
Improved code: show control when MyValues
is NOT null or empty.
Ofcourse the problem is how to express '1 or more items', which is the opposite of 0 items.
<ListBox ItemsSource={Binding MyValues}">
<ListBox.Style x:Uid="F404D7B2-B7D3-11E7-A5A7-97680265A416">
<Style TargetType="{x:Type ListBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding MyValues.Count}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
I solved it by adding:
<DataTrigger Binding="{Binding MyValues.Count, FallbackValue=0, TargetNullValue=0}">
Ergo setting the default for the binding. Ofcourse this doesn't work for all kinds of inverse problems, but helped me out with clean code.
yes no more function extending for setup setter & getter this is my example Object.defineProperty(obj,name,func)
var obj = {};
['data', 'name'].forEach(function(name) {
Object.defineProperty(obj, name, {
get : function() {
return 'setter & getter';
}
});
});
console.log(obj.data);
console.log(obj.name);
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
Actually Im agree with MikeW (+1) it's better to use profiler for this case.
Anyway, if you really need to grab all (n)varchar columns in db and make a search. See below. I suppose to use INFORMATION_SCHEMA.Tables + dynamic SQL. The plain search:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSV VARCHAR(2000), SQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSV)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ','
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH('')
)
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSV IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSV)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSV
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSV = SUBSTRING(ColumnNamesCSV, 0, LEN(ColumnNamesCSV))
UPDATE @Tables
SET SQL = 'SELECT * FROM ['+TableName+'] WHERE '''+@SearchText+''' IN ('+ColumnNamesCSV+')'
DECLARE @C INT,
@I INT,
@SQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @SQL = SQL FROM @Tables WHERE N = @I
SET @I = @I+1
EXEC(@SQL)
END
and one with LIKE clause:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSVLike VARCHAR(2000), LIKESQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSVLike)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ' LIKE ''%'+@SearchText+'%'' OR '
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH(''))
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSVLike IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSVLike)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSVLike
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSVLike = SUBSTRING(ColumnNamesCSVLike, 0, LEN(ColumnNamesCSVLike)-2)
UPDATE @Tables SET LIKESQL = 'SELECT * FROM ['+TableName+'] WHERE '+ColumnNamesCSVLike
DECLARE @C INT,
@I INT,
@LIKESQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @LIKESQL = LIKESQL FROM @Tables WHERE N = @I
SET @I = @I +1
EXEC(@LIKESQL)
END
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
Case in method names is important, so no addclass
.
Most of the answers here violate the single responsibility principle (a service class should not resolve dependencies itself) and/or use the service locator anti-pattern.
Another option to avoid these problems is to:
I’ve written an article with more details: Dependency Injection in .NET: A way to work around missing named registrations
You need an all in one environment. You may use MAMP or XAMPP or any other tools. After installing one of these tools you will need to edit(create) your .bash_profile(Assuming that you use bash).
Or even simple and more professional you can use Laravel Homestead.
Here is a link to official documentation: http://laravel.com/docs/5.0/homestead
Also Jeffrey has a free tutorial about it: https://laracasts.com/series/laravel-5-fundamentals/episodes/2
I advice you to go with homestead because you will preinstall all of the following tools.
If you just want the DOM attributes, it's probably simpler to use the attributes
node list on the element itself:
var el = document.getElementById("someId");
for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){
arr.push(atts[i].nodeName);
}
Note that this fills the array only with attribute names. If you need the attribute value, you can use the nodeValue
property:
var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
}
Here's a method that worked for me. When you type into the field, it puts that text into the hidden span, then gets its new width and applies it to the input field. It grows and shrinks with your input, with a safeguard against the input virtually disappearing when you erase all input. Tested in Chrome. (EDIT: works in Safari, Firefox and Edge at the time of this edit)
function travel_keyup(e)_x000D_
{_x000D_
if (e.target.value.length == 0) return;_x000D_
var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
oSpan.textContent=e.target.value;_x000D_
match_span(e.target, oSpan);_x000D_
}_x000D_
function travel_keydown(e)_x000D_
{_x000D_
if (e.key.length == 1)_x000D_
{_x000D_
if (e.target.maxLength == e.target.value.length) return;_x000D_
var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
oSpan.textContent=e.target.value + '' + e.key;_x000D_
match_span(e.target, oSpan);_x000D_
}_x000D_
}_x000D_
function match_span(oInput, oSpan)_x000D_
{_x000D_
oInput.style.width=oSpan.getBoundingClientRect().width + 'px';_x000D_
}_x000D_
_x000D_
window.addEventListener('load', function()_x000D_
{_x000D_
var oInput=document.querySelector('#menu-enter-travel input');_x000D_
oInput.addEventListener('keyup', travel_keyup);_x000D_
oInput.addEventListener('keydown', travel_keydown);_x000D_
_x000D_
match_span(oInput, document.querySelector('#menu-enter-travel span'));_x000D_
});
_x000D_
#menu-enter-travel input_x000D_
{_x000D_
width: 8px;_x000D_
}_x000D_
#menu-enter-travel span_x000D_
{_x000D_
visibility: hidden;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
}
_x000D_
<div id="menu-enter-travel">_x000D_
<input type="text" pattern="^[0-9]{1,4}$" maxlength="4">KM_x000D_
<span>9</span>_x000D_
</div>
_x000D_
I had the same problem using composer in wsl2.
Microsoft WSL team introduced a file called .wslconfig for tweaking WSL2 settings.
You basically have to create that file at %UserProfile%.wslconfig and set the settings below.
[wsl2]
memory=6GB # Any size you feel like
swap=30GB
localhostForwarding=true
Restart your computer, and from now on, you won't have any problem with high memory consumption.
Hopefully, it helps!
Another example to illustrate the __declspec keyword:
When you are writing a Windows Kernel Driver, sometimes you want to write your own prolog/epilog code sequences using inline assembler code, so you could declare your function with the naked attribute.
__declspec( naked ) int func( formal_parameters ) {}
Or
#define Naked __declspec( naked )
Naked int func( formal_parameters ) {}
Please refer to naked (C++)
enum ServicePlatform {
UPLAY = "uplay",
PSN = "psn",
XBL = "xbl"
}
becomes:
{ UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
so
ServicePlatform.UPLAY in ServicePlatform // false
SOLUTION:
ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
Both “relative” and “absolute” positioning are really relative, just with different framework. “Absolute” positioning is relative to the position of another, enclosing element. “Relative” positioning is relative to the position that the element itself would have without positioning.
It depends on your needs and goals which one you use. “Relative” position is suitable when you wish to displace an element from the position it would otherwise have in the flow of elements, e.g. to make some characters appear in a superscript position. “Absolute” positioning is suitable for placing an element in some system of coordinates set by another element, e.g. to “overprint” an image with some text.
As a special, use “relative” positioning with no displacement (just setting position: relative
) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).
Here is another way:
df[[i for i in list(df.columns) if i != '<your column>']]
You just pass all columns to be shown except of the one you do not want.
Simple Solution, use methods that Android has already given, rather than reinventing wheeeeeeeeeel :-)
editComment.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
return true;
}
}
return false;
}
});
module Status
BAD = 13
GOOD = 24
def self.to_str(status)
for sym in self.constants
if self.const_get(sym) == status
return sym.to_s
end
end
end
end
mystatus = Status::GOOD
puts Status::to_str(mystatus)
Output:
GOOD
You need to run this command in the top-level directory of a Selenium SVN repository checkout.
Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)
I had same error, just uninstalled and installed again the numpy package, that worked!
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
Well, as colon is kind of special symbol, but is part of method signature, it is possible to exted the NSString
with category to add this non-idiomatic style of string concatenation:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
You can define as many colon separated arguments as you find useful... ;-)
For a good measure, I've also added concat:
with variable arguments that takes nil
terminated list of strings.
// NSString+Concatenation.h
#import <Foundation/Foundation.h>
@interface NSString (Concatenation)
- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;
- (NSString *)concat:(NSString *)strings, ...;
@end
// NSString+Concatenation.m
#import "NSString+Concatenation.h"
@implementation NSString (Concatenation)
- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
{ return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
{ return [[[[self:a]:b]:c]:d];}
- (NSString *)concat:(NSString *)strings, ...
{
va_list args;
va_start(args, strings);
NSString *s;
NSString *con = [self stringByAppendingString:strings];
while((s = va_arg(args, NSString *)))
con = [con stringByAppendingString:s];
va_end(args);
return con;
}
@end
// NSString+ConcatenationTest.h
#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"
@interface NSString_ConcatenationTest : SenTestCase
@end
// NSString+ConcatenationTest.m
#import "NSString+ConcatenationTest.h"
@implementation NSString_ConcatenationTest
- (void)testSimpleConcatenation
{
STAssertEqualObjects([@"a":@"b"], @"ab", nil);
STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
@"this is string concatenation", nil);
}
- (void)testVarArgConcatenation
{
NSString *concatenation = [@"a" concat:@"b", nil];
STAssertEqualObjects(concatenation, @"ab", nil);
concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
STAssertEqualObjects(concatenation, @"abcdab", nil);
}
What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:
d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \
jsonStringB["timestamp_in_ms"]
Merging method is obviously up to you.
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
This is the deep cloning method I use, I think it Great, hope you make suggestions
function deepClone (obj) {
var _out = new obj.constructor;
var getType = function (n) {
return Object.prototype.toString.call(n).slice(8, -1);
}
for (var _key in obj) {
if (obj.hasOwnProperty(_key)) {
_out[_key] = getType(obj[_key]) === 'Object' || getType(obj[_key]) === 'Array' ? deepClone(obj[_key]) : obj[_key];
}
}
return _out;
}
Nowadays asuming you have Android Studio installed (2.2) in my case and just 1 emulator you might use this one liner
export ANDROID_SDK_ROOT=~/Library/Android/sdk/ && emulator '@'`emulator -list-avds`
If you do this often, make it easier:
$ echo 'export ANDROID_SDK_ROOT=~/Library/Android/sdk/' >> ~/.profile
Add an alias to ~.aliases
alias androidup="emulator '@'`emulator -list-avds`"
Recall to source ~/.profile ~/.aliases
before testing it
Next time just $ androidup
This question has a lot of answers but all they looks not very useful in case if you really want to use backgroundColor to style your buttons. UIButton has nice option to set different images for different control states but there is not same feature for background colors. So one of solutions is to add extension which will generate images from color and apply them to button.
extension UIButton {
private func image(withColor color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
self.setBackgroundImage(image(withColor: color), for: state)
}
}
Only one issue with this solution -- this change won't be applied to buttons created in storyboard. As for me it's not an issue because I prefer to style UI from code. If you want to use storyboards then some additional magic with @IBInspectable
needed.
Second option is subclassing but I prefer to avoid this.
Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.
for any Element type
extension Array {
func joined(glue:()->Element)->[Element]{
var result:[Element] = [];
result.reserveCapacity(count * 2);
let last = count - 1;
for (ix,item) in enumerated() {
result.append(item);
guard ix < last else{ continue }
result.append(glue());
}
return result;
}
}
And you can combine same events/functions in this way:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
'click blur paste' : function() {
// Handle click...
}
}, "input");
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
You can do it in this way with Swift 3.0:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.
public class PrivilegesToClaimsTransformer : IClaimsTransformation
{
private readonly IPrivilegeProvider privilegeProvider;
public const string DidItClaim = "http://foo.bar/privileges/resolved";
public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
{
this.privilegeProvider = privilegeProvider;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is ClaimsIdentity claimer)
{
if (claimer.HasClaim(DidItClaim, bool.TrueString))
{
return principal;
}
var privileges = await this.privilegeProvider.GetPrivileges( ... );
claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));
foreach (var privilegeAsRole in privileges)
{
claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
}
}
return principal;
}
}
To use this in your Controller just add an appropriate [Authorize(Roles="whatever")]
to your methods.
[HttpGet]
[Route("poc")]
[Authorize(Roles = "plugh,blast")]
public JsonResult PocAuthorization()
{
var result = Json(new
{
when = DateTime.UtcNow,
});
result.StatusCode = (int)HttpStatusCode.OK;
return result;
}
In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.
Future voters, consider the date of writing when you vote. As of today, this works on my machine.
™ You will probably want more error handling and logging on your implementation.
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
Here's a code to Get, Set and Delete Cookie in JavaScript.
function getCookie(name) {_x000D_
name = name + "=";_x000D_
var cookies = document.cookie.split(';');_x000D_
for(var i = 0; i <cookies.length; i++) {_x000D_
var cookie = cookies[i];_x000D_
while (cookie.charAt(0)==' ') {_x000D_
cookie = cookie.substring(1);_x000D_
}_x000D_
if (cookie.indexOf(name) == 0) {_x000D_
return cookie.substring(name.length,cookie.length);_x000D_
}_x000D_
}_x000D_
return "";_x000D_
}_x000D_
_x000D_
function setCookie(name, value, expirydays) {_x000D_
var d = new Date();_x000D_
d.setTime(d.getTime() + (expirydays*24*60*60*1000));_x000D_
var expires = "expires="+ d.toUTCString();_x000D_
document.cookie = name + "=" + value + "; " + expires;_x000D_
}_x000D_
_x000D_
function deleteCookie(name){_x000D_
setCookie(name,"",-1);_x000D_
}
_x000D_
Source: http://mycodingtricks.com/snippets/javascript/javascript-cookies/
readChar doesn't have much flexibility so I combined your solutions (readLines and paste).
I have also added a space between each line:
con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
Addressing Vicky Ronnen's head up, considering the following code:
function use_global
{
eval "$1='changed using a global var'"
}
function capture_output
{
echo "always changed"
}
function test_inside_a_func
{
local _myvar='local starting value'
echo "3. $_myvar"
use_global '_myvar'
echo "4. $_myvar"
_myvar=$( capture_output )
echo "5. $_myvar"
}
function only_difference
{
local _myvar='local starting value'
echo "7. $_myvar"
local use_global '_myvar'
echo "8. $_myvar"
local _myvar=$( capture_output )
echo "9. $_myvar"
}
declare myvar='global starting value'
echo "0. $myvar"
use_global 'myvar'
echo "1. $myvar"
myvar=$( capture_output )
echo "2. $myvar"
test_inside_a_func
echo "6. $_myvar" # this was local inside the above function
only_difference
will give
0. global starting value
1. changed using a global var
2. always changed
3. local starting value
4. changed using a global var
5. always changed
6.
7. local starting value
8. local starting value
9. always changed
Maybe the normal scenario is to use the syntax used in the test_inside_a_func
function, thus you can use both methods in the majority of cases, although capturing the output is the safer method always working in any situation, mimicking the returning value from a function that you can find in other languages, as Vicky Ronnen
correctly pointed out.
If you don't want to use Metadata you can use a [UIHint("PeriodType")]
attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
_x000D_
See a working sample in this JSFiddle.
Try:
myLayout.setBackgroundColor(Color.parseColor("#636161"));
If your MySQL server runs on default settings, you don't need to specify that.
Default MySQL port is 3306.
[updated to show mysql_error() usage]
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Error connecting to mysql: '.mysql_error());
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.
Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.
byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);
If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"
Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail.
You should do URLEncoding and then pass in the token, it will work.
Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor
The -jar
option only works if the JAR file is an executable JAR file, which means it must have a manifest file with a Main-Class
attribute in it.
If it's not an executable JAR, then you'll need to run the program with something like:
java -cp app.jar com.somepackage.SomeClass
where com.somepackage.SomeClass
is the class that contains the main
method to run the program.
using python this is what I ended up with
import os
os.popen(' '.join([
self._ghostscriptPath + 'gswin32c.exe',
'-q',
'-dNOPAUSE',
'-dBATCH',
'-r300',
'-sDEVICE=tiff12nc',
'-sPAPERSIZE=a4',
'-sOutputFile=%s %s' % (tifDest, pdfSource),
]))
I really like cdmckay's answer, but it does not really look good to check the size in a real time: it is just too slow (2 seconds for me). This is the improved version, which is way faster and more exact, also with an option to choose how big the error can be (default 250,000
, the smaller error is - the longer the calculation is):
function getLocalStorageMaxSize(error) {
if (localStorage) {
var max = 10 * 1024 * 1024,
i = 64,
string1024 = '',
string = '',
// generate a random key
testKey = 'size-test-' + Math.random().toString(),
minimalFound = 0,
error = error || 25e4;
// fill a string with 1024 symbols / bytes
while (i--) string1024 += 1e16;
i = max / 1024;
// fill a string with 'max' amount of symbols / bytes
while (i--) string += string1024;
i = max;
// binary search implementation
while (i > 1) {
try {
localStorage.setItem(testKey, string.substr(0, i));
localStorage.removeItem(testKey);
if (minimalFound < i - error) {
minimalFound = i;
i = i * 1.5;
}
else break;
} catch (e) {
localStorage.removeItem(testKey);
i = minimalFound + (i - minimalFound) / 2;
}
}
return minimalFound;
}
}
To test:
console.log(getLocalStorageMaxSize()); // takes .3s
console.log(getLocalStorageMaxSize(.1)); // takes 2s, but way more exact
This works dramatically faster for the standard error; also it can be much more exact when necessary.
Currently I Use following code :
Bitmap bMap = ThumbnailUtils.createVideoThumbnail(file.getAbsolutePath(), MediaStore.Video.Thumbnails.MICRO_KIND);
But I found better solution with Glide library with following code ( It also cache your image and have better performance than previous approach )
Glide.with(context)
.load(uri)
.placeholder(R.drawable.ic_video_place_holder)
.into(imageView);
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
If you're developing, and you're developing with a Windows machine, simply add localhost
as a Trusted Site.
And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...
I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...
Update: If you are using CLion 2020.2, then it already supports Makefiles. If you are using an older version, read on.
Even though currently only CMake is supported, you can instruct CMake to call make
with your custom Makefile
. Edit your CMakeLists.txt
adding one of these two commands:
When you tell CLion
to run your program, it will try to find an executable with the same name of the target in the directory pointed by PROJECT_BINARY_DIR
. So as long as your make
generates the file where CLion
expects, there will be no problem.
Here is a working example:
CLion
to pass its $(PROJECT_BINARY_DIR) to make
This is the sample CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8.4)
project(mytest)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_custom_target(mytest COMMAND make -C ${mytest_SOURCE_DIR}
CLION_EXE_DIR=${PROJECT_BINARY_DIR})
CLion's
directoryThis is the sample Makefile
:
all:
echo Compiling $(CLION_EXE_DIR)/$@ ...
g++ mytest.cpp -o $(CLION_EXE_DIR)/mytest
That is all, you may also want to change your program's working directory so it executes as it is when you run make from inside your directory. For this edit: Run -> Edit Configurations ... -> mytest -> Working directory
For the first ten multiples of 5, say
>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
The answer given by FelixFett worked for me. To reiterate:
<meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" />
I have it as the first 'meta' tag in my code. I added 10 and 11 as those are versions that are published now for Internet Explorer.
I would've just commented on his answer but I do not have a high enough reputation...
One more answer:
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';_x000D_
_x000D_
obj = Object.keys(j).length;_x000D_
console.log(obj)
_x000D_
Update January 2016
Really surprised no-one has suggested:
lsof -i :PORT_NUMBER
to get the basic information required. For instance, checking on port 1337:
lsof -i :1337
Other variations, depending on circumstances:
sudo lsof -i :1337
lsof -i tcp:1337
You can easily build on this to extract the PID itself. For example:
lsof -t -i :1337
which is also equivalent (in result) to this command:
lsof -i :1337 | awk '{ print $2; }' | head -n 2 | grep -v PID
Quick illustration:
For completeness, because frequently used together:
To kill the PID:
kill -9 <PID>
# kill -9 60401
or as a one liner:
kill -9 $(lsof -t -i :1337)
Just to add to this thread - if you are moving an existing item you will need to use clone
and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).
Example:
$("#content ul").append($('.existing_li').clone(true));
Open res -> values -> styles.xml
and to your <style>
add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>
. Example:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@drawable/background</item>
</style>
</resources>
There is a <item name ="android:colorBackground">@color/black</item>
also, that will affect not only your main window background but all the component in your app. Read about customize theme here.
If you want version specific styles:
If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:
res/values/styles.xml # themes for all versions res/values-v21/styles.xml # themes for API level 21+ only
Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.
change_column_default :employees, :foreign, false
In Typescript, my issue was I didn't close the websocket connection after receiving a message.
WebSocket.on("message", (data) => {
receivedMessage = true;
doSomething(data);
localSocket.close(); //This close the connection, allowing
});
trim off everything after the last instance of ":"
cat fileListingPathsAndFiles.txt | grep -o '^.*:'
and if you wanted to drop that last ":"
cat file.txt | grep -o '^.*:' | sed 's/:$//'
@kp123: you'd want to replace :
with /
(where the sed colon should be \/
)
Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS
option, because that controls comparing to NULL with the =
and <>
operators. IS [NOT] NULL
works whether ANSI_NULLS
is ON
or OFF
.
I've also tried this against SQL Server 2005 with isql
, because ANSI_NULLS
defaults to OFF
when using DB-Library.
I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.
netstat -ano
There will be plenty of processes using various ports. So to get only port we need use findstr
like below (here I use port 80)
netstat -ano | findstr 80
this will gave you result like this
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 7964
Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill
command for that.
taskkill /PID 7964 /F
Run your server again. This time it will be able to run. This can uses for Mysql server too.
If you are trying to do something very similar: a is not None
, the same issue comes up. That is, Numpy complains that one must use a.any
or a.all
.
A workaround is to do:
if not (a is None):
pass
Not too pretty, but it does the job.
Using anytime package:
library(anytime)
anydate("2009-01")
# [1] "2009-01-01"
My understanding is that the underscore is technically valid. Check out:
https://developer.mozilla.org/en/underscores_in_class_and_id_names
"...errata to the specification published in early 2001 made underscores legal for the first time."
The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.
Follow this:
Create a bin
folder in any directory(to be used in step 3).
Download winutils.exe and place it in the bin directory.
Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");
in your code.
import java.util.HashMap;
public class SmallestHighestRepeatedNumber { static int arr[] = { 9, 4, 5, 9, 2, 9, 1, 2, 8, 1, 1, 7, 7 };
public static void main(String[] args) {
int mode = mode(arr);
System.out.println(mode);
}
public static int mode(int[] array) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
int max = 1;
int temp = 0;
for (int i = 0; i < array.length; i++) {
if (hm.get(array[i]) != null) {
int count = hm.get(array[i]);
count++;
hm.put(array[i], count);
if (count > max || temp > array[i] && count == max) {
temp = array[i];
max = count;
}
} else
hm.put(array[i], 1);
}
return temp;
}
}
No command
sbt
found
It's saying that sbt
is not on your path. Try to run ./sbt
from ~/bin/sbt/bin
or wherever the sbt
executable is to verify that it runs correctly. Also check that you have execute permissions on the sbt
executable. If this works , then add ~/bin/sbt/bin
to your path and sbt
should run from anywhere.
See this question about adding a directory to your path.
To verify the path is set correctly use the which
command on LINUX. The output will look something like this:
$ which sbt
/usr/bin/sbt
Lastly, to verify sbt
is working try running sbt -help
or likewise. The output with -help will look something like this:
$ sbt -help
Usage: sbt [options]
-h | -help print this message
...
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL.createObjectURL(blob) to convert the Blob into a URL that you pass to img.src.
var data = '424D5E070000000000003E00000028000000EF...';
// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);
for (var i = 0; i < data.length; i += 2) {
bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});
// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
You can try the complete example at: http://jsfiddle.net/nj82y73d/
Unfortunately none of these answers solved the specific problem I had.
Here's a simple solution without having to mess with bash
. In my case, it was getting gradle
to work (for Android Studio
).
Btw, These steps relate to OSX (Mountain Lion 10.8.5)
Run the following command:
sudo nano /etc/paths
(or sudo vim /etc/paths
for vim)
Open a new terminal window then type:
echo $PATH
You should see the new path appended to the end of the PATH
I got these details from this post:
http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q
I hope that can help someone else
This usually happens when something goes wrong in Android Studio's first launch (eg. system crash, connection loss or whatever).
To resolve this issue close Android Studio and delete the following directory's content, necessary files will be downloaded on IDE's next launch.
macOS: ~/.gradle/wrapper/dists
Linux: ~/.gradle/wrapper/dists
Windows: C:\Users\your-username\.gradle\wrapper\dists
While downloading Gradle manually works, I recommend letting Android Studio itself to do it.
Disable the firewall and try to connect.
If that works, then enable the firewall and
Windows Defender Firewall -> Advanced Settings -> Inbound Rules(Right Click) -> New Rules -> Port -> Allow Port 1433 (Public and Private) -> Add
Do the same for Outbound Rules.
Then Try again.
You should be able to &&
the conditions:
ng-disabled="condition1 && condition2"
you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
I wasted too much time on this, I find that the AVAST is the issue!!!
If you have AVAST installed in you system, you have to:
Go to
settings
tab -->troubleshooting
, then you should UNCHECK the "enable hardware-assisted virtualization
"
Restart your PC, the install the intelhaxm-android.exe if it is not installed. You can find it:
C:\Users\{YOURUSERNAME}\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager
I don't know the PDO syntax for it, but this seems pretty straight-forward:
$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
see also How to pause or stop an iframe youtube video when you leave a tab view or minimise your Ionic App
$scope.stopVideo = function() {
var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
iframe.postMessage('{"event":"command","func":"'+'stopVideo'+ '","args":""}', '*');
}
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
A)
Object* o;
o = new Object();
`` B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
correct typo of
struct xyz a;
to
struct xyx a;
Better you can try typedef, easy to b
from datetime import datetime
date = datetime.today().date()
print(date)
The lambda:
() -> { System.out.println("Do nothing!"); };
actually represents an implementation for an interface like:
public interface Something {
void action();
}
which is completely different than the one you've defined. That's why you get an error.
Since you can't extend your @FunctionalInterface
, nor introduce a brand new one, then I think you don't have much options. You can use the Optional<T>
interfaces to denote that some of the values (return type or method parameter) is missing, though. However, this won't make the lambda body simpler.
Here it is: http://jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
html
<input id="myinputfield" value="This is some text" type="button">?
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});?
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
There is also a constructor overload for List that will work... But I guess this would required a strong typed array.
//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);
... for Array class
var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
container
class has 15px left & right padding, so if you want to remove this padding, use following, because row
class has -15px left & right margin.
<div class="container">
<div class="row">
<img class='img-responsive' src="#" alt="" />
</div>
</div>
I used that and it worked Perfectly :)
UIView* footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 500)];
[footerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"ProductCellBackground.png"]]];
self.tableView.tableFooterView = footerView;
[self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
[self.tableView setContentInset:(UIEdgeInsetsMake(0, 0, -500, 0))];
I've got this solution.
Get the id of the commit where the file was deleted using one of the ways below.
git log --grep=*word*
git log -Sword
git log | grep --context=5 *word*
git log --stat | grep --context=5 *word*
# recommended if you hardly
remember anythingYou should get something like:
commit bfe68bd117e1091c96d2976c99b3bcc8310bebe7 Author: Alexander Orlov Date: Thu May 12 23:44:27 2011 +0200
replaced deprecated GWT class - gwtI18nKeySync.sh, an outdated (?, replaced by a Maven goal) I18n generation script
commit 3ea4e3af253ac6fd1691ff6bb89c964f54802302 Author: Alexander Orlov Date: Thu May 12 22:10:22 2011 +0200
3. Now using the commit id bfe68bd117e1091c96d2976c99b3bcc8310bebe7 do:
git checkout bfe68bd117e1091c96d2976c99b3bcc8310bebe7^1 yourDeletedFile.java
As the commit id references the commit where the file was already deleted you need to reference the commit just before bfe68b which you can do by appending ^1
. This means: give me the commit just before bfe68b.
Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)
Here is my solution to the problem, a bit late perhaps. But it could maybe help others:
// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, ''); // ^ means starting, meaning only match the first hash
if (hash) {
$('.nav-tabs a[href="#' + hash + '"]').tab('show');
}
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
})
The problem with the new version of QuickText seems to be that it is set to react to the TAB key. Previously it was set to use CTRL-ENTER. If you change the key combination in the shortcut mapper then your TAB key should start working again, and QuickText should also work (with whatever new key you've assigned).
+1 to above answers. I use following config
log_line_prefix = '%t %c %u ' # time sessionid user
log_statement = 'all'
One of the things to also keep in mind is that when you have Visual Studio 2010 SP1 installed some C++ compilers and libraries may have been removed. There's been an update made available by Microsoft to make sure those are brought back to your system.
Install this update to restore the Visual C++ compilers and libraries that may have been removed when Visual Studio 2010 Service Pack 1 (SP1) was installed. The compilers and libraries are part of the Microsoft Windows Software Development Kit for Windows 7 and the .NET Framework 4 (later referred to as the Windows SDK 7.1).
Also, when you read the VS2010 SP1 README you'll also notice that some notes have been made in regards to the Windows 7 SDK (See section 2.2.1) installation. It may be that one of these conditions may apply to you and therefore may need to uncheck the C++ compiler-checkbox as the SDK installer will attempt to install an older version of compilers ÓR you may need to uninstall VS2010 SP1 and re-run the SDK 7.1 installation, repair or modification.
Condition 1: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 SP1 has been installed, the error may be encountered and some selected components may not be installed.
Workaround: Clear the Visual C++ Compilers checkbox before you run the Windows SDK 7.1 installation, repair, or modification.
Condition 2: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 has been installed but Visual Studio 2010 SP1 has not been uninstalled, the error may be encountered.
Workaround: Uninstall Visual Studio 2010 SP1 and then rerun the Windows SDK 7.1 installation, repair, or modification.
However, even then I found that I still needed to uninstall any existing Visual C++ 2010 redistributables, as has been suggested by mgrandi.
Steps to install curl in windows
Install cURL on Windows
There are 4 steps to follow to get cURL installed on Windows.
Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate
Step One: Install Visual C++ 2008 Redistributables
From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)
Step Two: Install Win(32/64) OpenSSL v1.0.0k Light
From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light
Step Three: Install cURL
Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html
Copy curl.exe to C:\Windows\System32
Step Four: Install Recent Certificates
Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt
If you have already installed curl
or after doing the above steps, add the directory where it's installed to the windows path:
1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt
Add
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Method
String getUUID(){
TelephonyManager teleManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
String tmSerial = teleManager.getSimSerialNumber();
String tmDeviceId = teleManager.getDeviceId();
String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
if (tmSerial == null) tmSerial = "1";
if (tmDeviceId== null) tmDeviceId = "1";
if (androidId == null) androidId = "1";
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDeviceId.hashCode() << 32) | tmSerial.hashCode());
String uniqueId = deviceUuid.toString();
return uniqueId;
}
go to windows>preferences>Java>Editor>Syntax Coloring go all the way down and click on Restore Defaults & Apply and Close
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
I had this problem and it was because the panel was outside of the [data-role="page"] element.
As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:
You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.
I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it
Edit: I just did a quick test with this:
<a href="test.html" style="{color: blue; background: white}
:visited {color: green}
:hover {background: yellow}
:visited:hover {color: purple}">Test</a>
And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:
(X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C)
, where ...
means "0 or more different values(B,) dot (B, C) -> (C,)
(A, B) dot (B,) -> (A,)
(B,) dot (B,) -> ()
Your problem is that you are using np.matrix
, which is totally unnecessary in your code - the main purpose of np.matrix
is to translate a * b
into np.dot(a, b)
. As a general rule, np.matrix
is probably not a good choice.
Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.
This is how it works:
sudo raspi-config
in the Raspberry Pi command lineNext thing you can set time using this command
sudo date -s "Mon Aug 12 20:14:11 UTC 2014"
More about data and time
man date
When Pi is connected to computer should have to manually set data and time
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
If you really want to kill a process immediately, you send it a KILL signal instead of a TERM signal (the latter a request to stop, the first will take effect immediately without any cleanup). It is easy to do:
kill -KILL <pid>
Be aware however that depending on the program you are stopping, its state may get badly corrupted when doing so. You normally only want to send a KILL signal when normal termination does not work. I'm wondering what the underlying problem is that you try to solve and whether killing is the right solution.
You could try
lsb_release -a
which works on at least Debian and Ubuntu (and since it's LSB, it should surely be on most of the other mainstream distros at least). http://rpmfind.net/linux/RPM/sourceforge/l/ls/lsb/lsb_release-1.0-1.i386.html suggests it's been around quite a while.
For my scheduler, I am using it to fire at 6 am every day and my cron notation is:
0 0 6 * * *
If you want 1:01:am then set it to
0 1 1 * * *
Complete code for the scheduler
@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
//complete scheduled work
}
** VERY IMPORTANT
To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):
@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
//complete scheduled work
}
You can find the complete time zone values from here.
Note: My Spring framework version is: 4.0.7.RELEASE
Add XML comments to the publicly visible types and members of course :)
///<Summary>
/// Gets the answer
///</Summary>
public int MyMethod()
{
return 42;
}
You need these <summary>
type comments on all members - these also show up in the intellisense popup menu.
The reason you get this warning is because you've set your project to output documentation xml file (in the project settings). This is useful for class libraries (.dll assemblies) which means users of your .dll are getting intellisense documentation for your API right there in visual studio.
I recommend you get yourself a copy of the GhostDoc Visual Studio AddIn.. Makes documenting much easier.
This code work for me.
# ----------port 80----------
RewriteEngine on
# redirect http non-www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
# redirect http www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
# ----------port 443----------
RewriteEngine on
# redirect https non-www to https www
RewriteCond %{SERVER_NAME} !^www\.(.*)$ [NC]
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
I think what he is trying to say is to use the
getContentPane().setBackground(Color.the_Color_you_want_here)
but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)
Eg:
jPanel.setbackground(Color.BLUE)
SELECT CONVERT(DATE,DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)) AS FirstDayOfPrevMonth
SELECT CONVERT(DATE,DATEADD(MS, -3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) , 0))) AS LastDayOfPrevMonth
The data dictionary table DBA_SYNONYMS
has information about all the synonyms in a database. So you can run the query
SELECT table_owner, table_name, db_link
FROM dba_synonyms
WHERE owner = 'PUBLIC'
AND synonym_name = <<synonym name>>
to see what the public synonym currently points at.
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.
In order to extract all of the files contained inside of a zip file in this API, you'd do this:
In Java 8:
private void extractAll(URI fromZip, Path toDirectory) throws IOException{
FileSystems.newFileSystem(fromZip, Collections.emptyMap())
.getRootDirectories()
.forEach(root -> {
// in a full implementation, you'd have to
// handle directories
Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
});
}
In java 7:
private void extractAll(URI fromZip, Path toDirectory) throws IOException{
FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());
for(Path root : zipFs.getRootDirectories()) {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// You can do anything you want with the path here
Files.copy(file, toDirectory);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// In a full implementation, you'd need to create each
// sub-directory of the destination directory before
// copying files into it
return super.preVisitDirectory(dir, attrs);
}
});
}
}
I have users who have not been completing all required data.
<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
<cfset unloadCheck=1>
$("#myInput").change(function(){
verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
});
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
verify();
window.onbeforeunload = confirmExit;
function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>
While this question is old, the answers aren't proper. Context menus have their own events on DataGridView. There is an event for row context menu and cell context menu.
The reason for which these answers aren't proper is they do not account for different operation schemes. Accessibility options, remote connections, or Metro/Mono/Web/WPF porting might not work and keyboard shortcuts will down right fail (Shift+F10 or Context Menu key).
Cell selection on right mouse click has to be handled manually. Showing the context menu does not need to be handled as this is handled by the UI.
This completely mimics the approach used by Microsoft Excel. If a cell is part of a selected range, the cell selection doesn't change and neither does CurrentCell
. If it isn't, the old range is cleared and the cell is selected and becomes CurrentCell
.
If you are unclear on this, CurrentCell
is where the keyboard has focus when you press the arrow keys. Selected
is whether it is part of SelectedCells
. The context menu will show on right click as handled by the UI.
private void dgvAccount_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == System.Windows.Forms.MouseButtons.Right)
{
DataGridViewCell c = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
if (!c.Selected)
{
c.DataGridView.ClearSelection();
c.DataGridView.CurrentCell = c;
c.Selected = true;
}
}
}
Keyboard shortcuts do not show the context menu by default, so we have to add them in.
private void dgvAccount_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.F10 && e.Shift) || e.KeyCode == Keys.Apps)
{
e.SuppressKeyPress = true;
DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
if (currentCell != null)
{
ContextMenuStrip cms = currentCell.ContextMenuStrip;
if (cms != null)
{
Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
Point p = new Point(r.X + r.Width, r.Y + r.Height);
cms.Show(currentCell.DataGridView, p);
}
}
}
}
I've reworked this code to work statically, so you can copy and paste them into any event.
The key is to use CellContextMenuStripNeeded
since this will give you the context menu.
Here's an example using CellContextMenuStripNeeded
where you can specify which context menu to show if you want to have different ones per row.
In this context MultiSelect
is True
and SelectionMode
is FullRowSelect
. This is just for the example and not a limitation.
private void dgvAccount_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.RowIndex == -1 || e.ColumnIndex == -1)
return;
bool isPayment = true;
bool isCharge = true;
foreach (DataGridViewRow row in dgv.SelectedRows)
{
if ((string)row.Cells["P/C"].Value == "C")
isPayment = false;
else if ((string)row.Cells["P/C"].Value == "P")
isCharge = false;
}
if (isPayment)
e.ContextMenuStrip = cmsAccountPayment;
else if (isCharge)
e.ContextMenuStrip = cmsAccountCharge;
}
private void cmsAccountPayment_Opening(object sender, CancelEventArgs e)
{
int itemCount = dgvAccount.SelectedRows.Count;
string voidPaymentText = "&Void Payment"; // to be localized
if (itemCount > 1)
voidPaymentText = "&Void Payments"; // to be localized
if (tsmiVoidPayment.Text != voidPaymentText) // avoid possible flicker
tsmiVoidPayment.Text = voidPaymentText;
}
private void cmsAccountCharge_Opening(object sender, CancelEventArgs e)
{
int itemCount = dgvAccount.SelectedRows.Count;
string deleteChargeText = "&Delete Charge"; //to be localized
if (itemCount > 1)
deleteChargeText = "&Delete Charge"; //to be localized
if (tsmiDeleteCharge.Text != deleteChargeText) // avoid possible flicker
tsmiDeleteCharge.Text = deleteChargeText;
}
private void tsmiVoidPayment_Click(object sender, EventArgs e)
{
int paymentCount = dgvAccount.SelectedRows.Count;
if (paymentCount == 0)
return;
bool voidPayments = false;
string confirmText = "Are you sure you would like to void this payment?"; // to be localized
if (paymentCount > 1)
confirmText = "Are you sure you would like to void these payments?"; // to be localized
voidPayments = (MessageBox.Show(
confirmText,
"Confirm", // to be localized
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2
) == DialogResult.Yes);
if (voidPayments)
{
// SQLTransaction Start
foreach (DataGridViewRow row in dgvAccount.SelectedRows)
{
//do Work
}
}
}
private void tsmiDeleteCharge_Click(object sender, EventArgs e)
{
int chargeCount = dgvAccount.SelectedRows.Count;
if (chargeCount == 0)
return;
bool deleteCharges = false;
string confirmText = "Are you sure you would like to delete this charge?"; // to be localized
if (chargeCount > 1)
confirmText = "Are you sure you would like to delete these charges?"; // to be localized
deleteCharges = (MessageBox.Show(
confirmText,
"Confirm", // to be localized
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2
) == DialogResult.Yes);
if (deleteCharges)
{
// SQLTransaction Start
foreach (DataGridViewRow row in dgvAccount.SelectedRows)
{
//do Work
}
}
}
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
We also ran into this error on a new Apache server build.
The fix in our case was to define a ServerAlias
in the httpd.conf
that corresponded to the host name that Java was trying to connect to. Our ServerName
was set to the internal host name. Our SSL cert was using the external host name, but that was not sufficient to avoid the warning.
To help debug, you can use this ssl command:
openssl s_client -servername <hostname> -connect <hostname>:443 -state
If there is a problem with that hostname, then it will print this message near the top of the output:
SSL3 alert read: warning:unrecognized name
I should also note that we did not get that error when using that command to connect to the internal host name, even though it did not match the SSL cert.
If all steps (in existing answers) dont work , Just close eclipse and again open eclipse .
You have the arguments in the wrong order:
git branch <branch-name> <commit>
and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)
If you want to check out the new branch as you create it:
git checkout -b <branch> <commit>
with the same behavior if you omit the commit argument.
If you want to search for documents that belong to a specific month, make sure to query like this:
// Anything greater than this month and less than the next month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 7, 1)}});
Avoid quering like below as much as possible.
// This may not find document with date as the last date of the month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 6, 30)}});
// don't do this too
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lte: new Date(2015, 6, 30)}});