I'll be brief but deadly. :) install -d will not work for you. It's simple. Try
$ npm install -g express
In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.
Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.
:-) Sunday | 0 -> Sun
|
Monday | 1 -> Mon
Tuesday | 2 -> Tue
Wednesday | 3 -> Wed
Thursday | 4 -> Thu
Friday | 5 -> Fri
Saturday | 6 -> Sat
|
:-) Sunday | 7 -> Sun
As you can see above, and as said before, the numbers 0
and 7
are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.
Examples of Number or Abbreviation Use
15 09 * * 5,6,0 command
15 09 * * 5,6,7 command
15 09 * * 5-7 command
15 09 * * Fri,Sat,Sun command
The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.
In Detail
Having two numbers 0
and 7
for Sunday can be useful for writing weekday ranges starting with 0
or ending with 7
. So you can write ranges starting with Sunday or ending with it, like 0-2
or 5-7
for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.
Use 'raw_input' for input from a console/terminal.
if you just want a command line argument like a file name or something e.g.
$ python my_prog.py file_name.txt
then you can use sys.argv...
import sys
print sys.argv
sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"
If you want to have full on command line options use the optparse module.
Pev
Check if it matches this regex:
'(\.pdf$|\.doc$|\.xls$)'
Note: if you extensions are not at the end of the url, remove the $
characters, but it does weaken it slightly
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
Very easy no need create class extends LocationListener 1- Variable
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;
2- onStartService()
@Override public void onStartService() {
addListenerLocation();
}
3- Method addListenerLocation()
private void addListenerLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(lastKnownLocation!=null){
currentLat = lastKnownLocation.getLatitude();
currentLon = lastKnownLocation.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}
4- onDestroy()
@Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(mLocationListener);
}
if not myList:
print "Nothing here"
Reading the documentation and studying what the fragment id is, it appears to simply be the stack index, so this works:
fragmentManager.popBackStackImmediate(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Zero (0
) is the the bottom of the stack, so popping up to it inclusive clears the stack.
CAVEAT: Although the above works in my program, I hesitate a bit because the FragmentManager documentation never actually states that the id is the stack index. It makes sense that it would be, and all my debug logs bare out that it is, but perhaps in some special circumstance it would not? Can any one confirm this one way or the other? If it is, then the above is the best solution. If not, this is the alternative:
while(fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStackImmediate(); }
The <ul>
is by default a block element, make it inline-block
instead:
.navigation-bar ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
vertical-align:top;
}
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
As suggested in official docker document also. Try running this:
sudo vi /etc/apt/sources.list
Then remove/comment any (deb [arch=amd64] https://download.docker.com/linux/ubuntu/ xenial stable
) such entry at the last lines of the file.
Then in terminal run this command:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu/ bionic stable"
sudo apt-get update
It worked in my case.
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
new Comparator<Integer> () {
public int compare(Integer a, Integer b) {
return b - a;
}
}
);
A Redirect can only happen if the first line in an HTTP message is "HTTP/1.x 3xx Redirect Reason
".
If you already called Response.Write()
or set some headers, it'll be too late for a redirect. You can try calling Response.Headers.Clear()
before the Redirect to see if that helps.
NOTE: HSSFDateUtil is deprecated
If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for
row.getCell(0).getDateCellValue()
directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()
UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).
You can use the if (HSSFDateUtil.isCellDateFormatted ..
code block directly in your switch case.
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getDateCellValue());
}
}
The output is
Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007
You mean InputBox? Just look in the Microsoft.VisualBasic namespace.
C# and VB.Net share a common library. If one language can use it, so can the other.
You can use the curl_error()
function to detect if there was some error. For example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $your_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true); // Required for HTTP error codes to be reported via our call to curl_error($ch)
//...
curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
// TODO - Handle cURL error accordingly
}
See the description of libcurl error codes here
For WPF:
YourButtonName.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:
EXEC msdb.dbo.sp_send_dbmail
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'
Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.
You can do the following during declaration:
String names[] = {"Ankit","Bohra","Xyz"};
And if you want to do this somewhere after declaration:
String names[];
names = new String[] {"Ankit","Bohra","Xyz"};
My approach is very similar to @Bineesh answer but with a more general approach.
You can declare the double array as follows:
var myDoubleArray = [[]];
And the storing and accessing the contents in the following manner:
var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;
myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;
console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],)
This will print the expected output
[ 9, 8 ] 9 123
python_test.py
import subprocess
a = subprocess.check_output("batch_1.bat")
print a
This gives output from batch file to be print on the python IDLE/running console. So in batch file you can echo the result in each step to debug the issue. This is also useful in automation when there is an error happening in the batch call, to understand and locate the error easily.(put "echo off" in batch file beginning to avoid printing everything)
batch_1.bat
echo off
echo "Hello World"
md newdir
echo "made new directory"
Copy servlet-api.jar from your tomcat server lib folder.
Paste it to WEB-INF > lib
folder
Error was solved!!!
If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:
INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;
If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.
You can build one with the HttpListener
class to listen for incoming requests and the HttpWebRequest
class to relay the requests.
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
You don't need to create an intermediate file. You can do
pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname
or
pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname
using psql
or pg_dump
to connect to a remote host.
With a big database or a slow connection, dumping a file and transfering the file compressed may be faster.
As Kornel said there is no need to dump to a intermediate file, if you want to work compressed you can use a compressed tunnel
pg_dump -C dbname | bzip2 | ssh remoteuser@remotehost "bunzip2 | psql dbname"
or
pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"
but this solution also requires to get a session in both ends.
Note: pg_dump
is for backing up and psql
is for restoring. So, the first command in this answer is to copy from local to remote and the second one is from remote to local. More -> https://www.postgresql.org/docs/9.6/app-pgdump.html
Add this inside your pages head tag (targeting the IE version you want):
<meta http-equiv="X-UA-Compatible" content="IE=8" />
Note, this will NOT change the fact that the browser says its in compatibility mode (called the browser mode), but the page will render in IE8 standards mode. If its STILL not rendering how you wish, its probably because you have javascript that is erroneously checking the I.E. version. See the following blog post to determine which property you should be keying off of because even if you set the meta X-UA-Compatible tag, the user agent string will still say MSIE 7.0.
In my case, for the fix I had to add a check for IE7 Compatibility mode. I did so using a simple javascript code:
//IE8 and later will have the word 'trident' in its user agent string.
if (navigator.userAgent.indexOf("Trident")>-1) { //do something }
This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.
In practice, most fields have simple getters and setters. A possible solution would look like this:
public property String foo;
a->Foo = b->Foo;
Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller
Math functions are faster, but always returns not native expected values. Easiest way that i found is
(3.2+'').replace(/^[-\d]+\./, '')
Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:
For example:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.
Both hosts support https
as well as http
, so change the protocol as you see fit (or use a protocol relative URI)
See also: https://developers.google.com/speed/libraries/devguide
That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all;
to your .title rules to force a break.
#calendar_container > #events_container > .event_block > .title {
width:400px;
font-size:12px;
word-break:break-all;
}
Add position:fixed
. Then the cover is fixed over the whole screen, also when you scroll.
And add maybe also margin: 0; padding:0;
so it wont have some space's around the cover.
#dimScreen
{
position:fixed;
padding:0;
margin:0;
top:0;
left:0;
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
}
And if it shouldn't stick on the screen fixed, use position:absolute;
CSS Tricks have also an interesting article about fullscreen property.
Edit:
Just came across this answer, so I wanted to add some additional things.
Like Daniel Allen Langdon mentioned in the comment, add top:0; left:0;
to be sure, the cover sticks on the very top and left of the screen.
If you some elements are at the top of the cover (so it doesn't cover everything), then add z-index
. The higher the number, the more levels it covers.
For perfomance:
$('#example').children().last()
or if you want a last children with a certain class as commented above.
$('#example').children('.test').last()
or a specific child element with a specific class
$('#example').children('li.test').last()
Try the $.prepend()
function.
$("#parent-div").prepend("<div class='child-div'>some text</div>");
var i = 0;_x000D_
$(document).ready(function () {_x000D_
$('.add').on('click', function (event) {_x000D_
var html = "<div class='child-div'>some text " + i++ + "</div>";_x000D_
$("#parent-div").prepend(html);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="parent-div">_x000D_
<div>Hello World</div>_x000D_
</div>_x000D_
<input type="button" value="add" class="add" />
_x000D_
This is flask.jsonify()
def jsonify(*args, **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
The json
module used is either simplejson
or json
in that order. current_app
is a reference to the Flask()
object i.e. your application. response_class()
is a reference to the Response()
class.
I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.
I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?
Taking one of the provided answers as an example:
result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I need to worry about the array being null, now it becomes this:
result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I want a comma-delimited string, now it becomes this:
result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());
This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.
Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:
public static string ToStringLinqy<T>(this T[] array, string delimiter)
{
// edit: let's replace this with a "better" version using a StringBuilder
//return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
}
But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:
public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
{
if (array != null)
{
// edit: replaced my previous implementation to use StringBuilder
if (array.Length > 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
builder.Append(delimiter);
builder.Append(array[i]);
}
return builder.ToString()
}
else
{
return string.Empty;
}
}
else
{
return null;
}
}
And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):
public static string ToString<T>(this T[] array, string delimiter)
{
if (array != null)
{
// determine if the length of the array is greater than the performance threshold for using a stringbuilder
// 10 is just an arbitrary threshold value I've chosen
if (array.Length < 10)
{
// assumption is that for arrays of less than 10 elements
// this code would be more efficient than a StringBuilder.
// Note: this is a crazy/pointless micro-optimization. Don't do this.
string[] values = new string[array.Length];
for (int i = 0; i < values.Length; i++)
values[i] = array[i].ToString();
return string.Join(delimiter, values);
}
else
{
// for arrays of length 10 or longer, use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
sb.Append(delimiter);
sb.Append(array[i]);
}
return sb.ToString();
}
}
else
{
return null;
}
}
For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.
That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:
// convert an enumeration of one type into an enumeration of another type
public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
{
foreach (TIn value in input)
{
yield return conversion(value);
}
}
// concatenate the strings in an enumeration separated by the specified delimiter
public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
{
IEnumerator<T> enumerator = input.GetEnumerator();
if (enumerator.MoveNext())
{
StringBuilder builder = new StringBuilder();
// start off with the first element
builder.Append(enumerator.Current);
// append the remaining elements separated by the delimiter
while (enumerator.MoveNext())
{
builder.Append(delimiter);
builder.Append(enumerator.Current);
}
return builder.ToString();
}
else
{
return string.Empty;
}
}
// concatenate all elements
public static string ToString<T>(this IEnumerable<T> input)
{
return ToString(input, string.Empty);
}
// concatenate all elements separated by a delimiter
public static string ToString<T>(this IEnumerable<T> input, string delimiter)
{
return input.Delimit(delimiter);
}
// concatenate all elements, each one left-padded to a minimum length
public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
{
return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
}
Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.
Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.
For this problem, I'd rather just write something like this in my application code:
int[] arr = { 0, 1, 2, 3, 0, 1 };
// 012301
result = arr.ToString<int>();
// comma-separated values
// 0,1,2,3,0,1
result = arr.ToString(",");
// left-padded to 2 digits
// 000102030001
result = arr.ToString(2, '0');
In JDK 7 you could use Files.walkFileTree()
and Files.deleteIfExists()
to delete a tree of files. (Sample: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)
In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.
In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DtCadastro)
</td>
<td style="width:50%">
@Html.DisplayFor(modelItem => item.DsLembrete)
</td>
<td>
@Html.DisplayFor(modelItem => item.DtLembrete)
</td>
<td>
@{
var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
}
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
<button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
</td>
<td class="text-right">
<button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
</td>
</tr>
}
do as coded:
@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}
and use it like this:
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.
Heredoc's are a great alternative to quoted strings because of increased readability and maintainability. You don't have to escape quotes and (good) IDEs or text editors will use the proper syntax highlighting.
A very common example: echoing out HTML from within PHP:
$html = <<<HTML
<div class='something'>
<ul class='mylist'>
<li>$something</li>
<li>$whatever</li>
<li>$testing123</li>
</ul>
</div>
HTML;
// Sometime later
echo $html;
It is easy to read and easy to maintain.
The alternative is echoing quoted strings, which end up containing escaped quotes and IDEs aren't going to highlight the syntax for that language, which leads to poor readability and more difficulty in maintenance.
Updated answer for Your Common Sense
Of course you wouldn't want to see an SQL query highlighted as HTML. To use other languages, simply change the language in the syntax:
$sql = <<<SQL
SELECT * FROM table
SQL;
The problem you have is that you're attempting to bind the "test" class to the event before there is anything with a "test" class in the DOM
. Although it may seem like this is all dynamic, what is really happening is JQuery
makes a pass over the DOM
and wires up the click event when the ready()
function fired, which happens before you created the "Click Me" in your button event.
By adding the "test" Click event to the "button" click handler it will wire it up after the correct element exists in the DOM
.
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("h2").html("<p class='test'>click me</p>")
$(".test").click(function(){
alert()
});
});
});
</script>
Using live()
(as others have pointed out) is another way to do this but I felt it was also a good idea to point out the minor error in your JS code. What you wrote wasn't wrong, it just needed to be correctly scoped. Grasping how the DOM
and JS works is one of the tricky things for many traditional developers to wrap their head around.
live()
is a cleaner way to handle this and in most cases is the correct way to go. It essentially is watching the DOM
and re-wiring things whenever the elements within it change.
You can also do this via curl, just you need a path to an image file and pass it to the function given below..
public static function getImageDataFromUrl($url)
{
$urlParts = pathinfo($url);
$extension = $urlParts['extension'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
return $base64;
}
As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:
var input = $.trim($("#spa").val());
if (input) {
// Do Stuff
}
You can also extract the logic out into functions, then by assigning a class and using the each()
method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.
So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test
, and use:
$(".test").each(function () {
$(this).keyup(function () {
$("#submit").prop("disabled", CheckInputs());
});
});
which would then call the following and return a boolean value to assign to the disabled
property:
function CheckInputs() {
var valid = false;
$(".test").each(function () {
if (valid) { return valid; }
valid = !$.trim($(this).val());
});
return valid;
}
You can see a working example of everything I've mentioned in this JSFiddle.
Seems there's a typo (missing colon) in the JSON dict provided by jro.
The correct syntax would be:
jdata = json.load('{"uri": "http:", "foo": "bar"}')
This cleared it up for me when playing with the code.
In my case (Linux) is alt+shift up/down
{ "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
{ "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },
Assign a new Image
object to your PictureBox
's Image
property. To load an Image
from a file, you may use the Image.FromFile
method. In your particular case, assuming the current directory is one under bin
, this should load the image bin/Pics/image1.jpg
, for example:
pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");
Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.
How about str.split()? Nothing to import.
import os
image_names = [f for f in os.listdir(path) if len(f.split('.jpg')) == 2]
Use style="?android:borderlessButtonStyle" in the XML file. It will show the Android default click effect.
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
style="?android:borderlessButtonStyle"
/>
Basically any file that is automatically regenerated.
A good test is to clone your repo and see if Android Studio is able to interpret and run your project immediately (generating what is missing).
If not, find what is missing, and make sure it isn't ignored, but added to the repo.
That being said, you can take example on existing .gitignore
files, like the Android one.
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# Eclipse project files
.classpath
.project
# Proguard folder generated by Eclipse
proguard/
# Intellij project files
*.iml
*.ipr
*.iws
.idea/
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
This may also be achieved using matplotlib.pyplot.quiver
, as noted in the linked answer;
plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
1) check if service declaration in manifest is nested in application tag
<application>
<service android:name="" />
</application>
2) check if your service.java
is in the same package or diff package as the activity
<application>
<!-- service.java exists in diff package -->
<service android:name="com.package.helper.service" />
</application>
<application>
<!-- service.java exists in same package -->
<service android:name=".service" />
</application>
I found out that re-installing Xampp as an administrator and running it as an Administrator worked.
This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below
@Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);
I know this question has been answered, but I would like to share an alternate solution:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareSubText = "WhatsApp - The Great Chat App";
String shareBodyText = "https://play.google.com/store/apps/details?id=com.whatsapp&hl=en";
shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubText);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(shareIntent, "Share With"));
My solution is to use Process.GetProcess()
for listing all the processes.
By filtering them to contain the processes I want, I can then run Process.Kill()
method to stop them:
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
Update:
In case if want to use async
approach with some useful recent methods from the C# 8
(Async Enumerables), then check this out:
const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
.Where(pr => pr.ProcessName == processName)
.ToAsyncEnumerable()
.ForEachAsync(p => p.Kill());
Note: using async
methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.
You can do it by using the td's index:
var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
No, you can't change file upload input's text. But there are some tricks to overlay an image over the button.
You can use
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
I had the same issue when switching from a dev branch to master branch. What I did was commit my changes and switch to the master branch. You might have uncommitted changes.
Try target="_top"
<a href="http://example.com" target="_top">
This link will open in same but parent window of iframe.
</a>
T(N) = T(N/2) + 1
T(N) = T(N/2) + 1 = (T(N/4) + 1)+ 1
...
T(N) = T(N/N) + (1 + 1 + 1 +... + 1) = 1 + logN (base 2 log) = 1 + logN
So the time complexity of binary search is O(logN)
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'
SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
Use below one. I have tested this with Windows form's Grid view cell.
Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;
Name of "Resource_Image", you can find from the project.
Under the project's name, you can find Properties
. Expand it. There you can see Resources.resx
file. Open it. Apply your file name as "Resource_Image".
What about using the following:
int number = input.nextInt();
if (number < 0) {
// negative
} else {
// it's a positive
}
Here, check out this function:
function seo_friendly_url($string){
$string = str_replace(array('[\', \']'), '', $string);
$string = preg_replace('/\[.*\]/U', '', $string);
$string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
$string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
return strtolower(trim($string, '-'));
}
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
try Parsing and Formatting
Take an example Parsing
String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n", input);
throw exc; // Rethrow the exception.
}
Formatting
ZoneId leavingZone = ...;
ZonedDateTime departure = ...;
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String out = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
The output for this example, which prints both the arrival and departure time, is as follows:
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo)
For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html
Here is a super simple way of doing it
row2dict = lambda r: dict(r.items())
you dont have to use open when you are using for loops.
declare
cursor cur_name is select * from emp;
begin
for cur_rec in cur_name Loop
dbms_output.put_line(cur_rec.ename);
end loop;
End ;
or
declare
cursor cur_name is select * from emp;
cur_rec emp%rowtype;
begin
Open cur_name;
Loop
Fetch cur_name into Cur_rec;
Exit when cur_name%notfound;
dbms_output.put_line(cur_rec.ename);
end loop;
Close cur_name;
End ;
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
Make sure you have installed 'make' tool through Cygwin's installer.
I had this problem on my Catalina OSX after I installed my Anaconda distribution as well.
This solution worked for me on macOS Catalina as of October 19, 2019
Step 1. Check if .bash_profile is available on your home folder, if not:
cd ~/
to go to your home folder (if you are not on your home folder)touch .bash_profile
to create your new file under the your home folderStep 2. Check if file .zshrc
is available on your home folder, if not:
Go to terminal and type nano ~/.zshrc
Type in the following line into the newly created .zshrc file: source ~/.bash_profile
Now to save the file in nano just hit ctrl
+X
.
It will prompt "Save modified buffer (ANSWERING "No" WILL DESTROY CHANGES)?". Just type in Y
Step 3. Check if .bash_profile and .zshrc files are created on your home folder. If yes, in terminal type in source ~/.zshrc
A few options:
filter(lambda x: len(x) > 0, list1) # Doesn't work with number types
filter(None, list1) # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)
sample session:
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>
Had the same problem....managed to get it to work after a little while.
Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables
http://www.wikihow.com/Install-FFmpeg-on-Windows
Hope this helps someone - even after a while after the question - good luck
I would like to say that you must always use jQuery latest or recent stable versions. However if you need to do some work with others versions then you can add that version and renamed the $
to some other name. For instance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>var $oldjQuery = $.noConflict(true);</script>
Look here if you write something using $
then you will get the latest version. But if you need to do anything with old then just use$oldjQuery
instead of $
.
Here is an example
$(function(){console.log($.fn.jquery)});
$oldjQuery (function(){console.log($oldjQuery.fn.jquery)})
You might have to use another batch file first to launch the second with admin rights.
In the first use
runas /noprofile /user:mymachine\administrator yourbatchfile.bat
Upon further reading, you must be able to type in the password at the prompt. You cannot pipe the password as this feature was locked down for security reasons.
You may have more luck with psexec.
"Reference-Style" Answer: This is an alternative answer to the one below with several different options shown. Uninstalling an MSI file from the command line without using msiexec.
The command you specify is correct: msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}
If you get "This action is only valid for products that are currently installed" you have used an unrecognized product or package code, and you must find the right one. Often this can be caused by using an erroneous package code instead of a product code to uninstall - a package code changes with every rebuild of an MSI file, and is the only guid you see when you view an msi file's property page. It should work for uninstall, provided you use the right one. No room for error. If you want to find the product code instead, you need to open the MSI. The product code is found in the Property table.
UPDATE, Jan 2018:
With all the registry redirects going on, I am not sure the below registry-based approach is a viable option anymore. I haven't checked properly because I now rely on the following approach using PowerShell: How can I find the product GUID of an installed MSI setup?
Also check this reference-style answer describing different ways to uninstall an MSI package and ways to determine what product version you have installed: Uninstalling an MSI file from the command line without using msiexec
Legacy, registry option:
You can also find the product code by perusing the registry from this base key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall . Press F3 and search for your product name. (If it's a 32-bit installer on a 64-bit machine, it might be under HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall instead).
Legacy, PowerShell option: (largely similar to the new, linked answer above)
Finally, you can find the product code by using PowerShell:
get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name
Similar post: WiX - Doing a major upgrade on a multi instance install (screenshot of how to find the product code in the MSI).
IntPtr GetIntPtr(Byte[] byteBuf)
{
IntPtr ptr = Marshal.AllocHGlobal(byteBuf.Length);
for (int i = 0; i < byteBuf.Length; i++)
{
Marshal.WriteByte(ptr, i, byteBuf[i]);
}
return ptr;
}
You need to set the height of html
to 100%
body {
background-image:url("../images/myImage.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
}
html {
height: 100%
}
I have two recommendation for you
-Drevision=2.0.1
in .mvn/maven.config
file. So basically you define your version only at one location.For anyone else who's looking for an answer in cases where you don't know the length of the packet prior.
Here's a simple solution that reads 4096 bytes at a time and stops when less than 4096 bytes were received. However, it will not work in cases where the total length of the packet received is exactly 4096 bytes - then it will call recv()
again and hang.
def recvall(sock):
data = b''
bufsize = 4096
while True:
packet = sock.recv(bufsize)
data += packet
if len(packet) < bufsize:
break
return data
Change it to:
<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.
The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:
<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>
Oh and just for completeness, you should really prefer classes to direct CSS styles.
var myTimer = setTimeout(..., 115000);
something.click(function () {
clearTimeout(myTimer);
myTimer = setTimeout(..., 115000);
});
Something along those lines!
This can also help to list procedure except the system procedures:
select * from sys.all_objects where type='p' and is_ms_shipped=0
Say util.R
produces a function foo()
. You can check if this function is available in the global environment and source the script if it isn't:
if(identical(length(ls(pattern = "^foo$")), 0))
source("util.R")
That will find anything with the name foo
. If you want to find a function, then (as mentioned by @Andrie) exists()
is helpful but needs to be told exactly what type of object to look for, e.g.
if(exists("foo", mode = "function"))
source("util.R")
Here is exists()
in action:
> exists("foo", mode = "function")
[1] FALSE
> foo <- function(x) x
> exists("foo", mode = "function")
[1] TRUE
> rm(foo)
> foo <- 1:10
> exists("foo", mode = "function")
[1] FALSE
Try This:
HTML:
<div class="customselect">
<select>
<option>2000</option>
<option>2001</option>
<option>2002</option>
</select>
</div>
CSS:
.customselect {
width: 70px;
overflow: hidden;
}
.customselect select {
width: 100px;
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
}
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
you can go to the XML file
then focus your mouse cursor into your button, text view or whatever you choose for your layout, then press Alt + Enter
to fix it, after that the error will be gone.it works for me.
I had the same problem in a RecyclerView list with switches, and solved it using @oguzhand answer, but with this code inside the checkedChangeListener:
if (buttonView.isPressed()) {
if (isChecked) {
group.setSelected(true);
} else {
group.setSelected(false);
}
}else{
if (isChecked) {
buttonView.setChecked(false);
} else {
buttonView.setChecked(true);
}
}
(Where 'group' is the entity I want to select/deselect)
You can always refresh the user's access token every time the user logs into your site through facebook. The offline access can't guarantee you get a life-long time access token, the access token changes whenever the user revoke you application access or the user changes his/her password.
Quoted from facebook http://developers.facebook.com/docs/authentication/
Note: If the application has not requested offline_access permission, the access token is time-bounded. Time-bounded access token also get invalidated when the user logs out of Facebook. If the application has obtained offline_access permission from the user, the access token does not have an expiry. However it gets invalidated whenever the user changes his/her password.
Assume you store the user's facebook uid and access token in a users table in your database,every time the user clicks on the "Login with facebook" button, you check the login statususing facebook Javascript API, and then examine the connection status from the response,if the user has connected to your site, you can then update the access token in the table.
A URL should be encoded when there are special characters located inside the URL. For example:
console.log(encodeURIComponent('?notEncoded=&+'));
_x000D_
We can observe in this example that all characters except the string notEncoded
are encoded with % signs. URL encoding is also known as percentage encoding because it escapes all special characters with a %. Then after this % sign every special character has a unique code
Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. In order to succesfully locate a resource on the web, it is necesarry to distinguish between when a character is meant as a part of string or part of the url structure.
JS offers a bunch of build in utility function which we can use to easily encode URL's. These are two convenient options:
encodeURIComponent()
: Takes a component of a URI as an argument and returns the encoded URI string.encodeURI()
: Takes a URI as an argument and returns the encoded URI string.Be aware of not passing in the whole URL (including scheme, e.g https://) into encodeURIComponent()
. This can actually transform it into a not functional URL. For example:
// for a whole URI don't use encodeURIComponent it will transform_x000D_
// the / characters and the URL won't fucntion properly_x000D_
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));_x000D_
_x000D_
// instead use encodeURI for whole URL's_x000D_
console.log(encodeURI("http://www.random.com/specials&char.html"));
_x000D_
We can observe f we put the whole URL in encodeURIComponent
that the foward slashes (/) are also converted to special characters. This will cause the URL to not function properly anymore.
Therefore (as the name implies) use:
encodeURIComponent
on a certain part of a URL which you want to encode.encodeURI
on a whole URL which you want to encode.You can try with ParseExact
method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
For me working solution is:
ON REMOTE:
git checkout -b some_tmp_name
ON LOCAL:
git push
ON REMOTE:
git checkout master
git branch -d some_tmp_name
But this is not the real solution it's just workaround.
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
Your keys may already be in PEM format, but just named with .crt or .key.
If the file's content begins with -----BEGIN
and you can read it in a text editor:
The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.
If the file is in binary:
For the server.crt, you would use
openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem
For server.key, use openssl rsa
in place of openssl x509
.
The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.
If this is for a Web server and you cannot specify loading a separate private and public key:
You may need to concatenate the two files. For this use:
cat server.crt server.key > server.includesprivatekey.pem
I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.
I read and read and read to figure out why I was getting a class not found error, it turns out the manifest.mf had an error in the line:
Main-Class: com.example.MainClass
I fixed the error by going to Project Properties dialog (right-click Project Files), then Run and Main Class and corrected whatever Netbeans decided to put here. Netbean inserted the project name instead of the class name. No idea why. Probably inebriated on muratina...
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
There's a whole bunch of things that can cause this. I'd read through these and try each of them
http://dev.mysql.com/doc/refman/5.1/en/gone-away.html
I've worked for several web hosting companies over the years and generally when I see this, it is the wait_timeout on the server end though this doesn't appear to be the case here.
If you find the solution, I hope you post it. I'd like to know.
This Code work for me :
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
For newer version of laravel:
composer create-project --prefer-dist laravel/laravel=5.5.* project_name
To exit from Python terminal, simply just do:
exit()
Please pay attention it's a function which called as most user mix it with exit without calling, but new Pyhton terminal show a message...
or as a shortcut, press:
Ctrl + D
on your keyboard...
The :: is known as method references. Lets say we want to call a calculatePrice method of class Purchase. Then we can write it as:
Purchase::calculatePrice
It can also be seen as short form of writing the lambda expression Because method references are converted into lambda expressions.
html, body {
height: 100%;
width: 100%;
}
html {
display: table;
margin: auto;
}
body {
padding-top: 50px;
display: table-cell;
}
div {
margin: auto;
}
This will center align objects and then also center align the items within them to center align multiple objects with different widths.
I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.
The concerns with cryptography in client-side (browser) javascript are detailed below. All but one of these concerns does not apply to the WebCrypto API, which is now reasonably well supported.
For an offline app, you must still design and implement a secure keystore.
Aside: If you are using Node.js, use the builtin crypto API.
I presume the primary concern is someone with physical access to the computer reading the localStorage
for your site, and you want cryptography to help prevent that access.
If someone has physical access you are also open to attacks other and worse than reading. These include (but are not limited to): keyloggers, offline script modification, local script injection, browser cache poisoning, and DNS redirects. Those attacks only work if the user uses the machine after it has been compromised. Nevertheless, physical access in such a scenario means you have bigger problems.
So keep in mind that the limited scenario where local crypto is valuable would be if the machine is stolen.
There are libraries that do implement the desired functionality, e.g. Stanford Javascript Crypto Library. There are inherent weaknesses, though (as referred to in the link from @ircmaxell's answer):
Each of these weaknesses corresponds with a category of cryptographic compromise. In other words, while you may have "crypto" by name, it will be well below the rigour one aspires to in practice.
All that being said, the actuarial assessment is not as trivial as "Javascript crypto is weak, do not use it". This is not an endorsement, strictly a caveat and it requires you to completely understand the exposure of the above weaknesses, the frequency and cost of the vectors you face, and your capacity for mitigation or insurance in the event of failure: Javascript crypto, in spite of its weaknesses, may reduce your exposure but only against thieves with limited technical capacity. However, you should presume Javascript crypto has no value against a determined and capable attacker who is targeting that information. Some would consider it misleading to call the data "encrypted" when so many weaknesses are known to be inherent to the implementation. In other words, you can marginally decrease your technical exposure but you increase your financial exposure from disclosure. Each situation is different, of course - and the analysis of reducing the technical exposure to financial exposure is non-trivial. Here is an illustrative analogy: Some banks require weak passwords, in spite of the inherent risk, because their exposure to losses from weak passwords is less than the end-user costs of supporting strong passwords.
If you read the last paragraph and thought "Some guy on the Internet named Brian says I can use Javascript crypto", do not use Javascript crypto.
For the use case described in the question it would seem to make more sense for users to encrypt their local partition or home directory and use a strong password. That type of security is generally well tested, widely trusted, and commonly available.
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
the provided solutions seem a little complex? this might help:
https://msdn.microsoft.com/en-us/library/ms174420.aspx
select
mystuff,
DATEPART ( year, MyDateColumn ) as yearnr,
DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
This could be done via CSS:
<style type="text/css">
@font-face {
font-family: "My Custom Font";
src: url(http://www.example.org/mycustomfont.ttf) format("truetype");
}
p.customfont {
font-family: "My Custom Font", Verdana, Tahoma;
}
</style>
<p class="customfont">Hello world!</p>
It is supported for all of the regular browsers if you use TrueType-Fonts (TTF), the Web Open Font Format (WOFF) or Embedded Opentype (EOT).
I found a faster way to solve the problem, at least on realistically large datasets using:
df.set_index(KEY).to_dict()[VALUE]
Proof on 50,000 rows:
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']
Output:
100 loops, best of 3: 7.04 ms per loop # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop # Jeff
100 loops, best of 3: 4.28 ms per loop # Kikohs (me)
Escaping works.
#!/bin/bash
FILES=(2011-09-04\ 21.43.02.jpg
2011-09-05\ 10.23.14.jpg
2011-09-09\ 12.31.16.jpg
2011-09-11\ 08.43.12.jpg)
echo ${FILES[0]}
echo ${FILES[1]}
echo ${FILES[2]}
echo ${FILES[3]}
Output:
$ ./test.sh
2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg
Quoting the strings also produces the same output.
If you can afford to tie yourself to just Lollipop and later, this seems to do the trick:
import android.transition.Slide;
import android.util.Log;
import android.view.Gravity;
.
.
.
f = new MyFragment();
f.setEnterTransition(new Slide(Gravity.END));
f.setExitTransition(new Slide(Gravity.START));
getFragmentManager()
.beginTransaction()
.replace(R.id.content, f, FRAG_TAG) // FRAG_TAG is the tag for your fragment
.commit();
Kotlin version:
f = MyFragment().apply {
enterTransition = Slide(Gravity.END)
exitTransition = Slide(Gravity.START)
}
fragmentManager
.beginTransaction()
.replace(R.id.content, f, FRAG_TAG) // FRAG_TAG is the tag for your fragment
.commit();
Hope this helps.
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
You're using integer division.
Try 7.0/10
instead.
With zero jQuery
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
.inv {
display: none;
}
</style>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>
Codepen
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
_x000D_
.inv {
display: none;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
</body>
</html>
_x000D_
Look at the fiddle here for a quick answer
data-ng-attr-title="{{d.age > 5 ? 'My age is greater than threshold': ''}}"
If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom
.
Java 6 & 7:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
Java 8 (even more secure):
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/
Use Ctrl+V to enter visual block mode
Move Up/Down to select the columns of text in the lines you want to comment.
Then hit Shift+i and type the text you want to insert.
Then hit Esc, wait 1 second and the inserted text will appear on every line
#created a sorting function to sort by length of elements of list
def sort_len(a):
num = len(a)
d = {}
i = 0
while i<num:
d[i] = len(a[i])
i += 1
b = list(d.values())
b.sort()
c = []
for i in b:
for j in range(num):
if j in list(d.keys()):
if d[j] == i:
c.append(a[j])
d.pop(j)
return c
InputStream is = new FileInputStream("c://filename");
return is;
import java.util.Collections;
List myList = new ArrayList();
String[] myArray = new String[] {"Java", "Util", "List"};
Collections.addAll(myList, myArray);
This is more a clarification than an answer! Yes, the clue is in the error message:
[hi: command not found
which shows you that your "hi" has been concatenated to the "[".
Unlike in more traditional programming languages, in Bash, "[" is a command just like the more obvious "ls", etc. - it's not treated specially just because it's a symbol, hence the "[" and the (substituted) "$s1" which are immediately next to each other in your question, are joined (as is correct for Bash), and it then tries to find a command in that position: [hi - which is unknown to Bash.
In C and some other languages, the "[" would be seen as a different "character class" and would be disjoint from the following "hi".
Hence you require a space after the opening "[".
As a more general solution you might want to check out the Microsoft Power Toy for XP that adds the "Open Command Window Here" option when you right-click: http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
In Vista and Windows 7, you'll get that option if you hold down shift and right-click (this is built in).
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");
breaking up the script keyword because VStudio / asp.net compiler doesn't like it
For completeness: If you are already using the Spring framework, the StringUtils provide the method
org.springframework.util.StringUtils.hasLength(String str)
Returns: true if the String is not null and has length
as well as the method
org.springframework.util.StringUtils.hasText(String str)
Returns: true if the String is not null, its length is greater than 0, and it does not contain whitespace only
GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.
Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.
SELECT DISTINCT e.Ename AS Employee,
m.mgr AS reports_to,
m.Ename AS manager
FROM Employees e, Employees m
WHERE e.mgr=m.EmpID;
In regards Jared's response, having Windows 2000 or better will not necessarily fix the issue at hand. Rob's response does work, however it is possible that this fix introduces security issues, as Windows updates will not be able to patch applications built as such.
In another post, Nick Guerrera suggests packaging the Visual C++ Runtime Redistributable with your applications, which installs quickly, and is independent of Visual Studio.
With little modification to @Hephaeastus 's code in one of the above comments, wrote the below method to list down folders and objects (files) in a given path. Works similar to s3 ls command.
from boto3 import session
def s3_ls(profile=None, bucket_name=None, folder_path=None):
folders=[]
files=[]
result=dict()
bucket_name = bucket_name
prefix= folder_path
session = boto3.Session(profile_name=profile)
s3_conn = session.client('s3')
s3_result = s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter = "/", Prefix=prefix)
if 'Contents' not in s3_result and 'CommonPrefixes' not in s3_result:
return []
if s3_result.get('CommonPrefixes'):
for folder in s3_result['CommonPrefixes']:
folders.append(folder.get('Prefix'))
if s3_result.get('Contents'):
for key in s3_result['Contents']:
files.append(key['Key'])
while s3_result['IsTruncated']:
continuation_key = s3_result['NextContinuationToken']
s3_result = s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter="/", ContinuationToken=continuation_key, Prefix=prefix)
if s3_result.get('CommonPrefixes'):
for folder in s3_result['CommonPrefixes']:
folders.append(folder.get('Prefix'))
if s3_result.get('Contents'):
for key in s3_result['Contents']:
files.append(key['Key'])
if folders:
result['folders']=sorted(folders)
if files:
result['files']=sorted(files)
return result
This lists down all objects / folders in a given path. Folder_path can be left as None by default and method will list the immediate contents of the root of the bucket.
If one really want to resize an array you could do something like this:
String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c]
arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]
If you're looking for where this is happening, in console you can use: document.querySelectorAll(" p * div ")
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
You can see the history with git-reflog (example here):
git reflog
In View
<select ng-model="boxmodel"><option ng-repeat="lst in list" value="{{lst.id}}">{{lst.name}}</option></select>
JS:
In side controller
$scope.boxModel = 600;
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
After I removed these three lines, the app worked fine, as expected.
Hope it helps!
If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in
extern "C" void foo();
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);
“tools:context” is one of the Design Attributes that can facilitate layout creation in XML in the development framework. This attribute is used to show the development framework what activity class is picked for implementing the layout. Using “tools:context”, Android Studio chooses the necessary theme for the preview automatically.
If you’d like to know more about some other attributes and useful tools for Android app development, take a look at this review: http://cases.azoft.com/4-must-know-tools-for-effective-android-development/
(For those who read all answers). My case was simply the fact that I created a SQL expression using the format Forms!Table!Control. That format is Ok within a query, but DAO doesn't recognize it. I'm surprised that nobody commented this.
This doesn't work:
Dim rs As DAO.Recordset, strSQL As String
strSQL = "SELECT * FROM Table1 WHERE Name = Forms!Table!Control;"
Set rs = CurrentDb.OpenRecordset(strSQL)
This is Ok:
Dim rs As DAO.Recordset, strSQL, val As String
val = Forms!Table!Control
strSQL = "SELECT * FROM Table1 WHERE Name = '" & val & "';"
Set rs = CurrentDb.OpenRecordset(strSQL)
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
I have found if the font face declarations are inside a media query IE (both edge and 11) won't load them; they need to be the first thing declared in the stylesheet and not wrapped in a media query
jQuery comes with the following options which could fulfil your need in this case:
append
is used to add an element at the end of the parent div
specified in the selector:
$('ul.tabs').append('<li>An element</li>');
prepend
is used to add an element at the top/start of the parent div
specified in the selector:
$('ul.tabs').prepend('<li>An element</li>');
insertAfter
lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:
$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>
insertBefore
will do the opposite of the above:
$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.
Here's a demo on jsbin.
.cut-text {
text-overflow: ellipsis;
overflow: hidden;
width: 160px;
height: 1.2em;
white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
Update npm 5:
As of npm 5.0.0, installed modules are added as a dependency by default, so the --save
option is no longer needed. The other save options still exist and are listed in the documentation for npm install
.
Original answer:
Before version 5, NPM simply installed a package under node_modules
by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the dependencies
section of your package.json
.
The --save
option instructed NPM to include the package inside of the dependencies
section of your package.json
automatically, thus saving you an additional step.
In addition, there are the complementary options --save-dev
and --save-optional
which save the package under devDependencies
and optionalDependencies
, respectively. This is useful when installing development-only packages, like grunt
or your testing library.
Arduino sketches are written in C++.
Here is a typical construct you'll encounter:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");
That's C++, not C.
Hence do yourself a favor and learn C++. There are plenty of books and online resources available.
try this
http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject
I just added the project of google services and added a reference in my project property->Android
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I think you want to remove the last five characters ('.', 'n', 'u', 'l', 'l'):
path = path.substring(0, path.length() - 5);
Note how you need to use the return value - strings are immutable, so substring
(and other methods) don't change the existing string - they return a reference to a new string with the appropriate data.
Or to be a bit safer:
if (path.endsWith(".null")) {
path = path.substring(0, path.length() - 5);
}
However, I would try to tackle the problem higher up. My guess is that you've only got the ".null" because some other code is doing something like this:
path = name + "." + extension;
where extension
is null. I would conditionalise that instead, so you never get the bad data in the first place.
(As noted in a question comment, you really should look through the String
API. It's one of the most commonly-used classes in Java, so there's no excuse for not being familiar with it.)
Simple changed is required:
Use
<th value={column} onClick={that.handleSort} >{column}</th>
instead of
<th value={column} onClick={that.handleSort} >{column}</th>
This can also be a cause for this[:) I solved my problem like this]
It may happen even if you are trying to insert a dataframe type column inside dataframe
you can try this
df['my_new']=pd.Series(my_new.values)
Log in to MySQL:
mysql -u root
Now create and grant
GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';
Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:
GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'
This is fine for junk data in development. Don't do this with anything you care about.
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
Assuming a Windows installation, do please refer to this:
http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php
- Uninstall all Oracle components using the Oracle Universal Installer (OUI).
- Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
- Delete any references to Oracle services left behind in the following part of the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora*
It should be pretty obvious which ones relate to Oracle.- Reboot your machine.
- Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
- Delete the "C:\Program Files\Oracle" directory.
- Empty the contents of your "C:\temp" directory.
- Empty your recycle bin.
Calling additional attention to some great comments that were left here:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE
key from the registry.%ORACLE_HOME%
.%PATH%
.This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.
Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.
(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)
It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.
Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));
.
See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.
i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());
You can use instanceof
.
instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
That means you can do something like this:
Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"
You'd have to check if the object is an instanceof boolean[]
, byte[]
, short[]
, char[]
, int[]
, long[]
, float[]
, double[]
, or Object[]
, if you want to detect all array types.
Also, an int[][]
is an instanceof Object[]
, so depending on how you want to handle nested arrays, it can get complicated.
For the toString
, java.util.Arrays
has a toString(int[])
and other overloads you can use. It also has deepToString(Object[])
for nested arrays.
public String toString(Object arr) {
if (arr instanceof int[]) {
return Arrays.toString((int[]) arr);
} else //...
}
It's going to be very repetitive (but even java.util.Arrays
is very repetitive), but that's the way it is in Java with arrays.
In a nutshell, sys.argv
is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0]
, and the second element (first argument, if there is one) is sys.argv[1]
, etc.
The test len(sys.argv) >= 2
simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.
Use component scanning as given below, if com.project.action.PasswordHintAction
is annotated with stereotype annotations
<context:component-scan base-package="com.project.action"/>
EDIT
I see your problem, in PasswordHintActionTest
you are autowiring PasswordHintAction
. But you did not create bean configuration for PasswordHintAction
to autowire. Add one of stereotype annotation(@Component, @Service, @Controller
) to PasswordHintAction
like
@Component
public class PasswordHintAction extends BaseAction {
private static final long serialVersionUID = -4037514607101222025L;
private String username;
or create xml configuration in applicationcontext.xml
like
<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />
Here's another implementation:
class DictObj(object):
def __init__(self, d):
self.__dict__ = d
def dict_to_obj(d):
if isinstance(d, (list, tuple)): return map(dict_to_obj, d)
elif not isinstance(d, dict): return d
return DictObj(dict((k, dict_to_obj(v)) for (k,v) in d.iteritems()))
[Edit] Missed bit about also handling dicts within lists, not just other dicts. Added fix.
Example query:
SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;
I think you need to push a revert commit. So pull
from github again, including the commit you want to revert, then use git revert
and push the result.
If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset
: git push origin :master
.
AWS EFS, EBS and S3. From Functional Standpoint, here is the difference
EFS:
Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security
Highly available, scalable service.
Running any application that has a high workload, requires scalable storage, and must produce output quickly.
It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.
Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.
Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.
EBS:
S3:
Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.
2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.
Fix:
I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".
After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.
C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
Volume in drive C is Windows
Volume Serial Number is 8EE6-5DD0
Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319
03/18/2010 08:23 PM 19,296 aspnet_regbrowsers.exe
03/18/2010 08:23 PM 36,696 aspnet_regiis.exe
03/18/2010 08:23 PM 102,232 aspnet_regsql.exe
3 File(s) 158,224 bytes
0 Dir(s) 34,836,508,672 bytes free
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.
HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.
Removing only decimal part can be done as follows:
number.replace(/(\.\d+)+/,'');
This would convert 13.6667px into 13px (leaving units px untouched).
Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2
class of burstable instances.
EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.
Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.
It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²
Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.
But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.
¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2
machines.
²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).
³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.
You can use LambdaEqualityComparer:
var distinctValues
= myCustomerList.Distinct(new LambdaEqualityComparer<OurType>((c1, c2) => c1.CustomerId == c2.CustomerId));
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
public LambdaEqualityComparer(Func<T, T, bool> equalsFunction)
{
_equalsFunction = equalsFunction;
}
public bool Equals(T x, T y)
{
return _equalsFunction(x, y);
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
private readonly Func<T, T, bool> _equalsFunction;
}
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
This is the way I got the solution. Simple and Sweet. Independent of Screen density:
export default class AwesomeProject extends Component {
constructor(props){
super(props);
this.state = {text: ""}
}
render() {
return (
<View
style={{
flex: 1,
backgroundColor: "#ececec",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}
>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 1"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 2"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<Button
onPress={onButtonPress}
title="Press Me"
accessibilityLabel="See an Information"
/>
</View>
</View>
);
}
}
Several options are available:
Call QueryDosDevice with a NULL lpDeviceName to list all DOS devices. Then use CreateFile and GetCommConfig with each device name in turn to figure out whether it's a serial port.
Call SetupDiGetClassDevs with a ClassGuid of GUID_DEVINTERFACE_COMPORT.
WMI is also available to C/C++ programs.
There's some conversation on the win32 newsgroup and a CodeProject, er, project.
It is because the framework requires that two objects that are the same must have the same hashcode. If you override the equals method to do a special comparison of two objects and the two objects are considered the same by the method, then the hash code of the two objects must also be the same. (Dictionaries and Hashtables rely on this principle).
Your best bets are probably going with one of the other lookup services (still screen-scraping), and checking whether they don't require CAPTCHAs.
The last appears the least likely to require a CAPTCHA at any point, but it's worth checking all three.
Use the menu item Settings>Preferences.
On the MISC tab of the resulting dialog, uncheck "Remember current session for next launch."
I went into wp-config/ and deleted the object-cache.php and advanced-cache.php and it worked fine for me.
if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple
https://www.npmjs.com/package/vue-shortkey
v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"
I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was
<?xmlversion="1.0"encoding="utf-8"?>
which was causing the error. When I removed that line, so that the stylesheet started with the line
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:text>From,To~</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
<xsl:value-of select="@DTS:From"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="@DTS:To"/>
<xsl:text>~</xsl:text>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.
Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.
Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:
ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
FOREIGN KEY ("parentId")
REFERENCES "Parent"(id)
ON DELETE CASCADE;
Most probably in your manage.py
the first line starts with !/usr/bin/python
which means you are using the system global python rather than the one in your virtual environment.
so replace
/usr/bin/python
with
~/projectpath/venv/bin/python
and you should be good.
Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.
In short it works ok for a small data set or just key points from a data set.
Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus()
creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).
Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!
function addfield() {
n=$('table tr').length;
$('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
$('input[name="aa"'+n+']').focus();
}
.m2/repository
mvn clean verify
) from the terminal at the current project location(where your project's pom.xml file exist) instead of running maven from eclipse.I know this is an old question, but since I was just looking to do this, I thought I would post what I ended up with. Because I am using Bootstrap, I went with a Bootstrap option.
HTML
<div class="col-xs-12">
<div class="form-group">
<asp:HiddenField ID="hidType" runat="server" />
<div class="btn-group" role="group" aria-label="Selection type" id="divType">
<button type="button" class="btn btn-default BtnType" data-value="1">Food</button>
<button type="button" class="btn btn-default BtnType" data-value="2">Drink</button>
</div>
</div>
</div>
jQuery
$(document).ready(function () {
$('#divType button').click(function () {
$(this).addClass('active').siblings().removeClass('active');
$('#<%= hidType.ClientID%>').val($(this).data('value'));
//alert($(this).data('value'));
});
});
I chose to store the value in a hidden field so that it would be easy for me to get the value server-side.
Edit Looking back, this is non-idiomatic Go. Small helper functions like this add an extra step of complexity. In general, the Go philosophy prefers to include the 3 simple lines over 1 tricky line.
As @robyoder mentioned, json.Indent
is the way to go. Thought I'd add this small prettyprint
function:
package main
import (
"bytes"
"encoding/json"
"fmt"
)
//dont do this, see above edit
func prettyprint(b []byte) ([]byte, error) {
var out bytes.Buffer
err := json.Indent(&out, b, "", " ")
return out.Bytes(), err
}
func main() {
b := []byte(`{"hello": "123"}`)
b, _ = prettyprint(b)
fmt.Printf("%s", b)
}
https://go-sandbox.com/#/R4LWpkkHIN or http://play.golang.org/p/R4LWpkkHIN
Quick fix: Change how excel converts imported files. Go to 'File', then 'Options', then 'Advanced'. Scroll down and uncheck 'Use system seperators'. Also change 'Decimal separator' to '.' and 'Thousands separator' to ',' . Then simply 're-save' your file in the CSV (Comma delimited) format. The root cause is usually associated with how the csv file is created. Trust that helps. Point is, why use extra code if not necessary? Cross-platform understanding and integration is key in engineering/development.
Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
comes before a stringCultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean that ß
will compare equal to SS
in Germany, or similarstringValue.Equals(otherStringValue)
null
is not considered equal to anythingStringComparison
option, it will use what looks like a direct ordinal equality check, i.e. ß
is not the same as SS
, in any language or culturestringValue == otherStringValue
stringValue.Equals()
.==
operator calls the static Equals(string a, string b)
method (which in turn goes to an internal EqualsHelper
to do the comparison..Equals()
on a null
string gets null
reference exception, while on ==
does not.Object.ReferenceEquals(stringValue, otherStringValue)
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo
or .Equals
, depending on the choice.
If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:
df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
left_on = 'key2', right_on = 'key1').drop('key1')
The .drop('key1')
part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.
This looks like you might not have enough memory allocated to your Windows VM. If the JVM is configured to use more (maximum) memory than is available then you'll get this sort of error message.
You can read more about SQL Developer's memory at (that) Jeff Smith's blog.
The default settings still seem to be -Xms128m -Xmx800m
. I can generate a similar error by setting -Xmx to be large than the physical RAM in my (physical) PC. So with the default settings, you will have problems if you don't have 800m of memory allocated to Windows. That doesn't seem like much, but it seems to be in the recommended window based on this knowledgebase article.
While you could attempt to reduce the JVM requirements in your product.conf
file that will likely lead to other issues later, if it works at all. So increase your Windows VM memory allocation, reboot, and try to launch SQL Developer again.
Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.
But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:
<parent>
<sibling></sibling>
<child></child>
</parent>
The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!
Now, how to style the sibling?
When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:
parent sibling { }
parent sibling:hover { }
parent:hover sibling { }
These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:
div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}
Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.
Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.