You can use Jquery's on method and listen for the scroll
event.
to be secured, you should execute 3 commands :
cmdkey /generic:"server-address" /user:"username" /pass:"password"
mstsc /v:server-address
cmdkey /delete:server-address
first command to save the credential
second command to open remote desktop
and the third command to delete the credential
all of these commands can be saved in a batch file(bat).
If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".
Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.
In order to have a popop with Chrome 14+, you need to do the following :
jQuery(window).bind('beforeunload', function(){
return 'my text';
});
The user will be asked if he want to stay or leave.
If you need to initialize an array fast, you might do it by blocks instead of with a generator initializer, and it's going to be much faster. Creating a list by [0]*count
is just as fast, still.
import array
def zerofill(arr, count):
count *= arr.itemsize
blocksize = 1024
blocks, rest = divmod(count, blocksize)
for _ in xrange(blocks):
arr.fromstring("\x00"*blocksize)
arr.fromstring("\x00"*rest)
def test_zerofill(count):
iarr = array.array('i')
zerofill(iarr, count)
assert len(iarr) == count
def test_generator(count):
iarr = array.array('i', (0 for _ in xrange(count)))
assert len(iarr) == count
def test_list(count):
L = [0]*count
assert len(L) == count
if __name__ == '__main__':
import timeit
c = 100000
n = 10
print timeit.Timer("test(c)", "from __main__ import c, test_zerofill as test").repeat(number=n)
print timeit.Timer("test(c)", "from __main__ import c, test_generator as test").repeat(number=n)
print timeit.Timer("test(c)", "from __main__ import c, test_list as test").repeat(number=n)
Results:
(array in blocks) [0.022809982299804688, 0.014942169189453125, 0.014089107513427734]
(array with generator) [1.1884641647338867, 1.1728270053863525, 1.1622772216796875]
(list) [0.023866891860961914, 0.035660028457641602, 0.023386955261230469]
try this :
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat);
I had did it and it worked
The newer SSH commands will list fingerprints as a SHA256 Key.
For example:
ssh-keygen -lf ~/.ssh/id_dsa.pub
1024 SHA256:19n6fkdz0qqmowiBy6XEaA87EuG/jgWUr44ZSBhJl6Y (DSA)
If you need to compare it against an old fingerprint you also need to specify to use the MD5 fingerprint hashing function.
ssh-keygen -E md5 -lf ~/.ssh/id_dsa.pub
2048 MD5:4d:5b:97:19:8c:fe:06:f0:29:e7:f5:96:77:cb:3c:71 (DSA)
Also available: -E sha1
Update... YES...yes... I know... DSA keys for SSH should no longer be used, the older RSA key or newer ecliptic keys should be used instead.
To those 'admins' that keep editing the command I used in the above. STOP CHANGING IT! You make the command and resulting output mis-match!
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string
, it's a string, and if something is declared as a double
, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!"
to a double
, there's no meaningful conversion. Sure, you could just set the double
to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double
:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail()
method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
You can try jclasslib:
https://github.com/ingokegel/jclasslib
It's nice that it can associate itself with *.class extension.
I had the same issue with Base64 not being defined. I went to an online encoder and then saved the output into a variable. This probably is not ideal for many images, but for my needs it was sufficient.
function makePDF(){
var doc = new jsPDF();
var image = "data:image/png;base64,iVBORw0KGgoAA..";
doc.addImage(image, 'JPEG', 15, 40, 180, 160);
doc.save('title');
}
Video with fall back:
try {
video.srcObject = mediaSource;
} catch (error) {
video.src = URL.createObjectURL(mediaSource);
}
video.play();
From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)
Although the answers above seems correct, just a simple explanation to give you an idea of how it works.
Suppose that your column is set to be DECIMAL(13,4)
. This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.
So, in summary, for that column you would have a max value of: 999999999.9999
use the float or real data types only if the precision provided by decimal (up to 38 digits) is insufficient
Approximate numeric data types do not store the exact values specified for many numbers; they store an extremely close approximation of the value.(Technet)
Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators (Technet)
so generally because the precision provided by decimal is [10E38 ~ 38 digits] if your number can fit in it, and smaller storage space (and maybe speed) of Float is not important and dealing with abnormal behaviors and issues of approximate numeric types are not acceptable, use Decimal generally.
more useful information
main source : MCTS Self-Paced Training Kit (Exam 70-433): Microsoft® SQL Server® 2008 Database Development - Chapter 3 - Tables , Data Types , and Declarative Data Integrity Lesson 1 - Choosing Data Types (Guidelines) - Page 93
Update this function :
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime(0);
}
else {
ini_set('magic_quotes_runtime', 0);
}
$magic_quotes = get_magic_quotes_runtime();
$file_buffer = fread($fd, filesize($path));
$file_buffer = $this->EncodeString($file_buffer, $encoding);
fclose($fd);
if ($magic_quotes) {
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime($magic_quotes);
}
else {
ini_set('magic_quotes_runtime', $magic_quotes);
}
}
return $file_buffer;
You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile
for x in itertools.takewhile(lambda x: x[2] == 0, list)
print x
Or you could use the os.path.walk function, which does more work for you than just os.walk:
A stupid example:
def walk_func(blah_args, dirname,names):
print ' '.join(('In ',dirname,', called with ',blah_args))
for name in names:
print 'Walked on ' + name
if __name__ == '__main__':
import os.path
directory = './'
arguments = '[args go here]'
os.path.walk(directory,walk_func,arguments)
One can use the textract library. It take care of both "doc" as well as "docx"
import textract
text = textract.process("path/to/file.extension")
You can even use 'antiword' (sudo apt-get install antiword) and then convert doc to first into docx and then read through docx2txt.
antiword filename.doc > filename.docx
Ultimately, textract in the backend is using antiword.
Ensure Script Debugging is disabled
I was getting this intermittently despite having tried several of the above suggestions. As soon as I disabled this, my debugging my site worked like a dream. (Think I'd only turned it on by accident, or perhaps in a previous life).
For tcsh:
set X = `echo $* | awk -F " " '{print $NF}'`
somecommand "$X"
I'm quite sure this would be a portable solution, except for the assignment.
Like this?
[bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.
Open IntelliJ preferences.
Search for "compiler" (or something like "compi").
Scroll down to Maven -->java compiler. In the right panel will be a list of modules and their associated java compile version "target bytecode version."
Select a version >1.5. You may need to upgrade your jdk if one is not available.
If you run into this problem after having $GOPATH
set up, it may be because you're running it with an unsupported shell. I was using fish
and it did not work, launching it with bash
worked fine.
First all need to do is start hadoop nodes and Trackers, simply by typing start-all.sh on ur terminal. To check all the trackers and nodes are started write 'jps' command. if everything is fine and working, go to your browser type the following url http://localhost:50070
I'm using an older Huawei phone. When I plug in to my Debian Stretch instance I get the USB computer connection popup. If this is set to MTP, PTP or "Connect to PC software" I found that "adb devices" will fail. However, if I set the connection option to:
Mount SD Card
I then could run "adb devices" and status changed from unauthorized to device.
Also I turned on:
USB debugging
Add the Git\bin
directory to the Path
environment variable. The directory is %ProgramFiles%\Git\bin
by default. By this way you can access Git Bash with simply typing bash
in every terminal including the integrated terminal of Visual Studio Code.
I'm aware that there are several answers here, but this is what I came up with. This only handles MySQL DATETIME values as per the original question I was responding to. The array $a needs some work. I welcome comments on how to improve. Call as:
echo time_elapsed_string('2014-11-14 09:42:28');
function time_elapsed_string($ptime)
{
// Past time as MySQL DATETIME value
$ptime = strtotime($ptime);
// Current time as MySQL DATETIME value
$csqltime = date('Y-m-d H:i:s');
// Current time as Unix timestamp
$ctime = strtotime($csqltime);
// Elapsed time
$etime = $ctime - $ptime;
// If no elapsed time, return 0
if ($etime < 1){
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str){
// Divide elapsed time by seconds
$d = $etime / $secs;
if ($d >= 1){
// Round to the next lowest integer
$r = floor($d);
// Calculate time to remove from elapsed time
$rtime = $r * $secs;
// Recalculate and store elapsed time for next loop
if(($etime - $rtime) < 0){
$etime -= ($r - 1) * $secs;
}
else{
$etime -= $rtime;
}
// Create string to return
$estring = $estring . $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ';
}
}
return $estring . ' ago';
}
You can use gridspec
and figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)
Well, you can read the entirety of the POST body like so
echo file_get_contents( 'php://input' );
And, assuming your webserver is Apache, you can read the request headers like so
$requestHeaders = apache_request_headers();
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
If you can change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
Arrays.sort(myArray);
int max = myArray[myArray.length - 1];
If you can't change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > max) {
max = myArray[i];
}
}
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
Had a related issue with a different, but similar fix:
I had a Windows service project set to "Any-CPU" using a 64-bit DLL. Same error message. Tried a whole bunch of things, but nothing worked. Finally, I went into project Properties -> Build and noticed that project had "Prefer 32-bit" checked. Unchecked this and no more error.
My guess is that the windows service was expecting a 32-bit DLL, and couldn't find it.
If you have directories containing really (>100'000) many files, here is a (non-portable) way to go:
String directoryPath = "a path";
// -f flag is important, because this way ls does not sort it output,
// which is way faster
String[] params = { "/bin/sh", "-c",
"ls -f " + directoryPath + " | wc -l" };
Process process = Runtime.getRuntime().exec(params);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String fileCount = reader.readLine().trim() - 2; // accounting for .. and .
reader.close();
System.out.println(fileCount);
As already mentioned in comments by Uwe and UseR, a general solution in the tidyverse
format would be to use the command unite
:
library(tidyverse)
n = c(2, 3, 5)
s = c("aa", "bb", "cc")
b = c(TRUE, FALSE, TRUE)
df = data.frame(n, s, b) %>%
unite(x, c(n, s), sep = " ", remove = FALSE)
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
For me the shortest and my favorite oneliner for accessing to the parent directory is:
sys.path.append(os.path.dirname(os.getcwd()))
or:
sys.path.insert(1, os.path.dirname(os.getcwd()))
os.getcwd() returns the name of the current working directory, os.path.dirname(directory_name) returns the directory name for the passed one.
Actually, in my opinion Python project architecture should be done the way where no one module from child directory will use any module from the parent directory. If something like this happens it is worth to rethink about the project tree.
Another way is to add parent directory to PYTHONPATH system environment variable.
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
It seems that this can't be done, not at least with current versions of IE (6 and 7).
IE supports form attribute accept-charset, but only if its value is 'utf-8'.
The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.
var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);
In most of the cases it’s only a need for the transpiler/bundler, which might not be configured to work with JSX files, but with JS! So you are forced to use JS files instead of JSX.
And since react is just a library for javascript, it makes no difference for you to choose between JSX or JS. They’re completely interchangeable!
In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files.
I know its bit older post, but still i would like to add up something to the answers above.
There might be some situation where in, the "value" of more than one items in the dropdown list is duplicated/same. So, make sure that you have no repeated values in the list items to trigger this "onselectedindexchanged" event
I just had to figure this out for a client presentation and found a work around to having the GIF play a few times by making a fake loop.
Hope this helps.
The following also worked for me. ISO 8859-1 is going to save a lot, hahaha - mainly if using Speech Recognition APIs.
Example:
file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");
Here's a chart that summarises some of the most important conversions in pandas.
Conversions to string are trivial .astype(str)
and are not shown in the figure.
Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes
a object
b object
dtype: object
# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes
a int64
b int64
dtype: object
# Infers better data types for object data - soft conversion
df.infer_objects().dtypes
a object # no change
b int64
dtype: object
# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes
Do this, it works:
defaultConfig {
applicationId "com.example.maps"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
I had similar problem when I tried to build a signed apk for my app.
Strange, it happened only when I wanted to build a release apk, while on debug apk everything worked OK.
Finally, looking on this thread, I checked for support library duplications in build.gradle and removed any duplications but this wasn't enough..
I had to do clean project and only then finally I've got it to work.
def dict_to_object(dick):
# http://stackoverflow.com/a/1305663/968442
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
return Struct(**dick)
If one decides to permanently convert that dict
to object this should do. You can create a throwaway object just before accessing.
d = dict_to_object(d)
By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.
See In eclipse, ctrl-click goes to the declaration of the method I clicked. For interfaces with one implementation, how can I just directly to that implementation? for some alternative solutions.
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
A shortcut you can add to your .bashrc etc, based on other answers here:
function perf {
curl -o /dev/null -s -w "%{time_connect} + %{time_starttransfer} = %{time_total}\n" "$1"
}
Usage:
> perf stackoverflow.com
0.521 + 0.686 = 1.290
I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just one match.
var desiredNames = new[] { "Pankaj", "Garg" };
var people = new[]
{
new { FirstName="Pankaj", Surname="Garg" },
new { FirstName="Marc", Surname="Gravell" },
new { FirstName="Jeff", Surname="Atwood" }
};
var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered select p.FirstName).ToList();
Suppose I have two list objects.
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
Using Contains, it will search for each List 1 item in List 2 that means iteration will happen 49 times !!!
See the example:
mkdir test && echo "Something" > test/file
Shell will try to create directory test
and then, only if it was successfull will try create file inside it.
So you may interrupt a sequence of steps if one of them failed.
I faced the same issue which was due to going to branch with wrong casing. git let me switch to branch with incorrect casing ie feature/Name
instead of feature/name
. Found an easier solution than listed above just:
git checkout master (or develop)
git checkout feature/name
< with correct casinggit push
Just attend those: 1- Gmail authentication for allow low level emails does not accept before you restart your client browser 2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like below
const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
routes.get('/test', (req, res) => {
res.status(200).json({ message: 'test!' });
});
routes.post('/Email', (req, res) =>{
var smtpTransport = nodemailer.createTransport({
host: "smtp.gmail.com",
secureConnection: false,
port: 587,
requiresAuth: true,
domains: ["gmail.com", "googlemail.com"],
auth: {
user: "your gmail account",
pass: "your password*"
}
});
var mailOptions = {
from: '[email protected]',
to:'[email protected]',
subject: req.body.subject,
//text: req.body.content,
html: '<p>'+req.body.content+' </p>'
};
smtpTransport.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log('Error while sending mail: ' + error);
} else {
console.log('Message sent: %s', info.messageId);
}
smtpTransport.close();
});
})
module.exports = routes;
For me, it was just close the android studio and restart as Administrator.
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as @eumiro has pointed out in comments - strftime
jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.
Example:
<div data-foo="bar"></div>
If you grabbed the value of the attribute using .data('foo')
, it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah')
and then later use .data('foo')
to grab the value, it would return "bar" even though the DOM says data-foo="blah"
. If you use .data()
to set the value, it'll change the value in the jQuery object but not in the DOM.
Basically, .data()
is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr()
is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data()
and .attr()
. Otherwise, stick with one or the other.
I guess you've meant:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
This would be sorted like this:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
On Windows, Chrome might be installed in your AppData folder:
"C:\Users\\AppData\Local\Google\Chrome\Application"
Before you execute the command, make sure all of your Chrome windows are closed and not otherwise running. Or, the command line param would not be effective.
chrome.exe --allow-file-access-from-files
$(document).ready(function() {
$("#aDateFrom").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var minDate = $('#aDateFrom').datepicker('getDate');
$("#aDateTo").datepicker("change", { minDate: minDate });
}
});
$("#aDateTo").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var maxDate = $('#aDateTo').datepicker('getDate');
$("#aDateFrom").datepicker("change", { maxDate: maxDate });
}
});
});
Few Operation relates to Array in Swift
Create Array
var stringArray = ["One", "Two", "Three", "Four"]
Add Object in Array
stringArray = stringArray + ["Five"]
Get Value from Index object
let x = stringArray[1]
Append Object
stringArray.append("At last position")
Insert Object at Index
stringArray.insert("Going", at: 1)
Remove Object
stringArray.remove(at: 3)
Concat Object value
var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
I am currently working on this, and i have already a number of solutions. It is nice to have a high quality site, that i can use also for my convenience. Because if you do not write these things down, you will eventually forget some parts. And i can also recommend writing some basic's down if you are starting any kind of new programming/design.
So if the float functions are causing problems there is a couple of options you can try.
One is modify the div alignment in the div tag it self like so <div class="kosher" align=left>
If this does not suit you then there is another option with margin like so.
.leftdiv {
display: inline-block;
width: 40%;
float: left;
}
.rightdiv {
display: block;
margin-right: 20px;
margin-left: 45%;
}
Don't forget to remove the <div align=left>
.
I find that using Apache Commons IO makes my life much easier.
String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");
You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.
you can use class "img-fluid" for newer version i.e Bootstrap v4.
and can use class "img-responsive" for older version like Bootstrap v3.
Usage:-
img tag with :-
class="img-fluid"
src="..."
Prior to standardization there was ioctl(
...FIONBIO
...)
and fcntl(
...O_NDELAY
...)
, but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO
to work on sockets and O_NDELAY
to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO
or O_NDELAY
on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.
POSIX addressed this with the introduction of O_NONBLOCK
, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.
New programs should use fcntl(
...O_NONBLOCK
...)
, as standardized by POSIX.
you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:
.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}
Just a quick thing, that denotes the intent of descending order.
descending = -1
a.sort_by { |h| h[:bar] * descending }
(Will think of a better way in the mean time) ;)
a.sort_by { |h| h[:bar] }.reverse!
for example if you want to get EMAIL ADDRESS from config->store email addresses. You can specify from wich store you will want the address:
$store=Mage::app()->getStore()->getStoreId();
/* Sender Name */
Mage::getStoreConfig('trans_email/ident_general/name',$store);
/* Sender Email */
Mage::getStoreConfig('trans_email/ident_general/email',$store);
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined
keyword.
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).
To specifically address your problem, you should remove the brackets after donothing
in your setTimeout
call, and make waitsecs
a number not a string:
console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
But that won't stop execution; "after" will be logged before your function runs.
To wait properly, you can use anonymous functions:
console.log('before');
setTimeout(function(){
console.log('after');
},500);
All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval
/ clearInterval
if it needs to loop.
I had the same problem and my problem had nothing to do with paths. One of my dll-s was written in c++ and it turnes out that if your visual studio doesn't know how to open a dll file it will say that it did not find it. What i did was locate which dll it did not find, than searched for that dll in my directories and opened it in a separate visual studio window. When trying to navigate through Solution explorer of that project, visual studio said that it cannot show what is inside and that i need some extra extensions, so that it can open those files. Surely enough, after installing the recomended extension (in my case something to do with c++) the
"This application has failed to start because xxx.dll was not found."
error miraculously dissapeared.
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular,
rand()
anduniqid()
are not cryptographically secure random number generators. See Scott's answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
md5(uniqid($your_user_login, true))
For me this was thrown when running unit tests under MSTest
(VS2015). Had to add
<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>
in
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config
Add the following code to the .htaccess file:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
Where [your domain name] is your website's domain name.
You can also redirect specific folders off of your domain name by replacing the last line of the code above with:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
Use insert() to insert an element before a given position.
For instance, with
arr = ['A','B','C']
arr.insert(0,'D')
arr becomes ['D','A','B','C']
because D
is inserted before the element at index 0.
Now, for
arr = ['A','B','C']
arr.insert(4,'D')
arr becomes ['A','B','C','D']
because D
is inserted before the element at index 4 (which is 1 beyond the end of the array).
However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.
Here's some example code:
import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
print perm
will print out
('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t
You can access the keys with ${!array[@]}
:
bash-4.0$ echo "${!array[@]}"
foo bar
Then, iterating over the key/value pairs is easy:
for i in "${!array[@]}"
do
echo "key :" $i
echo "value:" ${array[$i]}
done
You could use a GET
request to get the page content and then display that data using the Webview
, this way you are not using multiple server calls. Alternative you can use Javascript
to check the DOM
object for validity.
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
Use XSSFCellStyle.BORDER_MEDIUM
or XSSFBorderFormatting.BORDER_MEDIUM
(both enums refer to the same value):
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
cell.setCellStyle(cellStyle);
Use setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, XSSFColor)
or setBottomBorderColor(XSSFColor)
(equivalent for top, left, right):
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFColor color = new XSSFColor(new java.awt.Color(128, 0, 128));
cellStyle.setTopBorderColor(color);
cellStyle.setRightBorderColor(color);
cellStyle.setBottomBorderColor(color);
cellStyle.setLeftBorderColor(color);
cell.setCellStyle(cellStyle);
You can get the parameters you are asking for by typing:
dir /?
For the full list, try:
dir /s /b /a:d
You can use Array.sort
.
Here's an example:
var arr = [{
"updated_at": "2012-01-01T06:25:24Z",
"foo": "bar"
},
{
"updated_at": "2012-01-09T11:25:13Z",
"foo": "bar"
},
{
"updated_at": "2012-01-05T04:13:24Z",
"foo": "bar"
}
]
arr.sort(function(a, b) {
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
console.log(arr);
_x000D_
I simply just add e(fx)clipse in eclipse marketplace. Easy and simple
You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
Or, if the columns are not matched up in order:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
To make it a bit more user-friendly:
After you've unpacked it, go into the directory, and run bin/pycharm.sh
.
Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...
Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)
To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)
(Unless you are trying to debug an application, you usually do not need to see the output of it.)
There is no need for an UDF here. Column
already provides cast
method with DataType
instance :
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
or short string:
changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
where canonical string names (other variations can be supported as well) correspond to simpleString
value. So for atomic types:
from pyspark.sql import types
for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType',
'DecimalType', 'DoubleType', 'FloatType', 'IntegerType',
'LongType', 'ShortType', 'StringType', 'TimestampType']:
print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp
and for example complex types
types.ArrayType(types.IntegerType()).simpleString()
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'
You can delete the file using
unlink($Your_file_path);
but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.
You can save an image as 'png' and use the python imaging library (PIL) to convert this file to 'jpg':
import Image
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.savefig('testplot.png')
Image.open('testplot.png').save('testplot.jpg','JPEG')
The original:
The JPEG image:
View -> Show Symbol -> uncheck Show End of Line.
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
You can use the inbuilt function max()
with multiple arguments:
print max(1, 2, 3)
or a list:
list = [1, 2, 3]
print max(list)
or in fact anything iterable.
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
All that the test
attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %>
returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if>
tag looks for.
Add Json NamingStrategy property to your class definition.
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
_x000D_
While it is possible to combine the results, I would advise against doing so.
You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.
The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?
If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.
Deadlock occurs when two threads aquire locks which prevent either of them from progressing. The best way to avoid them is with careful development. Many embedded systems protect against them by using a watchdog timer (a timer which resets the system whenever if it hangs for a certain period of time).
It seems the interface has changed in .NET 4.0. There is the following method that achieves all of the above. As Tommy Engebretsen suggested, putting it in a TextChanged event handler makes it automatic.
textBox1.ScrollToEnd();
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
import tensorflow as tf
print(tf.VERSION)
Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.
button = $('.status-button a', whatever);
if(button.hasClass('close')) {
button.delay(10000).queue(function() {
$(this).click().dequeue();
});
}
All previous answers have overlooked that the setcookie
could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com
domain, there might be a cookie set on tar.com
. Therefore, you want to unset cookies for all domains that might have dropped the cookie:
$host = explode('.', $_SERVER['HTTP_HOST']);
while ($host) {
$domain = '.' . implode('.', $host);
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1, '/', $domain);
}
array_shift($host);
}
Can you just just some
?
<div style="text-align: center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>
If you have a border on a button and want to hide the dotted outline in Firefox without removing the border (and hence it's extra width on the button) you can use:
.button::-moz-focus-inner {
border-color: transparent;
}
I really like this method as well, less clutter:
count=$[count+1]
A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox
Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
indicate, this routine is of the third kind.
The syntactical rules of VBScript are simple:
Use parameter list () when calling a (routine as a) Function
If you want to display a message to the user and need to know the user's reponse:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
Don't use parameter list () when calling a (routine as a) Sub
If you want to display a message to the user and are not interested in the response:
MsgBox "Hello World!", 65, "MsgBox Example"
This beautiful simplicity is messed up by:
The design flaw of using () for parameter lists and to force call-by-value semantics
>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2
S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that
>> s = "value"
>> MsgBox(s)
'works' are in for a suprise when they try:
>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number: 1044
Error Description: Cannot use parentheses when calling a Sub
The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by
Randomize()
although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in
Randomize n
and
Randomize (n)
The Call statement that allows parameter list () in Sub calls:
s = "value" Call MsgBox(s, 65, "MsgBox Example")
which further encourage programmers to use () without thinking.
(Based on What do you mean "cannot use parentheses?")
you must add in your MODULE-LEVEL build.gradle file with:
//module-level build.gradle file
repositories {
maven {
url 'https://maven.google.com'
}
}
see: Google's Maven repository
I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:
//project-level build.gradle file
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0
Yes, the first one is a static method
also called class method
, while the second one is an instance method
.
Consider the following examples, to understand it in more detail.
In ES5
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.isPerson = function(obj) {
return obj.constructor === Person;
}
Person.prototype.sayHi = function() {
return "Hi " + this.firstName;
}
In the above code, isPerson
is a static method, while sayHi
is an instance method of Person
.
Below, is how to create an object from Person
constructor.
var aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
In ES6
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
static isPerson(obj) {
return obj.constructor === Person;
}
sayHi() {
return `Hi ${this.firstName}`;
}
}
Look at how static
keyword was used to declare the static method isPerson
.
To create an object of Person
class.
const aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class
introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.
You have to include sort
function which is in algorithm
header file which is a standard template library in c++.
Usage: std::sort(str.begin(), str.end());
#include <iostream>
#include <algorithm> // this header is required for std::sort to work
int main()
{
std::string s = "dacb";
std::sort(s.begin(), s.end());
std::cout << s << std::endl;
return 0;
}
OUTPUT:
abcd
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
Is this what you mean?
function showAsFloat(num, n){_x000D_
return !isNaN(+num) ? (+num).toFixed(n || 2) : num;_x000D_
}_x000D_
_x000D_
document.querySelector('#result').textContent = _x000D_
[_x000D_
'command | result',_x000D_
'-----------------------------------------------',_x000D_
'showAsFloat(1); | ' + showAsFloat(1),_x000D_
'showAsFloat(1.314); | ' + showAsFloat(1.314),_x000D_
'showAsFloat(\'notanumber\') | ' + showAsFloat('notanumber'),_x000D_
'showAsFloat(\'23.44567\', 3) | ' + showAsFloat('23.44567', 3),_x000D_
'showAsFloat(2456198, 5) | ' + showAsFloat('2456198', 5),_x000D_
'showAsFloat(0); | ' + showAsFloat(0)_x000D_
].join('\n');
_x000D_
<pre id="result"></pre>
_x000D_
You should use this one too:
./gradlew :app:dependencies
(Mac and Linux) -With ./
gradlew :app:dependencies
(Windows) -Without ./
The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.
The references in a website project are stored in its web.config file. Update the reference there to fix the error.
I spent some time looking at all the references in my solution before realizing that I had forgotten about the references in the web.config file.
As scoota269 says, you should use onSubmit
instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)
<form action="#" onsubmit="handle">
<input type="text" name="txt" />
</form>
<script>
function handle(e){
e.preventDefault(); // Otherwise the form will be submitted
alert("FORM WAS SUBMITTED");
}
</script>
If you want to have an event on the input-field then you need to make sure your handle()
will return false, otherwise the form will get submitted.
<form action="#">
<input type="text" name="txt" onkeypress="handle(event)" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
e.preventDefault(); // Ensure it is only this code that runs
alert("Enter was pressed was presses");
}
}
</script>
You may have to replace getActivity() with MainActivity.this for those that are having issues with this.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
You can use pure Python to do it:
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
malloc(0)
may (optionally) return NULL
, depending on the implementation. Do you realize why you may be calling malloc(0)
? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
There is no reason against using a single block for multiple operations, since any thrown exception will prevent the execution of further operations after the failed one. At least as long as you can conclude which operation failed from the exception caught. That is as long as it is fine if some operations are not processed.
However I'd say that returning the exception makes only limited sense. A return value of a function should be the expected result of some action, not the exception. If you need to react on the exception in the calling scope then either do not catch the exception here inside your function, but in the calling scope or re-throw the exception for later processing after having done some debug logging and the like.
I've taken Irritate's answer and refactored it so as to minimize the computational steps for subsequent computations by factoring it into the fewest constants. The motivation is to allow a scaler to be trained on one set of data, and then be run on new data (for an ML algo). In effect, it's much like SciKit's preprocessing MinMaxScaler for Python in usage.
Thus, x' = (b-a)(x-min)/(max-min) + a
(where b!=a) becomes x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
which can be reduced to two constants in the form x' = x*Part1 + Part2
.
Here's a C# implementation with two constructors: one to train, and one to reload a trained instance (e.g., to support persistence).
public class MinMaxColumnSpec
{
/// <summary>
/// To reduce repetitive computations, the min-max formula has been refactored so that the portions that remain constant are just computed once.
/// This transforms the forumula from
/// x' = (b-a)(x-min)/(max-min) + a
/// into x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
/// which can be further factored into
/// x' = x*Part1 + Part2
/// </summary>
public readonly double Part1, Part2;
/// <summary>
/// Use this ctor to train a new scaler.
/// </summary>
public MinMaxColumnSpec(double[] columnValues, int newMin = 0, int newMax = 1)
{
if (newMax <= newMin)
throw new ArgumentOutOfRangeException("newMax", "newMax must be greater than newMin");
var oldMax = columnValues.Max();
var oldMin = columnValues.Min();
Part1 = (newMax - newMin) / (oldMax - oldMin);
Part2 = newMin + (oldMin * (newMin - newMax) / (oldMax - oldMin));
}
/// <summary>
/// Use this ctor for previously-trained scalers with known constants.
/// </summary>
public MinMaxColumnSpec(double part1, double part2)
{
Part1 = part1;
Part2 = part2;
}
public double Scale(double x) => (x * Part1) + Part2;
}
This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.
My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.
The supports
method makes sure that all requests that were handled by the StringHttpMessageConverter
(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite
method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).
@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
converterType === StringHttpMessageConverter::class.java
override fun beforeBodyWrite(
body: Any?,
returnType: MethodParameter,
selectedContentType: MediaType,
selectedConverterType: Class<out HttpMessageConverter<*>>,
request: ServerHttpRequest,
response: ServerHttpResponse
): Any? {
return if (request.uri.path.contains("api")) {
response.getHeaders().contentType = MediaType.APPLICATION_JSON
ob.writeValueAsString(body)
} else body
}
}
I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter
should be used for the output.
First, use SoapUI to create your soap project from the wsdl. Try to send a request to play with the wsdl's operations. Observe how the xml request composes your data fields.
And then, if you are having problem getting SoapClient acts as you want, here is how I debug it. Set the option trace so that the function __getLastRequest() is available for use.
$soapClient = new SoapClient('http://yourwdsdlurl.com?wsdl', ['trace' => true]);
$params = ['user' => 'Hey', 'account' => '12345'];
$response = $soapClient->__soapCall('<operation>', $params);
$xml = $soapClient->__getLastRequest();
Then the $xml variable contains the xml that SoapClient compose for your request. Compare this xml with the one generated in the SoapUI.
For me, SoapClient seems to ignore the keys of the associative array $params and interpret it as indexed array, causing wrong parameter data in the xml. That is, if I reorder the data in $params, the $response is completely different:
$params = ['account' => '12345', 'user' => 'Hey'];
$response = $soapClient->__soapCall('<operation>', $params);
If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure
I used the following stored procedure to return the value.
CREATE PROCEDURE usp_get_count
AS
BEGIN
DECLARE @VALUE int;
SET @VALUE=(SELECT COUNT(*) FROM tblCar);
RETURN @VALUE;
END
GO
With versions of cut
I know of, no, this is not possible. cut
is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd
) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.
field.setInputType(InputType.TYPE_CLASS_TEXT);
The localStorage
can only store string content and you are trying to store a jQuery object since html(htmlString)
returns a jQuery object.
You need to set the string content instead of an object. And use the setItem
method to add data and getItem
to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:
String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );
7 years have passed and I don't know whether it works for IE6 or not, but this prompts OpenFileDialog in FF and Chrome.
var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
As stated in other answers, label is an inline element. However, you can apply display: inline-block
to the label and then center with text-align
.
#name_label {
display: inline-block;
width: 90%;
text-align: right;
}
Why display: inline-block
and not display: inline
? For the same reason that you can't align label
, it's inline.
Why display: inline-block
and not display: block
? You could use display: block
, but it will be on another line. display: inline-block
combines the properties of inline
and block
. It's inline, but you can also give it a width, height, and align it.
Just for fun, I found an interesting article here, to use a somehow hidden evaluate function that does exist in Excel. The trick is to assign it to a name, and use the name in your cells, because EVALUATE() would give you an error msg if used directly in a cell. I tried and it works! You can use it with a relative name, if you want to copy accross rows if a sheet.
We can set layout gravity on any view like below way-
myView = findViewById(R.id.myView);
myView.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
or
myView.setGravity(Gravity.BOTTOM);
This is equilent to below xml code
<...
android:gravity="center_vertical|right"
...
.../>
My take from here (compatible with "use strict"; does not really use jQuery):
function decodeURIParams(query) {
if (query == null)
query = window.location.search;
if (query[0] == '?')
query = query.substring(1);
var params = query.split('&');
var result = {};
for (var i = 0; i < params.length; i++) {
var param = params[i];
var pos = param.indexOf('=');
if (pos >= 0) {
var key = decodeURIComponent(param.substring(0, pos));
var val = decodeURIComponent(param.substring(pos + 1));
result[key] = val;
} else {
var key = decodeURIComponent(param);
result[key] = true;
}
}
return result;
}
function encodeURIParams(params, addQuestionMark) {
var pairs = [];
for (var key in params) if (params.hasOwnProperty(key)) {
var value = params[key];
if (value != null) /* matches null and undefined */ {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
}
if (pairs.length == 0)
return '';
return (addQuestionMark ? '?' : '') + pairs.join('&');
}
//// alternative to $.extend if not using jQuery:
// function mergeObjects(destination, source) {
// for (var key in source) if (source.hasOwnProperty(key)) {
// destination[key] = source[key];
// }
// return destination;
// }
function navigateWithURIParams(newParams) {
window.location.search = encodeURIParams($.extend(decodeURIParams(), newParams), true);
}
Example usage:
// add/update parameters
navigateWithURIParams({ foo: 'bar', boz: 42 });
// remove parameter
navigateWithURIParams({ foo: null });
// submit the given form by adding/replacing URI parameters (with jQuery)
$('.filter-form').submit(function(e) {
e.preventDefault();
navigateWithURIParams(decodeURIParams($(this).serialize()));
});
For me, this error occurred because of a null parameter being passed. Checking the variable values fixed my issue without having to change the code. I used BackgroundWorker.
Private Sub BagQty_KeyPress(sender As Object, e As KeyPressEventArgs) Handles BagQty.KeyPress
Select e.KeyChar
Case Microsoft.VisualBasic.ChrW(Keys.Return)
PurchaseTotal.Text = Val(ActualRate.Text) * Val(BagQty.Text)
End Select
End Sub
I use this line for Spring Boot applications:
logging.level.org.springframework.jdbc.core = TRACE
This approach pretty universal and I usually use it for any other classes inside my application.
Currently you are sending the data as typical POST values, which look like this:
first_name=somename&last_name=somesurname
If you want to send data as json you need to create an object with data and stringify it.
data: JSON.stringify(someobject)
To update the content of existing rows use the UPDATE
statement:
UPDATE table_name SET table_column = 'test';
It might help to see your CSS, as it sounds like a rather weird issue. But anyway, if it is happening and all else is good, you could try shifting the hover effect to javascript (you could use jquery as well). Simply, bind to the mouseover or better still mouseenter event and light up your element when the event fires.
Checkout the last example here: http://api.jquery.com/mouseover/, you could use something similar to log when the event fires and take it from there!
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
You could try something like this:
select *
from jobdetails
where job_no like '071[12]%'
Not exactly what you're asking, but it has the same effect, and is flexible in other ways too :)
I faced similar issue and it was caused because I had written WebServlet Path in the .java file as well as in the web.xml . Removing it from any one location works fine for me.
In the .java file
@WebServlet("/index1.jsp")
and in web.xml
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>tpc.Logout</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/index1.jsp</url-pattern>
</servlet-mapping>
Add list-style-position: inside
to the ul
element. (example)
The default value for the list-style-position
property is outside
.
ul {_x000D_
text-align: center;_x000D_
list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>
_x000D_
Another option (which yields slightly different results) would be to center the entire ul
element:
.parent {_x000D_
text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
in my case
my service has function to Upload Files
and this error just shown up on trying to upload Big Files
so I found this answer to Increase maxRequestLength
to needed value in web.config
and problem solved
if you don't make any upload or download operations maybe this answer will not help you
There is a straightforward way using xargs:
> echo '"quoted"' | xargs
quoted
xargs uses echo as the default command if no command is provided and strips quotes from the input. See e.g. here.
If you are looking for a recursive version without using the json
module:
def ordereddict_to_dict(value):
for k, v in value.items():
if isinstance(v, dict):
value[k] = ordereddict_to_dict(v)
return dict(value)
jQuery has a built-in method jQuery.grep
that works similarly to the ES5 filter
function from @adamse's Answer and should work fine on older browsers.
Using adamse's example:
var peoples = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
you can do the following
jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate
(as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:
svn switch --relocate \
svn+ssh://olduser@svnserver/path/to/repo \
svn+ssh://newuser@svnserver/path/to/repo
where svn+ssh://olduser@svnserver/path/to/repo
can be found in the URL:
line output of svn info
command. This command asked me for the password of newuser
.
Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update
etc.
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
.Net Core Solution
Handles null situation and does not throw an exception, but returns true
if no value is presented; otherwise takes the inputted Boolean and reverses it.
public class BooleanToReverseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> !(bool?) value ?? true;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> !(value as bool?);
}
Xaml
IsEnabled="{Binding IsSuccess Converter={StaticResource BooleanToReverseConverter}}"
App.Xaml I like to put all my converter statics in the app.xaml file so I don't have to redeclare them throughout the windows/pages/controls of the project.
<Application.Resources>
<converters:BooleanToReverseConverter x:Key="BooleanToReverseConverter"/>
<local:FauxVM x:Key="VM" />
</Application.Resources>
To be clear converters:
is the namespace to the actual class implementation (xmlns:converters="clr-namespace:ProvingGround.Converters"
).
Return a tuple:
func getTime() -> (Int, Int, Int) {
...
return ( hour, minute, second)
}
Then it's invoked as:
let (hour, minute, second) = getTime()
or:
let time = getTime()
println("hour: \(time.0)")
try this
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1.BalloonTipText = "Application Minimized.";
notifyIcon1.BalloonTipTitle = "test";
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowInTaskbar = false;
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(1000);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ShowInTaskbar = true;
notifyIcon1.Visible = false;
WindowState = FormWindowState.Normal;
}
Even inspite of installing Service pack you are getting the error then try removing/renaming the cvtres.exe in the C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin folder. This has worked for me.
Another pure BASH way:
> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv
I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:
var out = def({
'int': function(a) {
alert('Here is int '+a);
},
'float': function(a) {
alert('Here is float '+a);
},
'string': function(a) {
alert('Here is string '+a);
},
'int,string': function(a, b) {
alert('Here is an int '+a+' and a string '+b);
},
'default': function(obj) {
alert('Here is some other value '+ obj);
}
});
out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);
The methods used to achieve this:
var def = function(functions, parent) {
return function() {
var types = [];
var args = [];
eachArg(arguments, function(i, elem) {
args.push(elem);
types.push(whatis(elem));
});
if(functions.hasOwnProperty(types.join())) {
return functions[types.join()].apply(parent, args);
} else {
if (typeof functions === 'function')
return functions.apply(parent, args);
if (functions.hasOwnProperty('default'))
return functions['default'].apply(parent, args);
}
};
};
var eachArg = function(args, fn) {
var i = 0;
while (args.hasOwnProperty(i)) {
if(fn !== undefined)
fn(i, args[i]);
i++;
}
return i-1;
};
var whatis = function(val) {
if(val === undefined)
return 'undefined';
if(val === null)
return 'null';
var type = typeof val;
if(type === 'object') {
if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
return 'array';
if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
return 'date';
if(val.hasOwnProperty('toExponential'))
type = 'number';
if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
return 'string';
}
if(type === 'number') {
if(val.toString().indexOf('.') > 0)
return 'float';
else
return 'int';
}
return type;
};
Use mysql_num_rows(), to check if rows are available or not
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
For those of you using the cache
option of $.ajaxSetup()
on mobile Safari, it appears that you may have to use a timestamp for POSTs, since mobile Safari caches that too. According to the documentation on $.ajax()
(which you are directed to from $.ajaxSetup()
):
Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
So setting that option alone won't help you in the case I mentioned above.
just add
android:gravity="bottom" android:paddingBottom="10dp"
change paddingBottom according to your size of edittext
Hmmm... Keep in mind that Class may or may not implement equals() -- that is not required by the spec. For instance, HP Fortify will flag myClass.equals(myOtherClass).
This is a function that I use. Created it once so I always have this functionality:
function getDir(){
$directory = dirname(__FILE__);
$directory = explode("/",$directory);
$findTarget = 0;
$targetPath = "";
foreach($directory as $dir){
if($findTarget == 1){
$targetPath = "".$targetPath."/".$dir."";
}
if($dir == "public_html"){
$findTarget = 1;
}
}
return "http://www.".$_SERVER['SERVER_NAME']."".$targetPath."";
}
Use DecimalFormat
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(myDouble);
System.out.println(fString);
If you want disable it in Global, you can write a custom middleware, like this
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
then add this class youappname.middlewarefilename.DisableCsrfCheck
to MIDDLEWARE_CLASSES
lists, before django.middleware.csrf.CsrfViewMiddleware
resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...
hard-size your DIV relative to your image
position your asp:login control where needed...
Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.
If your functions are mainly doing I/O work (and less CPU work) and you have Python 3.2+, you can use a ThreadPoolExecutor:
from concurrent.futures import ThreadPoolExecutor
def run_io_tasks_in_parallel(tasks):
with ThreadPoolExecutor() as executor:
running_tasks = [executor.submit(task) for task in tasks]
for running_task in running_tasks:
running_task.result()
run_io_tasks_in_parallel([
lambda: print('IO task 1 running!'),
lambda: print('IO task 2 running!'),
])
If your functions are mainly doing CPU work (and less I/O work) and you have Python 2.6+, you can use the multiprocessing module:
from multiprocessing import Process
def run_cpu_tasks_in_parallel(tasks):
running_tasks = [Process(target=task) for task in tasks]
for running_task in running_tasks:
running_task.start()
for running_task in running_tasks:
running_task.join()
run_cpu_tasks_in_parallel([
lambda: print('CPU task 1 running!'),
lambda: print('CPU task 2 running!'),
])
Here are two suggestions. First, if mysql supports ROW_NUMBER(), it's very simple:
WITH Ranked AS (
SELECT Id, Name, OtherColumns,
ROW_NUMBER() OVER (
PARTITION BY Name
ORDER BY Id DESC
) AS rk
FROM messages
)
SELECT Id, Name, OtherColumns
FROM messages
WHERE rk = 1;
I'm assuming by "last" you mean last in Id order. If not, change the ORDER BY clause of the ROW_NUMBER() window accordingly. If ROW_NUMBER() isn't available, this is another solution:
Second, if it doesn't, this is often a good way to proceed:
SELECT
Id, Name, OtherColumns
FROM messages
WHERE NOT EXISTS (
SELECT * FROM messages as M2
WHERE M2.Name = messages.Name
AND M2.Id > messages.Id
)
In other words, select messages where there is no later-Id message with the same Name.
If you are using HUE this is fairly simple as well. Simply go to the Hive editor in HUE, execute your hive query, then save the result file locally as XLS or CSV, or you can save the result file to HDFS.
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
Just few more details:
`image` blob
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
<img src="data:image/png;base64,'.base64_encode($row['image']).'">
The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows:
SELECT coalesce(a, '') || coalesce(b, '') FROM foo;
As you are on 9.x, you can wrap that into a DO statement:
do
$body$
declare
num_users integer;
begin
SELECT count(*)
into num_users
FROM pg_user
WHERE usename = 'my_user';
IF num_users = 0 THEN
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
END IF;
end
$body$
;
The problem is still your pg_hba.conf
file (/etc/postgresql/9.1/main/pg_hba.conf*
).
This line:
local all postgres peer
Should be:
local all postgres md5
* If you can't find this file, running locate pg_hba.conf
should show you where the file is.
After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be sudo service postgresql restart
.
These are brief descriptions of both options according to the official PostgreSQL docs on authentication methods.
The peer authentication method works by obtaining the client's operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.
The password-based authentication methods are md5 and password. These methods operate similarly except for the way that the password is sent across the connection, namely MD5-hashed and clear-text respectively.
If you are at all concerned about password "sniffing" attacks then md5 is preferred. Plain password should always be avoided if possible. However, md5 cannot be used with the db_user_namespace feature. If the connection is protected by SSL encryption then password can be used safely (though SSL certificate authentication might be a better choice if one is depending on using SSL).
Sample location for pg_hba.conf
:
/etc/postgresql/9.1/main/pg_hba.conf
Plenty of responses already, but you can use this:
Sub runQry(qDefName)
Dim db As DAO.Database, qd As QueryDef, par As Parameter
Set db = CurrentDb
Set qd = db.QueryDefs(qDefName)
On Error Resume Next
For Each par In qd.Parameters
Err.Clear
par.Value = Eval(par.Name) 'try evaluating param
If Err.Number <> 0 Then 'failed ?
par.Value = InputBox(par.Name) 'ask for value
End If
Next par
On Error GoTo 0
qd.Execute dbFailOnError
End Sub
Sub runQry_test()
runQry "test" 'qryDef name
End Sub
<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>
A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.
To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.
If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.
just use the android:hint
attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.
I'm surprised why no one suggested to use the WinForms Textbox.
XAML:
<WindowsFormsHost Margin="10" Width="70">
<wf:TextBox x:Name="textbox1"/>
</WindowsFormsHost>
Also don't forget the Winforms Namespace:
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
C#:
AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection(){"String 1", "String 2", "etc..."};
textbox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textbox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textbox1.AutoCompleteCustomSource = stringCollection;
With Autocomplete, you need to do it in the Code behind, because for some reasons, others might can explain, it throws an exception.