As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.
Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.
In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.
if you debug and loook at ctx=null,maybe your username hava proble ,you shoud write like "ac\administrator"(double "\") or "administrator@ac"
You will have to provide the entire user dn
in SECURITY_PRINCIPAL
like this
env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test");
Try this:
jQuery('body').after('<a id="Download" target="_blank">Click Here</a>');
var canvas = document.getElementById('canvasID');
var ctx = canvas.getContext('2d');
document.getElementById('Download').addEventListener('click', function() {
downloadCanvas(this, 'canvas', 'test.png');
}, false);
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.Download = filename;
}
You can just put this code in console in firefox or chrom and after changed your canvas tag ID in this above script and run this script in console.
After the execute this code you will see the link as text "click here" at bottom of the html page. click on this link and open the canvas drawing as a PNG image in new window save the image.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"
$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"
Look in to jQuery Selectors :contains is a selector
here is info on the :contains selector
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
String a="Siva";
for(int i=0;i<=a.length()-1;i++){
System.out.print(a.charAt(i));
}
for(int i = a.length() - 1; i >= 0; --i){
System.out.println(a.charAt(i));
}
After watching the DevBytes video (by Roman Nurik) and reading the very last line in the docs, which says:
Note: If you like the auto-hiding behavior of IMMERSIVE_STICKY but need to show your own UI controls as well, just use IMMERSIVE combined with Handler.postDelayed() or something similar to re-enter immersive mode after a few seconds.
the answer, radu122 gave, worked for me. Just setup a handler and your will be good to go.
Here is the code which works for me:
@Override
protected void onResume() {
super.onResume();
executeDelayed();
}
private void executeDelayed() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// execute after 500ms
hideNavBar();
}
}, 500);
}
private void hideNavBar() {
if (Build.VERSION.SDK_INT >= 19) {
View v = getWindow().getDecorView();
v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
Google says "after a few seconds" - but I want to provide this functionality as soon as possible. Maybe I will change the value later, if I have to, I will update this answer.
My favorite:
https://inloop.github.io/sqlite-viewer/
No installation needed. Just drop the file.
I found out that with HostGator you have to set files to CMOD 644 and Folders to 755. Since I did this based on their tech support it works with HostGator
You can also use numpy.subtract
It has the advantage over the difference operator, -
, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:
array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
Example: (Python 3.5)
import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
which gives you
the difference = [ 0.1 0.2 0.3]
Remember, however, that if you try to subtract sequences (lists or tuples) with the -
operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays
Wrong Code:
print([1.1, 2.2, 3.3] - [1, 2, 3])
You've got to override your Canvas's paint(Graphics g)
method and perform your drawing there. See the paint() documentation.
As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.
The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.
(And enhancing print statements with Data::Dumper)
I suggest you to use fnmatch and the upper method. In this way you can find any of the following:
.
import fnmatch
import os
for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
if fnmatch.fnmatch(file.upper(), '*.TXT'):
print(file)
In my case, my script has parameters, so I set:
Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
How about just a simple reset button?
<form>
<input type="text" id="textfield1" size="5">
<input type="text" id="textfield2" size="5">
<input type="reset" value="Reset">
</form>
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
An alternative tool to py2exe is bbfreeze which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.
You can also use XmlConvert.ToDateString
var dateStr = "2011-03-21 13:26";
var parsedDate = XmlConvert.ToDateTime(dateStr, "yyyy-MM-dd hh:mm");
It is good to specify the date kind, the code is:
var anotherParsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
More details on different parsing options http://amir-shenodua.blogspot.ie/2017/06/datetime-parsing-in-net.html
It's important to note that Lauritz's suggestion idea of using bisect does not actually find the closest value in MyList to MyNumber. Instead, bisect finds the next value in order after MyNumber in MyList. So in OP's case you'd actually get the position of 44 returned instead of the position of 4.
>>> myList = [1, 3, 4, 44, 88]
>>> myNumber = 5
>>> pos = (bisect_left(myList, myNumber))
>>> myList[pos]
...
44
To get the value that's closest to 5 you could try converting the list to an array and using argmin from numpy like so.
>>> import numpy as np
>>> myNumber = 5
>>> myList = [1, 3, 4, 44, 88]
>>> myArray = np.array(myList)
>>> pos = (np.abs(myArray-myNumber)).argmin()
>>> myArray[pos]
...
4
I don't know how fast this would be though, my guess would be "not very".
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
I use printf, is shorter as it doesn't need flags to do the work:
printf "\rMy static $myvars composed text"
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
needs to be:
var t = document.getElementById("table"),
tableRows = t.getElementsByTagName("tr"),
r = [], i, len, tds, j, jlen;
for ( i =0, len = tableRows.length; i<len; i++) {
tds = tableRows[i].getElementsByTagName('td');
for( j = 0, jlen = tds.length; j < jlen; j++) {
r.push(tds[j]);
}
}
Because getElementsByTagName
returns a NodeList
an Array-like structure. So you need to loop through the return nodes and then populate you r
like above.
I find that the Browse With..
menu item only appears in Visual Studio 2010 when I Run as administrator
. And in that case it is available even while in debug mode.
$scope.toggleRightDelayed = function(){
var myInterval = $interval(function(){
$scope.toggleRight();
},1000,1)
.then(function(){
$interval.cancel(myInterval);
});
};
Here are some conversion routines I wrote many years ago for a c++/cli project, they should still work.
void StringToStlWString ( System::String const^ s, std::wstring& os)
{
String^ string = const_cast<String^>(s);
const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
System::String^ StlWStringToString (std::wstring const& os) {
String^ str = gcnew String(os.c_str());
//String^ str = gcnew String("");
return str;
}
System::String^ WPtrToString(wchar_t const* pData, int length) {
if (length == 0) {
//use null termination
length = wcslen(pData);
if (length == 0) {
System::String^ ret = "";
return ret;
}
}
System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
return ret;
}
void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
stlString = pString;
}
void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
stlString = pString;
}
Laravel provides bunch of helper functions and for your requirement you can simply
use url() function of Laravel Helpers
but in case of Laravel 5.2 you will have to use url('/')
here is the list of all other helper functions of Laravel
I had this issue with Dialogs based on an extended DialogFragment which worked fine on devices running API 26 but failed with API 23. The above strategies didn't work but I resolved the issue by removing the onCreateView method (which had been added by a more recent Android Studio template) from the DialogFragment and creating the dialog in onCreateDialog.
I had the exact same problem. Turned out that the max-heap-size was set to 1024 and missing the unit. The configuration needed to be max-heap-size=1024m.
So apparently invalid memory configuration in the jnlp file will cause this exact behavior.
In case of a large file you can use pandas.read_csv
with the chunksize
argument which allows to read the dataset per chunk:
import pandas as pd
INPUT_CSV = "input.csv"
OUTPUT_CSV = "output.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(OUTPUT_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
If you want to update the file inplace, you can use a temporary file and erase it at the end
import pandas as pd
INPUT_CSV = "input.csv"
TMP_CSV = "tmp.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(TMP_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
os.replace(TMP_CSV, INPUT_CSV)
Try this definitely work.
SELECT p.PersonID AS person_id,
p.Name, p.SS,
f.FearID AS fear_id,
f.Fear
FROM person_fear AS pf
LEFT JOIN persons AS p ON pf.PersonID = p.PersonID
LEFT JOIN fears AS f ON pf.PersonID = f.FearID
WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID
@EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5
@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles(profiles = "localtest")
class TestActiveProfile {
@Test
void testActiveProfile(){
}
}
[0-9]{4,6}
can be shortened to \d{4,6}
rules: {
cname: {
required: true,
minlength: 2
}
},
messages: {
cname: {
required: "<li>Please enter a name.</li>",
minlength: "<li>Your name is not long enough.</li>"
}
}
Short answer:
sudo apt-get install php7.2-json
(or php7.1-json
or php5-json
depending on the PHP version you're running)
Then of course make sure you restart Apache:
sudo service apache2 restart
Or if you are using PHP-FPM:
sudo service php7.2-fpm restart
(Or php7.1-fpm
or php5-fpm
)
Debian has removed the previous JSON extension as of PHP 5.5rc2 due to a license conflict.
The JSON license has a clause which states:
The Software shall be used for Good, not Evil.
This causes a problem with Free Software Foundation's definition of free software which states:
The freedom to run the program, for any purpose (freedom 0).
FSF goes on to specifically list the JSON license as nonfree.
Yes it seems a bit silly. Nevertheless Debian has removed the non-compliant JSON extension, and instead offered a replacement extension that is functionally equivalent.
To be clear: PHP itself has NOT removed JSON, it's still in master. This is a distro / package manager issue.
We have not removed json and we will never release a version of php without json support built in. Any changes in 5.5 is due to whatever distro packaging you are using which we have no control over.
http://iteration99.com/2013/php-json-licensing-and-php-5-5/
http://liorkaplan.wordpress.com/2013/06/01/bye-bye-non-free-php-json-extension/
https://bugs.php.net/bug.php?id=63520
http://philsturgeon.co.uk/blog/2013/08/fud-cracker-php-55-never-lost-json-support
You would naturally use Integer#to_s(2)
, String#to_i(2)
or "%b"
in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:
def int_to_binary(x)
p = 0
two_p = 0
output = ""
while two_p * 2 <= x do
two_p = 2 ** p
output << ((two_p & x == two_p) ? "1" : "0")
p += 1
end
#Reverse output to match the endianness of %b
output.reverse
end
To check it works:
1.upto(1000) do |n|
built_in, custom = ("%b" % n), int_to_binary(n)
if built_in != custom
puts "I expected #{built_in} but got #{custom}!"
exit 1
end
puts custom
end
window.location.href = window.location.href
If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:
m {a-z A-Z}
for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.
To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}
. I don't think these bookmarks stay across different VSCode sessions though.
More vim shortcuts here.
Also make sure to use
send -- "$PWD\r"
instead, as passwords starting with a dash (-) will fail otherwise.
The above won't interpret a string starting with a dash as an option to the send command.
As this Spring's Jira ticket, it is an intentional design. But the following code works for me.
public static Map<String, Object> getAllKnownProperties(Environment env) {
Map<String, Object> rtn = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
rtn.put(key, propertySource.getProperty(key));
}
}
}
}
return rtn;
}
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
I've been using some simple CSS and it seems to remove them and work fine.
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
This tutorial from CSS Tricks explains in detail & also shows how to style them
I used following code:
The reason I used hashCode was because I was getting some garbage values appended to the ip address when I used getHostAddress
. But hashCode
worked really well for me as then I can use Formatter to get the ip address with correct formatting.
Here is the example output :
1.using getHostAddress
: ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
2.using hashCode
and Formatter
: ***** IP=238.194.77.212
As you can see 2nd methods gives me exactly what I need.
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i(TAG, "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
echo '<p class="paragrah"' . $i . '">'
There's a convenient method for this in MySql called GROUP_CONCAT. An equivalent for SQL Server doesn't exist, but you can write your own using the SQLCLR. Luckily someone already did that for you.
Your query then turns into this (which btw is a much nicer syntax):
SELECT CUSTOMFIELD, ISSUE, dbo.GROUP_CONCAT(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602
GROUP BY CUSTOMFIELD, ISSUE
But please note that this method is good for at the most 100 rows within a group. Beyond that, you'll have major performance problems. SQLCLR aggregates have to serialize any intermediate results and that quickly piles up to quite a lot of work. Keep this in mind!
Interestingly the FOR XML
doesn't suffer from the same problem but instead uses that horrendous syntax.
Honestly, I had problems with bundler circular dependencies and the best way to go is rm -rf .bundle
. Save yourselves the headache and just use the hammer.
"Proper way to declare custom exceptions in modern Python?"
This is fine, unless your exception is really a type of a more specific exception:
class MyException(Exception):
pass
Or better (maybe perfect), instead of pass
give a docstring:
class MyException(Exception):
"""Raise for my specific kind of exception"""
From the docs
Exception
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
That means that if your exception is a type of a more specific exception, subclass that exception instead of the generic Exception
(and the result will be that you still derive from Exception
as the docs recommend). Also, you can at least provide a docstring (and not be forced to use the pass
keyword):
class MyAppValueError(ValueError):
'''Raise when my specific value is wrong'''
Set attributes you create yourself with a custom __init__
. Avoid passing a dict as a positional argument, future users of your code will thank you. If you use the deprecated message attribute, assigning it yourself will avoid a DeprecationWarning
:
class MyAppValueError(ValueError):
'''Raise when a specific subset of values in context of app is wrong'''
def __init__(self, message, foo, *args):
self.message = message # without this you may get DeprecationWarning
# Special attribute you desire with your Error,
# perhaps the value that caused the error?:
self.foo = foo
# allow users initialize misc. arguments as any other builtin Error
super(MyAppValueError, self).__init__(message, foo, *args)
There's really no need to write your own __str__
or __repr__
. The builtin ones are very nice, and your cooperative inheritance ensures that you use it.
Maybe I missed the question, but why not:
class MyException(Exception):
pass
Again, the problem with the above is that in order to catch it, you'll either have to name it specifically (importing it if created elsewhere) or catch Exception, (but you're probably not prepared to handle all types of Exceptions, and you should only catch exceptions you are prepared to handle). Similar criticism to the below, but additionally that's not the way to initialize via super
, and you'll get a DeprecationWarning
if you access the message attribute:
Edit: to override something (or pass extra args), do this:
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super(ValidationError, self).__init__(message)
# Now for your custom code...
self.errors = errors
That way you could pass dict of error messages to the second param, and get to it later with e.errors
It also requires exactly two arguments to be passed in (aside from the self
.) No more, no less. That's an interesting constraint that future users may not appreciate.
To be direct - it violates Liskov substitutability.
I'll demonstrate both errors:
>>> ValidationError('foo', 'bar', 'baz').message
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
ValidationError('foo', 'bar', 'baz').message
TypeError: __init__() takes exactly 3 arguments (4 given)
>>> ValidationError('foo', 'bar').message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foo'
Compared to:
>>> MyAppValueError('foo', 'FOO', 'bar').message
'foo'
I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...
Here's what I came up with:
python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"
That's the one-liner, here's it a little more readable:
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)
This worked for downloading a tarball. I was able to extract the package and download it after downloading.
EDIT:
To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint
package, but this was tested on my machine and works fine:
#!/usr/bin/env python
from clint.textui import progress
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
total_length = int(r.headers.get('content-length'))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1):
if chunk:
f.write(chunk)
f.flush()
Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).
The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.
Please follow the steps as mentioned below.
Visit the standard URL www.visualstudio.com/downloads
Scroll down and click on encircled below as shown in snapshot down
After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Join
You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i
to rate
and using that instead. See the updated code below:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
# V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
for rate in growthRates:
# V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
fund = fund * (1 + 0.01 * rate) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
When you change your passwords in the security tab, there are two sections, one above and one below. I think the common mistake here is that others try to log-in with the account they have set "below" the one used for htaccess, whereas they should log in to the password they set on the above section. That's how I fixed mine.
Use sudo npm install -g appium
.
This is a "problem" on the client side, not really an Oracle problem.
It's the client application which formats and displays the date this way.
In your case it's SQL*Plus which does this formatting.
Other SQL clients have other defaults.
In case anyone is setting a ForeignKey
, you can just allow nullable fields without setting a default:
new_field = models.ForeignKey(model, null=True)
If you already have data stored within the database, you can also set a default value:
new_field = models.ForeignKey(model, default=<existing model id here>)
For Alpine Linux:
apk add openssl-dev
This one uses Apache commons-lang which will most likely be on your class path already:
Map<String, String> collect = Stream.of(
Pair.of("hello", "world"),
Pair.of("abc", "123"),
Pair.of("java", "eight")
).collect(Collectors.toMap(Pair::getKey, Pair::getValue));
I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.
A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.
I just make it simple:
i = [1,2,1,3]
k = 0
for ii in i:
if ii == 1 :
print ("index of 1 = ", k)
k = k+1
output:
index of 1 = 0
index of 1 = 2
first, create a new branch in the current position (in case you need your old 'screwed up' history):
git branch fubar-pin
update your list of remote branches and sync new commits:
git fetch --all
then, reset your branch to the point where origin/branch points to:
git reset --hard origin/branch
be careful, this will remove any changes from your working tree!
Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
var id = rec.get('id');
// some DELETE/GET ajax callback here...
// pass in 'id' var or some key
// inside success
grid.getStore().removeAt(rowIndex);
}
The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
You can use Guava to split the string, and convert it into an ArrayList. This works with an empty string as well, and returns an empty list.
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
String commaSeparated = "item1 , item2 , item3";
// Split string into list, trimming each item and removing empty items
ArrayList<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
System.out.println(list);
list.add("another item");
System.out.println(list);
outputs the following:
[item1, item2, item3]
[item1, item2, item3, another item]
Given your constraints, you're stuck with brute force search (or creating an index if the search will be repeated). Can you elaborate any on how the ArrayList
is generated--perhaps there is some wiggle room there.
If all you're looking for is prettier code, consider using the Apache Commons Collections classes, in particular CollectionUtils.find(), for ready-made syntactic sugar:
ArrayList haystack = // ...
final Object needleField1 = // ...
final Object needleField2 = // ...
Object found = CollectionUtils.find(haystack, new Predicate() {
public boolean evaluate(Object input) {
return needleField1.equals(input.field1) &&
needleField2.equals(input.field2);
}
});
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:
if ($('#elem').is(':visible')) {
// do something
}
You should set visibility in your CSS first though, using simply:
#elem { display: none; }
This is the shortest way
String mPhoneNumber = "+972505555555";
mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
String mMessage = "Hello world";
String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
mSendToWhatsApp
)));
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
I solved it simply by removing the domain from the request url.
Before: https://some.domain.com/_vti_bin/service.svc
After: /_vti_bin/service.svc
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
With regard to the specific question of generating a reverse IntStream
:
starting from Java 9 you can use the three-argument version of the IntStream.iterate(...)
:
IntStream.iterate(10, x -> x >= 0, x -> x - 1).forEach(System.out::println);
// Out: 10 9 8 7 6 5 4 3 2 1 0
where:
IntStream.iterate?(int seed, IntPredicate hasNext, IntUnaryOperator next);
seed
- the initial element;hasNext
- a predicate to apply to elements to determine when the
stream must terminate;next
- a function to be applied to the previous element to produce a
new element.Can't. Interfaces don't exist at runtime.
Create a variable of the type and use Object.keys
on it
Conroy's answer was right. In the case you need only stuff from body tag, just use:
$('#my_iframe').contents().find('body').html();
The stack is just a way that programs and functions use memory.
The stack always confused me, so I made an illustration:
Hope it's more helpful than confusing.
Feel free to use the SVG image (CC0 licensed).
restarting IIS solved the same issue in my case. Seems like something fails in IIS. Didn't worth my panic, either.
IIS 7.5, btw.
This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/
sequence(1, 2).map(toString); // lazily returns "1", "2"
Thanks to @a_horse_with_no_name's comment, I changed my PGPORT definition to 5432 in pg_env.sh. That fixed the problem for me. I don't know why postgres set it as 5433 initially when it was hosting the service at 5432.
Should have checked, Once I included the jQuery UI Library it worked fine and was animating...
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
Use
ls | % {(get-date) - $_.LastWriteTime }
It can work to retrieve the diff. You can replace ls
with a single file.
The shortest:
let arr = [...Array(10)];
console.log(arr);
_x000D_
To combine bitmasks you want to use bitwise-or. In the trivial case where every value you combine has exactly 1 bit on (like your example), it's equivalent to adding them. If you have overlapping bits however, or'ing them handles the case gracefully.
To decode the bitmasks you and your value with a mask, like so:
if(val & (1<<1)) SusanIsOn();
if(val & (1<<2)) BobIsOn();
if(val & (1<<3)) KarenIsOn();
For Color :
[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
For Image
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar_320X44.png"] forBarMetrics:UIBarMetricsDefault];
inserting data form one table to another table in different DATABASE
insert into DocTypeGroup
Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType
from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup
RUN
- command triggers while we build the docker image.
CMD
- command triggers while we launch the created docker image.
How about an extension method that doesn't use regex.
If you do stick to one of the Regex options at least use RegexOptions.Compiled
in the static variable.
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
This builds on Usman Zafar's answer converted to a method group.
Super late to this thread but here goes.
TLDR; Add the following block in your AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
// HERE: replace "Verlag" with your font
[[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
....
}
A few ways you can do this outside of using a plugin like react-native-global-props
so Ill walk you though step by step.
First let's create a location for our assets. Let's make the following directory at our root.
```
ios/
static/
fonts/
```
Now let's add a "React Native" NPM in our package.json
"rnpm": {
"static": [
"./static/fonts/"
]
}
Now we can run "react-native link" to add our assets to our native apps.
That should add your font names into the projects .plist
(for VS code users run code ios/*/Info.plist
to confirm)
Here let's assume Verlag
is the font you added, it should look something like this:
<dict>
<plist>
.....
<key>UIAppFonts</key>
<array>
<string>Verlag Bold Italic.otf</string>
<string>Verlag Book Italic.otf</string>
<string>Verlag Light.otf</string>
<string>Verlag XLight Italic.otf</string>
<string>Verlag XLight.otf</string>
<string>Verlag-Black.otf</string>
<string>Verlag-BlackItalic.otf</string>
<string>Verlag-Bold.otf</string>
<string>Verlag-Book.otf</string>
<string>Verlag-LightItalic.otf</string>
</array>
....
</dict>
</plist>
Now that you mapped them, now let's make sure they are actually there and being loaded (this is also how you'd do it manually).
Go to "Build Phase" > "Copy Bundler Resource"
, If it didn't work you'll a manually add under them here.
First open your XCode logs, like:
Then you can add the following block in your AppDelegate.m
to log the names of the Fonts and the Font Family.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
.....
for (NSString* family in [UIFont familyNames])
{
NSLog(@"%@", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(@" %@", name);
}
}
...
}
Once you run you should find your fonts if loaded correctly, here we found ours in logs like this:
2018-05-07 10:57:04.194127-0700 MyApp[84024:1486266] Verlag
2018-05-07 10:57:04.194266-0700 MyApp[84024:1486266] Verlag-Book
2018-05-07 10:57:04.194401-0700 MyApp[84024:1486266] Verlag-BlackItalic
2018-05-07 10:57:04.194516-0700 MyApp[84024:1486266] Verlag-BoldItalic
2018-05-07 10:57:04.194616-0700 MyApp[84024:1486266] Verlag-XLight
2018-05-07 10:57:04.194737-0700 MyApp[84024:1486266] Verlag-Bold
2018-05-07 10:57:04.194833-0700 MyApp[84024:1486266] Verlag-Black
2018-05-07 10:57:04.194942-0700 MyApp[84024:1486266] Verlag-XLightItalic
2018-05-07 10:57:04.195170-0700 MyApp[84024:1486266] Verlag-LightItalic
2018-05-07 10:57:04.195327-0700 MyApp[84024:1486266] Verlag-BookItalic
2018-05-07 10:57:04.195510-0700 MyApp[84024:1486266] Verlag-Light
So now we know it loaded the Verlag
family and are the fonts inside that family
Verlag-Book
Verlag-BlackItalic
Verlag-BoldItalic
Verlag-XLight
Verlag-Bold
Verlag-Black
Verlag-XLightItalic
Verlag-LightItalic
Verlag-BookItalic
Verlag-Light
These are now the case sensitive names we can use in our font family we can use in our react native app.
Then to set a default font to add your font family name in your AppDelegate.m
with this line
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
// ADD THIS LINE (replace "Verlag" with your font)
[[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
....
}
Done.
The following code will work for google apiv2:
public void convertAddress() {
if (address != null && !address.isEmpty()) {
try {
List<Address> addressList = geoCoder.getFromLocationName(address, 1);
if (addressList != null && addressList.size() > 0) {
double lat = addressList.get(0).getLatitude();
double lng = addressList.get(0).getLongitude();
}
} catch (Exception e) {
e.printStackTrace();
} // end catch
} // end if
} // end convertAddress
Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.
Source Link
For Android
Calendar.getInstance().getTime() gives
Thu Jul 26 15:54:13 GMT+05:30 2018
Use
String oldDate = "Thu Jul 26 15:54:13 GMT+05:30 2018";
DateFormat format = new SimpleDateFormat("EEE LLL dd HH:mm:ss Z yyyy");
Date updateLast = format.parse(oldDate);
In 3.2 and later, Python saves .pyc compiled byte code files in a sub-directory named __pycache__
located in the directory where your source files reside with filenames that identify the Python version that created them (e.g. script.cpython-33.pyc)
My problem had a slightly different solution. The directory in which brew wanted to create the symlinks were not owned by the current user.
ls -la /usr/local/bin/lib/node | grep node
yielded:
drwxr-xr-x 3 24561 wheel 102 May 4 2012 node
drwxr-xr-x 7 24561 wheel 238 Sep 18 16:37 node_modules
For me, the following fixed it:
sudo chown $(users) /usr/local/bin/lib/node_modules
sudo chown $(users) /usr/local/bin/lib/node
ps. $(users)
will get expanded to your username, went a little out of my way to help out lazy copy pasters ;)
I am using React Bootstrap, which is based on Bootstrap 4. The approach is to use Sass, simliar to Nelson Rothermel's answer above.
The idea is to override Bootstraps Sass variable for font family in your custom Sass file. If you are using Google Fonts, then make sure you import it at the top of your custom Sass file.
For example, my custom Sass file is called custom.sass
with the following content:
@import url('https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap');
$font-family-sans-serif: "Dancing Script", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;
I simply added the font I want to the front of the default values, which can be found in ..\node_modules\boostrap\dist\scss\_variables.scss
.
How the custom.scss
file is used is shown here, which is obtained from here, which is obtained from here...
Because the React app is created by the Create-React-App utility, there's no need to go through all the crufts like Gulp; I just saved the files and React will compile the Sass for me automagically behind the scene.
I believe if you change the value of the ComSpec environment variable to %SystemRoot%system32\cmd.exe
(CMD) then it doesn't matter if the file extension is .BAT
or .CMD
. I'm not sure, but this may even be the default for WinXP and above.
Unfortunately, you may have to override this:
In Objective-C:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
In Swift:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
Try something like this:
In Objective-C:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UILabel *myLabel = [[UILabel alloc] init];
myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont boldSystemFontOfSize:18];
myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
In Swift:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let myLabel = UILabel()
myLabel.frame = CGRect(x: 20, y: 8, width: 320, height: 20)
myLabel.font = UIFont.boldSystemFont(ofSize: 18)
myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
let headerView = UIView()
headerView.addSubview(myLabel)
return headerView
}
I encounter this issue when I first run LEMP on centos7 refer to this post.
I restart nginx to test the phpinfo page, but get this
http://xxx.xxx.xxx.xxx/info.php is not unreachable now.
Then I use tail -f /var/log/nginx/error.log
to see more info. I find is the
php-fpm.sock file not exist. Then I reboot the system, everything is OK.
Here may not need to reboot the system as Fath's post, just reload nginx and php-fpm.
Try this in your constructor
MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);
async-await
syntax works perfectly for something like the following...
changeStateFunction = () => {
// Some Worker..
this.setState((prevState) => ({
year: funcHandleYear(),
month: funcHandleMonth()
}));
goNextMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
goPrevMonth = async () => {
await this.changeStateFunction();
const history = createBrowserHistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.
I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach()
(because it is "iterable") which eliminates the need to maked iterated _fetch()
calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id']
)
OK, so I found the solution here: targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout
I should have searched for targetContentOffsetForProposedContentOffset
in the begining.
You could inspect the available apache2 modules:
$ ls /usr/lib/apache2/modules/
Or try to enable the php module, if you have the appropriate access:
$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..
Assuming you don't want to make it a block element, then you might try:
.title {
display: inline-block; /* which allows you to set the height/width; but this isn't cross-browser, particularly as regards IE < 7 */
line-height: 2em; /* or */
padding-top: 1em;
padding-bottom: 1em;
}
But the easiest solution is to simply treat the .title
as a block-level element, and using the appropriate heading tags <h1>
through <h6>
.
You can also use a fadeIn/FadeOut Combo, too....
$('.test').bind('click', function(){
$('.div1').fadeIn(500);
$('.div2').fadeOut(500);
$('.div3').fadeOut(500);
return false;
});
Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.
If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.
What about this simple approach. Its working fine for me.
extension UITextField {
func charactersLimit(to:Int) {
if (self.text!.count > to) {
self.deleteBackward()
}
}
}
Then:
someTextField.charactersLimit(to:16)
This replaces the beginning of each line with "//":
:%s!^!//!
This replaces the beginning of each selected line (use visual mode to select) with "//":
:'<,'>s!^!//!
Note that gv
(in normal mode) restores the last visual selection, this comes in handy from time to time.
dict2 = dict1
does not copy the dictionary. It simply gives you the programmer a second way (dict2
) to refer to the same dictionary.
You can use varargs
public function yourFunction(Parameter... parameters)
See also
It would be O(n log n) if you built the heap by repeatedly inserting elements. However, you can create a new heap more efficiently by inserting the elements in arbitrary order and then applying an algorithm to "heapify" them into the proper order (depending on the type of heap of course).
See http://en.wikipedia.org/wiki/Binary_heap, "Building a heap" for an example. In this case you essentially work up from the bottom level of the tree, swapping parent and child nodes until the heap conditions are satisfied.
Adapted from CodeReview, here is a variant which works with num=1
!
from itertools import product
import operator
def prod(ls):
return reduce(operator.mul, ls, 1)
def powered(factors, powers):
return prod(f**p for (f,p) in zip(factors, powers))
def divisors(num) :
pf = dict(prime_factors(num))
primes = pf.keys()
#For each prime, possible exponents
exponents = [range(i+1) for i in pf.values()]
return (powered(primes,es) for es in product(*exponents))
http://pinvoke.net/default.aspx/user32.EnumDesktopWindows
There is an example of using user.dll's EnumWindow in C# to list all open windows.
Not sure of exact syntax (you use varchar2 type which means not SQL Server hence TOP) but you can use the LIMIT keyword for MySQL:
Select * FROM test_table WHERE user_id = value
ORDER BY DATE_ADDED DESC LIMIT 1
Or rownum in Oracle
SELECT * FROM
(Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)
WHERE rnum = 1
If DB2, I'm not sure whether it's TOP, LIMIT or rownum...
Just for a more animated and cute solution:
$(window).scroll(function(){
$("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});
And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb
Update: and a non-animated jQuery solution:
$(window).scroll(function(){
$("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});
Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football)
You want it to read (SPORT == 'Football')
, so your format string needs to be @"(SPORT == '%@')"
.
I would like to say that you must always use jQuery latest or recent stable versions. However if you need to do some work with others versions then you can add that version and renamed the $
to some other name. For instance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>var $oldjQuery = $.noConflict(true);</script>
Look here if you write something using $
then you will get the latest version. But if you need to do anything with old then just use$oldjQuery
instead of $
.
Here is an example
$(function(){console.log($.fn.jquery)});
$oldjQuery (function(){console.log($oldjQuery.fn.jquery)})
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
you can git fetch nameofremoterepo
, then git log
and personally, I alias gitlog
to git log --graph --oneline --pretty --decorate --all
. try out and see if it fits you
There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="10">
<rect x="10" y="10" height="100" width="100" style="stroke:#ff0000;fill: #0000ff"/>
</svg>
<svg x="200">
<rect x="10" y="10" height="100" width="100" style="stroke:#009900;fill: #00cc00"/>
</svg>
</svg>
The two rectangles are identical (apart from the colors), but the parent svg elements have different x values.
** Here myTF is outlet for MT TEXT FIELD **
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: self.myTF.frame.size.height - width, width: self.myTF.frame.size.width, height: self.myTF.frame.size.height)
border.borderWidth = width
self.myTF.layer.addSublayer(border)
self.myTF.layer.masksToBounds = true
In my case I'm using the ObjectContext as opposed to the DbContext so I tweaked the code in the accepted answer for that purpose.
public static class ConnectionTools
{
public static void ChangeDatabase(
this ObjectContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? Source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}
I think you can use typeahead.js
. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.
SQL Server 2008 And Up
Just filter a unique index:
CREATE UNIQUE NONCLUSTERED INDEX UQ_Party_SamAccountName
ON dbo.Party(SamAccountName)
WHERE SamAccountName IS NOT NULL;
In Lower Versions, A Materialized View Is Still Not Required
For SQL Server 2005 and earlier, you can do it without a view. I just added a unique constraint like you're asking for to one of my tables. Given that I want uniqueness in column SamAccountName
, but I want to allow multiple NULLs, I used a materialized column rather than a materialized view:
ALTER TABLE dbo.Party ADD SamAccountNameUnique
AS (Coalesce(SamAccountName, Convert(varchar(11), PartyID)))
ALTER TABLE dbo.Party ADD CONSTRAINT UQ_Party_SamAccountName
UNIQUE (SamAccountNameUnique)
You simply have to put something in the computed column that will be guaranteed unique across the whole table when the actual desired unique column is NULL. In this case, PartyID
is an identity column and being numeric will never match any SamAccountName
, so it worked for me. You can try your own method—be sure you understand the domain of your data so that there is no possibility of intersection with real data. That could be as simple as prepending a differentiator character like this:
Coalesce('n' + SamAccountName, 'p' + Convert(varchar(11), PartyID))
Even if PartyID
became non-numeric someday and could coincide with a SamAccountName
, now it won't matter.
Note that the presence of an index including the computed column implicitly causes each expression result to be saved to disk with the other data in the table, which DOES take additional disk space.
Note that if you don't want an index, you can still save CPU by making the expression be precalculated to disk by adding the keyword PERSISTED
to the end of the column expression definition.
In SQL Server 2008 and up, definitely use the filtered solution instead if you possibly can!
Controversy
Please note that some database professionals will see this as a case of "surrogate NULLs", which definitely have problems (mostly due to issues around trying to determine when something is a real value or a surrogate value for missing data; there can also be issues with the number of non-NULL surrogate values multiplying like crazy).
However, I believe this case is different. The computed column I'm adding will never be used to determine anything. It has no meaning of itself, and encodes no information that isn't already found separately in other, properly defined columns. It should never be selected or used.
So, my story is that this is not a surrogate NULL, and I'm sticking to it! Since we don't actually want the non-NULL value for any purpose other than to trick the UNIQUE
index to ignore NULLs, our use case has none of the problems that arise with normal surrogate NULL creation.
All that said, I have no problem with using an indexed view instead—but it brings some issues with it such as the requirement of using SCHEMABINDING
. Have fun adding a new column to your base table (you'll at minimum have to drop the index, and then drop the view or alter the view to not be schema bound). See the full (long) list of requirements for creating an indexed view in SQL Server (2005) (also later versions), (2000).
Update
If your column is numeric, there may be the challenge of ensuring that the unique constraint using Coalesce
does not result in collisions. In that case, there are some options. One might be to use a negative number, to put the "surrogate NULLs" only in the negative range, and the "real values" only in the positive range. Alternately, the following pattern could be used. In table Issue
(where IssueID
is the PRIMARY KEY
), there may or may not be a TicketID
, but if there is one, it must be unique.
ALTER TABLE dbo.Issue ADD TicketUnique
AS (CASE WHEN TicketID IS NULL THEN IssueID END);
ALTER TABLE dbo.Issue ADD CONSTRAINT UQ_Issue_Ticket_AllowNull
UNIQUE (TicketID, TicketUnique);
If IssueID 1 has ticket 123, the UNIQUE
constraint will be on values (123, NULL). If IssueID 2 has no ticket, it will be on (NULL, 2). Some thought will show that this constraint cannot be duplicated for any row in the table, and still allows multiple NULLs.
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
Use org.junit.Assert's method assertArrayEquals
:
import org.junit.Assert;
...
Assert.assertArrayEquals( expectedResult, result );
If this method is not available, you may have accidentally imported the Assert class from junit.framework
.
Try this for immediate child elements of type div
$("#foo > div")[0].children.length
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
In WinForm, we can always get the Control Key status by:
bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;
Actually the best answer is
SELECT CONVERT(VARCHAR(1000), varbinary_value, 1);
using "2
" cuts off the "0x
" at the start of the varbinary
.
Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
Here I have added code, the way you want line by line.
The .=
helps you to echo multiple lines of code.
$html = '<div>';
$html .= '<h3><a href="#">First</a></h3>';
$html .= '<div>Lorem ipsum dolor sit amet.</div>';
$html .= '</div>';
$html .= '<div>';
echo $html;
Starting with your data frame DF
, you could use the data.table
package:
library(data.table)
## EDIT: As suggested by @MichaelChirico, setDT converts a
## data.frame to a data.table by reference and is preferred
## if you don't mind losing the data.frame
setDT(DF)
# EDIT: To get the column name 'Mean':
DF[, .(Mean = rowMeans(.SD)), by = ID]
# ID Mean
# [1,] A 3.666667
# [2,] B 4.333333
# [3,] C 3.333333
# [4,] D 4.666667
# [5,] E 4.333333
HashMaps gives you freedom of synchronization and debugging is lot more easier
I got it and explained in below:
//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;
<table id="tableID" class="table table-condensed">
<thead>
<tr>
<th><label>From Group</lable></th>
<th><label>To Group</lable></th>
<th><label>Level</lable></th>
</tr>
</thead>
<tbody>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>
//call on click of Save button;
$('#saveDtls').click(function(event) {
var TableData = []; //initialize array;
var data=""; //empty var;
//Here traverse and read input/select values present in each td of each tr, ;
$("table#tableID > tbody > tr").each(function(row, tr) {
TableData[row]={
"fromGroup": $('td:eq(0) select',this).val(),
"toGroup": $('td:eq(1) input',this).val(),
"level": $('td:eq(2) input',this).val()
};
//Convert tableData array to JsonData
data=JSON.stringify(TableData)
//alert('data'+data);
});
});
As described in Cloaking your ASP.NET MVC Web Application on IIS 7, you can turn off the X-AspNet-Version header by applying the following configuration section to your web.config:
<system.web>
<httpRuntime enableVersionHeader="false"/>
</system.web>
and remove the X-AspNetMvc-Version header by altering your Global.asax.cs as follows:
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
As described in Custom Headers You can remove the "X-Powered-By" header by applying the following configuration section to your web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
</customHeaders>
</httpProtocol>
</system.webServer>
There is no easy way to remove the "Server" response header via configuration, but you can implement an HttpModule
to remove specific HTTP Headers as described in Cloaking your ASP.NET MVC Web Application on IIS 7 and in how-to-remove-server-x-aspnet-version-x-aspnetmvc-version-and-x-powered-by-from-the-response-header-in-iis7.
Plot the statistical autocorrelation given a pandas datatime Series of returns:
import matplotlib.pyplot as plt
def plot_autocorr(returns, lags):
autocorrelation = []
for lag in range(lags+1):
corr_lag = returns.corr(returns.shift(-lag))
autocorrelation.append(corr_lag)
plt.plot(range(lags+1), autocorrelation, '--o')
plt.xticks(range(lags+1))
return np.array(autocorrelation)
0 */1 * * * “At minute 0 past every hour.”
0 */2 * * * “At minute 0 past every 2nd hour.”
This is the proper way to set cronjobs for every hr.
Just one more alternative using URL
var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
You can give tooltipTemplate a function, and format the tooltip as you wish:
tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}
Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.
The key part is that I am reducing the scope of the problem: I forbid indirect execution of the script via the path (as in /bin/sh [script path relative to path component]
).
This can be detected because $0
will be a relative path which does not resolve to any file relative to the current folder. I believe that direct execution using the #!
mechanism always results in an absolute $0
, including when the script is found on the path.
I also require that the pathname and any pathnames along a chain of symbolic links only contain a reasonable subset of characters, notably not \n
, >
, *
or ?
. This is required for the parsing logic.
There are a few more implicit expectations which I will not go into (look at this answer), and I do not attempt to handle deliberate sabotage of $0
(so consider any security implications). I expect this to work on almost any Unix-like system with a Bourne-like /bin/sh
.
#!/bin/sh
(
path="${0}"
while test -n "${path}"; do
# Make sure we have at least one slash and no leading dash.
expr "${path}" : / > /dev/null || path="./${path}"
# Filter out bad characters in the path name.
expr "${path}" : ".*[*?<>\\]" > /dev/null && exit 1
# Catch embedded new-lines and non-existing (or path-relative) files.
# $0 should always be absolute when scripts are invoked through "#!".
test "`ls -l -d "${path}" 2> /dev/null | wc -l`" -eq 1 || exit 1
# Change to the folder containing the file to resolve relative links.
folder=`expr "${path}" : "\(.*/\)[^/][^/]*/*$"` || exit 1
path=`expr "x\`ls -l -d "${path}"\`" : "[^>]* -> \(.*\)"`
cd "${folder}"
# If the last path was not a link then we are in the target folder.
test -n "${path}" || pwd
done
)
i use this based on max solution
def getPath(filename):
import os
import sys
from os import chdir
from os.path import join
from os.path import dirname
from os import environ
if hasattr(sys, '_MEIPASS'):
# PyInstaller >= 1.6
chdir(sys._MEIPASS)
filename = join(sys._MEIPASS, filename)
elif '_MEIPASS2' in environ:
# PyInstaller < 1.6 (tested on 1.5 only)
chdir(environ['_MEIPASS2'])
filename = join(environ['_MEIPASS2'], filename)
else:
chdir(dirname(sys.argv[0]))
filename = join(dirname(sys.argv[0]), filename)
return filename
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):
margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/
A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.
It seems everybody has different solution. I solved my problem like:
When I install 64bit mingw it installed itself to : "C:\Program Files\mingw-w64\x86_64-5.1.0-posix-seh-rt_v4-rev0\mingw64\bin"
Eventhough mingw-make.exe was under the path above, one invalid charecter or long path name confused CMake. I try to add path to environment path, try to give CMAKE as paramater it didn't work for me .
Finally I moved complex path of mingw-w64 to "C:/mingw64", than set the environment path, restarted CMake. Problem solved for me .
this will help newbees also.
just adding more details to @coder_For_Life22's answer.
if this answer helps you don't forget to upvote. it motivates us.
for this you must already know the path of the app's keystore file and password
for this example consider the key is stored at "c:\keystorekey\new.jks"
1. open this page https://code.google.com/archive/p/openssl-for-windows/downloads
2. download 32 or 64 bit zip file as per your windows OS.
3. extract the downloaded file where ever you want and remember the path.
4. for this example we consider that you have extracted the folder in download folder.
so the file address will be "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe";
5. now on keyboard press windows+r button.
6. this will open run box.
7. type cmd and press Ctrl+Shift+Enter.
8. this will open command prompt as administrator.
9. here navigate to java's bin folder:
if you use jre provided by Android Studio you will find the path as follows:
a. open android studio.
b. file->project structure
c. in the left pane, click 'SDK location'
d. in the right pane, below 'JDK location' is your jre path.
e. add "\bin" at the end of this path as the file "keytool.exe", we need, is inside this folder.
for this example i consider, you have installed java separately and following is the path
"C:\Program Files\Java\jre-10.0.2\bin"
if you have installed 32bit java it will be in
"C:\Program Files (x86)\Java\jre-10.0.2\bin"
10. now with above paths execute command as following:
keytool -exportcert -alias androiddebugkey -keystore "c:\keystorekey\new.jks" | "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary |"C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" base64
errors:
if you get:
---
'keytool' is not recognized as an internal or external command
---
this means that java is installed somewhere else.
For the most part you just set the .val() method. All of the answers are pretty accurate, just wanted to post my results to anyone who may need to set the value via the client id that gets rendered.
$('#' + '<%= doc_title.ClientID %>').val(null);
Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
def send_mail(send_from: str, subject: str, text: str,
send_to: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="smtp.gmail.com", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Usage:
username = '[email protected]'
password = 'top-secret'
default_address = ['[email protected]']
send_mail(send_from= username,
subject="test",
text="text",
send_to= None,
files= # pass a list with the full filepaths here...
)
To use with any other email provider, just change the smtp configurations.
Just use sapply
> sapply(airquality, function(x) sum(is.na(x)))
Ozone Solar.R Wind Temp Month Day
37 7 0 0 0 0
You could also use apply
or colSums
on the matrix created by is.na()
> apply(is.na(airquality),2,sum)
Ozone Solar.R Wind Temp Month Day
37 7 0 0 0 0
> colSums(is.na(airquality))
Ozone Solar.R Wind Temp Month Day
37 7 0 0 0 0
By itself, document.activeElement
can still return an element if the document isn't focused (and thus nothing in the document is focused!)
You may want that behavior, or it may not matter (e.g. within a keydown
event), but if you need to know something is actually focused, you can additionally check document.hasFocus()
.
The following will give you the focused element if there is one, or else null
.
var focused_element = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focused_element = document.activeElement;
}
To check whether a specific element has focus, it's simpler:
var input_focused = document.activeElement === input && document.hasFocus();
To check whether anything is focused, it's more complex again:
var anything_is_focused = (
document.hasFocus() &&
document.activeElement !== null &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
);
Robustness Note: In the code where it the checks against document.body
and document.documentElement
, this is because some browsers return one of these or null
when nothing is focused.
It doesn't account for if the <body>
(or maybe <html>
) had a tabIndex
attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow.
Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable.
I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there.
You could also remove the || null
part if you don't mind getting false
in some cases. (You could still get null
if document.activeElement
is null
):
var focused_element = (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement &&
document.activeElement
) || null;
For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state:
var input_focused = false;
input.addEventListener("focus", function() {
input_focused = true;
});
input.addEventListener("blur", function() {
input_focused = false;
});
You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.
public static <E> E[] appendToArray(E[] array, E item) { ...
Note the <E>
.
Static generic methods need their own generic declaration (public static <E>
) separate from the class's generic declaration (public class ArrayUtils<E>
).
If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_
):
String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");
This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.
[EXCEL PROFESSIONAL PLUS 2016, 32BITS, VERSION 1802, BUILD 9029.2167]
I was having the same issue and I could solve the problem by customizing the display scaling in windows 10, 64 bits. It is extremelly simple and it works for a single user. Just follow the instructions below and you will have all the Form Controls, sheet shapes, figures and ActiveX Controls back to their original size. No need to coding or doing advanced trickery/wizardry/hacks. If the provided link is broken, just repeat these steps.
To Set Display Custom Scaling in Windows 10, you need to do the following.
Open Settings.
It is an old post, but I hope it helps anyone who is dealing with this annoying and stressing Excel problem.
https://winaero.com/blog/set-display-custom-scaling-windows-10/
To quote from man rand :
The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So, with no seed value, rand()
assumes the seed as 1 (every time in your case) and with the same seed value, rand()
will produce the same sequence of numbers.
Jon Skeet created a SmartEnumerable<T>
type a while back to solve this exact issue. You can see it's implementation here:
http://codeblog.jonskeet.uk/2007/07/27/smart-enumerations/
To download: http://www.yoda.arachsys.com/csharp/miscutil/
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
function disableItems(divSelector){
var disableInputs = $(divSelector).find(":input").not("[disabled]");
disableInputs.attr("data-reenable", true);
disableInputs.attr("disabled", true);
}
function reEnableItems(divSelector){
var reenableInputs = $(divSelector).find("[data-reenable]");
reenableInputs.removeAttr("disabled");
reenableInputs.removeAttr("data-reenable");
}
well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper.
void main(){
float bug=0.0;
vec3 tile=texture2D(colMap, coords.st).xyz;
vec4 col=vec4(tile, 1.0);
if(something) bug=1.0;
col.x+=bug;
gl_FragColor=col;
}
Im under the impression that theres no way to do this, it would be nice though.
You can achieve a similar result by having a Alarm_last_set_time recorded somewhere, and having a On_boot_starter BroadcastReciever:BOOT_COMPLETED kinda thing.
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
if(session_status()!=PHP_SESSION_ACTIVE) session_start()
In the code of the button that saves the changes to the database eg the update button, add the following lines of code:
MyDataGridView.DataSource = MyTableBindingSource
MyDataGridView.Update()
MyDataGridView.RefreshEdit()
There are two options:
First
You can also use like is()
$('#dropDownId').is(':disabled');
Second
Using == true
by checking if the attributes value is disabled
. attr()
$('#dropDownId').attr('disabled');
whatever you feel fits better , you can use :)
Cheers!
Here's a list of the registered URI schemes. Each one has an RFC - a document defining it, which is almost a standard. The RFC tells the developers of new applications (such as browsers, ftp clients, etc.) what they need to support. If you need a new base-level protocol, you can use an unregistered one. The other answers tell you how. Please keep in mind you can do lots of things with the existing protocols, thus gaining their existing implementations.
The git cherry-pick <commit>
command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.
Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)
Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.
Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send
System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:
Here is what the trace log looked like on the machine where the client certificate failed.
System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.
Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL
Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)
After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.
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
Just an update to the Java 8 version
public Map<String, List<String>> splitQuery(URL url) {
if (Strings.isNullOrEmpty(url.getQuery())) {
return Collections.emptyMap();
}
return Arrays.stream(url.getQuery().split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, **Collectors**.mapping(Map.Entry::getValue, **Collectors**.toList())));
}
mapping and toList() methods have to be used with Collectors which was not mentioned in the top answer. Otherwise it would throw compilation error in IDE
Try this code:
preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);
Using /
as a delimiter means you also need to escape it here, like so: <\/a>.
UPDATE
preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';
Might not be the best way...
Removing some unnecessary SQL and then COUNT(*)
will be faster than SQL_CALC_FOUND_ROWS
. Example:
SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name
Then count without unnecessary part:
SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'
Try this
int parentWidth = ((parentViewType)childView.getParent()).getWidth();
int parentHeight = ((parentViewType)childView.getParent()).getHeight();
then you can use LinearLayout.LayoutParams for setting the chileView's parameters
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(childWidth,childLength);
childView.setLayoutParams(params);
This works well with most CSS properties if there are no hyphens in them.
var element = document.createElement('select');
element.style.width = "100px";
For properties with hyphens in them like max-width
, you should convert the sausage-case
to camelCase
var element = document.createElement('select');
element.style.maxWidth = "100px";
If the radio buttons are added dynamically, you may wish to use this
$(document).on('change', 'input[type=radio][name=bedStatus]', function (event) {
switch($(this).val()) {
case 'allot' :
alert("Allot Thai Gayo Bhai");
break;
case 'transfer' :
alert("Transfer Thai Gayo");
break;
}
});
INSERT INTO #Temp1
SELECT val1, val2
FROM TABLE1
UNION
SELECT val1, val2
FROM TABLE2
I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)
To resolve this during development, I used
request.session.flush()
It's as simple as this:
unsigned int foo;
int bar = 10;
foo = (unsigned int)bar;
Or vice versa...
The WCF API in .NET handles missing parameters by returning an HTTP 404
"Endpoint Not Found" error, when using the webHttpBinding.
The 404 Not Found
can make sense if you consider your web service method name together with its parameter signature. That is, if you expose a web service method LoginUser(string, string)
and you request LoginUser(string)
, the latter is not found.
Basically this would mean that the web service method you are calling, together with the parameter signature you specified, cannot be found.
10.4.5 404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.
The 400 Bad Request
, as Gert suggested, remains a valid response code, but I think it is normally used to indicate lower-level problems. It could easily be interpreted as a malformed HTTP request, maybe missing or invalid HTTP headers, or similar.
10.4.1 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
I do not think that every database has auto-update timestamps (e.g. Postgres). So I've decided to update this field manually everywhere in my code. This will work with every database:
thingy.setLastTouched(new Date());
HibernateUtil.save(thingy);
There are reasons to use triggers, but for most projects, this is not one of them. Triggers dig you even deeper into a specific database implementation.
MySQL 5.6.28 (Ubuntu 15.10, OpenJDK 64-Bit 1.8.0_66) seems to be very forgiving, not requiring anything beyond
@Column(name="LastTouched")
MySQL 5.7.9 (CentOS 6, OpenJDK 64-Bit 1.8.0_72) only works with
@Column(name="LastTouched", insertable=false, updatable=false)
not:
FAILED: removing @Temporal
FAILED: @Column(name="LastTouched", nullable=true)
FAILED: @Column(name="LastTouched", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
My other system info (identical in both environments)
If you really don't want to use numpy
you can do something like this:
def matmult(a,b):
zip_b = zip(*b)
# uncomment next line if python 3 :
# zip_b = list(zip_b)
return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))
for col_b in zip_b] for row_a in a]
x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
y = [[1,2],[1,2],[3,4]]
import numpy as np # I want to check my solution with numpy
mx = np.matrix(x)
my = np.matrix(y)
Result:
>>> matmult(x,y)
[[12, 18], [27, 42], [42, 66], [57, 90]]
>>> mx * my
matrix([[12, 18],
[27, 42],
[42, 66],
[57, 90]])
Swift 4.2 version of SwiftArchitect's solution above (works great):
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Invocation:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
If you plan to build a full functional applications with more than a handful of features, I will suggest to jump right to using Eclipse RCP as the framework.
If your application won't grow too big or your requirements are just too unique to be handled by a normal business framework, you can safely jump with Swing.
At the end of the day, I'd suggest you to try both technologies to find the one suit you better. Like Netbeans vs Eclipse vs IntelliJ, there is no the absolute correct answer here and both frameworks have their own drawbacks.
Pro Swing:
Pro SWT:
Try casting the element you want to update to HTMLInputElement. As stated in the other answers you need to hint to the compiler that this is a specific type of HTMLElement:
var inputElement = <HTMLInputElement>document.getElementById('greet');
inputElement.value = greeter(inputValue);
You have a few options including the "Round-trip ("O") format specifier".
var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("O"));
Console.WriteLine(date1.ToString("s", System.Globalization.CultureInfo.InvariantCulture));
Output
2008-03-01T07:00:00.0000000
2008-03-01T07:00:00
However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:
DateTime has countless traps in it that are designed to give your code bugs:
1.- DateTime values with DateTimeKind.Unspecified are bad news.
2.- DateTime doesn't care about UTC/Local when doing comparisons.
3.- DateTime values are not aware of standard format strings.
4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.
I also face the same problem and strangely changing the values in php.ini did not worked for me. So I found out one more solution which worked for me.
Once mysql console is open. Enter your mysql password. and give these commands.
If you still have problems watch this video.
You can use not filter on top of missing.
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"not": {
"filter": {
"missing": {
"field": "searchField"
}
}
}
}
}
}
As a bonus for setting up a Title Case shortcut key Ctrl+kt (while holding Ctrl, press k and t), go to Preferences
--> Keybindings-User
If you have a blank file open and close with the square brackets:
[ { "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" } ]
Otherwise if you already have stuff in there, just make sure if it comes after another command to prepend a comma "," and add:
{ "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" }
You can use selectedOptions
var selectedValues = Array.from(document.getElementById('select-meal-type').selectedOptions).map(el=>el.value);
console.log(selectedValues);
_x000D_
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2" selected>Lunch</option>
<option value="3">Dinner</option>
<option value="4" selected>Snacks</option>
<option value="5">Dessert</option>
</select>
_x000D_
In my part my sql hanged up when I tried to close it while endlessly running. So what I did is I open my task manager and end task my sql query. This stop my sql and restarted it.
public async Task<Product> GetValue(int id)
{
Product Products = await _context.Products.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return Products;
}
AsNoTracking()
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
Try this function
function fieldsValidations(element) {
var isFilled = true;
var fields = $("#"+element)
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
isFilled = false;
return false;
}
});
return isFilled;
}
And use it as
$("#submit").click(function () {
if(fieldsValidations('initiate')){
$("#submit").html("<i class=\"fas fa-circle-notch fa-spin\"></i>");
}
});
Enjoy :)
var valArr = ["1","2","3"];
/* Below Code Matches current object's (i.e. option) value with the array values */
/* Returns -1 if match not found */
$("select").multiselect("widget").find(":checkbox").each(function(){
if(jQuery.inArray(this.value, valArr) !=-1)
this.click();
});
This selects the options whose value matches with values in array.
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)pls refer this https://stackoverflow.com/a/1972404/951045
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mngr.getDeviceId();
add READ_PHONE_STATE
permission to AndroidManifest.xml
Seems your selector is wrong, try using:
a.button:hover{
background: #383;
}
Your code
a.button a:hover
Means it is going to search for an a
element inside a
with class button.
Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.
Download zip file and extract it, with in that you will find mysql-connector-XXX.jar
file
If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java
Select the version you want to use and add the dependency in your pom.xml
file