ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.
That's because the browser doesn't transmit that part to the server, sorry.
You can set your hash directly to URL too.
window.location.hash = "YourHash";
The result : http://url#YourHash
I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...
// Add code below ...
function locationHashChanged(qs)
{
var q = parseQs(qs);
// ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
// YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
// THAT IS PASSED TO changeHashValue(hashQuery)
}
// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
stopHashListener();
hashValue = hashQuery;
location.hash = hashQuery;
startHashListener();
}
// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
var hashQuery = getHashQuery();
if (hashQuery == hashValue)
return;
hashValue = hashQuery;
locationHashChanged(hashQuery);
}
function parseQs(qs)
{
var q = {};
var pairs = qs.split('&');
for (var idx in pairs) {
var arg = pairs[idx].split('=');
q[arg[0]] = arg[1];
}
return q;
}
function startHashListener()
{
hashListener = setInterval(checkIfHashChanged, 1000);
}
function stopHashListener()
{
if (hashListener != null)
clearInterval(hashListener);
hashListener = null;
}
function getHashQuery()
{
return location.hash.replace(/^#/, '');
}
var hashListener = null;
var hashValue = '';//getHashQuery();
startHashListener();
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
Here's my solution for history-enabled tabs:
var tabContainer = $(".tabs"),
tabsContent = tabContainer.find(".tabsection").hide(),
tabNav = $(".tab-nav"), tabs = tabNav.find("a").on("click", function (e) {
e.preventDefault();
var href = this.href.split("#")[1]; //mydiv
var target = "#" + href; //#myDiv
tabs.each(function() {
$(this)[0].className = ""; //reset class names
});
tabsContent.hide();
$(this).addClass("active");
var $target = $(target).show();
if ($target.length === 0) {
console.log("Could not find associated tab content for " + target);
}
$target.removeAttr("id");
// TODO: You could add smooth scroll to element
document.location.hash = target;
$target.attr("id", href);
return false;
});
And to show the last-selected tab:
var currentHashURL = document.location.hash;
if (currentHashURL != "") { //a tab was set in hash earlier
// show selected
$(currentHashURL).show();
}
else { //default to show first tab
tabsContent.first().show();
}
// Now set the tab to active
tabs.filter("[href*='" + currentHashURL + "']").addClass("active");
Note the *=
on the filter
call. This is a jQuery-specific thing, and without it, your history-enabled tabs will fail.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
Ben Alman has a great jQuery plugin for dealing with this: http://benalman.com/projects/jquery-hashchange-plugin/
If you're not using jQuery it may be an interesting reference to dissect.
This will remove the trailing hash as well. eg: http://test.com/123#abc -> http://test.com/123
if(window.history.pushState) {
window.history.pushState('', '/', window.location.pathname)
} else {
window.location.hash = '';
}
For those who are looking for pure javascript solution
document.getElementById(location.hash.substring(1)).style.display = 'block'
Hope this saves you some time.
I always assumed the !
just indicated that the hash fragment that followed corresponded to a URL, with !
taking the place of the site root or domain. It could be anything, in theory, but it seems the Google AJAX Crawling API likes it this way.
The hash, of course, just indicates that no real page reload is occurring, so yes, it’s for AJAX purposes. Edit: Raganwald does a lovely job explaining this in more detail.
Looking at Biju's answer I found a working solution.
I created an extra context-file test-context.xml
:
<context:property-placeholder location="classpath:config/spring-test.properties"/>
Containing the profile:
spring.profiles.active=localtest
And loading the test with:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration(locations = {
"classpath:config/test-context.xml" })
public class TestContext {
@Test
public void testContext(){
}
}
This saves some work when creating multiple test-cases.
Another way would be to use .Net parser for HttpRequest. To do that you need to use a bit of reflection and simple class for WorkerRequest.
First create class that derives from HttpWorkerRequest (for simplicity you can use SimpleWorkerRequest):
public class MyWorkerRequest : SimpleWorkerRequest
{
private readonly string _size;
private readonly Stream _data;
private string _contentType;
public MyWorkerRequest(Stream data, string size, string contentType)
: base("/app", @"c:\", "aa", "", null)
{
_size = size ?? data.Length.ToString(CultureInfo.InvariantCulture);
_data = data;
_contentType = contentType;
}
public override string GetKnownRequestHeader(int index)
{
switch (index)
{
case (int)HttpRequestHeader.ContentLength:
return _size;
case (int)HttpRequestHeader.ContentType:
return _contentType;
}
return base.GetKnownRequestHeader(index);
}
public override int ReadEntityBody(byte[] buffer, int offset, int size)
{
return _data.Read(buffer, offset, size);
}
public override int ReadEntityBody(byte[] buffer, int size)
{
return ReadEntityBody(buffer, 0, size);
}
}
Then wherever you have you message stream create and instance of this class. I'm doing it like that in WCF Service:
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
public string Upload(Stream data)
{
HttpWorkerRequest workerRequest =
new MyWorkerRequest(data,
WebOperationContext.Current.IncomingRequest.ContentLength.
ToString(CultureInfo.InvariantCulture),
WebOperationContext.Current.IncomingRequest.ContentType
);
And then create HttpRequest using activator and non public constructor
var r = (HttpRequest)Activator.CreateInstance(
typeof(HttpRequest),
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[]
{
workerRequest,
new HttpContext(workerRequest)
},
null);
var runtimeField = typeof (HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
if (runtimeField == null)
{
return;
}
var runtime = (HttpRuntime) runtimeField.GetValue(null);
if (runtime == null)
{
return;
}
var codeGenDirField = typeof(HttpRuntime).GetField("_codegenDir", BindingFlags.Instance | BindingFlags.NonPublic);
if (codeGenDirField == null)
{
return;
}
codeGenDirField.SetValue(runtime, @"C:\MultipartTemp");
After that in r.Files
you will have files from your stream.
Use OnItemClickListener
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
When you click on a row a listener is fired. So you setOnClickListener
on the listview and use the annonymous inner class OnItemClickListener
.
You also override onItemClick
. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).
Using the position you get the item .
Edit : From your comments i assume you need to set the adapter o listview
So assuming your activity extends ListActivtiy
setListAdapter(adapter);
Or if your activity class extends Activity
ListView lv = (ListView) findViewById(R.id.listview1);
//initialize adapter
lv.setAdapter(adapter);
xargs and seq will help
function __run_times { seq 1 $1| { shift; xargs -i -- "$@"; } }
the view :
abon@abon:~$ __run_times 3 echo hello world
hello world
hello world
hello world
If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:
CSS
.linkWithImageIcon{
Display:inline-block;
}
.MyLink{
Background:#FF3300;
width:200px;
height:70px;
vertical-align:top;
display:inline-block; font-weight:bold;
}
.MyLinkText{
/*---The margin depends on how the image size is ---*/
display:inline-block; margin-top:5px;
}
HTML
<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>
if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design
You can use the following to refresh the page by clicking the back button:
window.addEventListener('popstate', () => {
location.reload();
}, false);
From the React documentation: The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture. (emphasis added)
If you have a click event listener in your React code and you don't want it to bubble up, I think what you want to do is use onClickCapture
instead of onClick
. Then you would pass the event to the handler and do event.nativeEvent.stopPropagation()
to keep the native event from bubbling up to a vanilla JS event listener (or anything that's not react).
iOS5 has support for this (Reference). If you want to invoke the native date picker you might have a an option with PhoneGap (have not tested this myself).
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Add References properly
In my case I was using a ASCX page and the aspx page that contains the ascx control is not using the references properly. I just pasted the following code and it worked :
<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>
Following code uses most efficient way of looping to check if a given number is prime.
function checkPrime(number){
if (number==2 || number==3) {
return true
}
if(number<2 ||number % 2===0){
return false
}
else{
for (let index = 3; index <= Math.sqrt(number); index=index+2) {
if (number%index===0) {
return false
}
}
}
return true
}
Check your line endings! If you see an error about the file not being found, followed by this "premature of end headers" error in your Apache log - it may be that you have Windows line endings in your script in instead of Unix style. I ran into that problem / solution.
I've had same issue, rebuilding project clears the error for me.
build -> rebuild project -> run
Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.
If you're using LESS CSS, I wrote a little mixin to move the dropdown with the connecting arrow:
.dropdown-menu-shift( @num-pixels, @arrow-position: 10px ) { // mixin to shift the dropdown menu
left: @num-pixels;
&:before { left: -@num-pixels + @arrow-position; } // triangle outline
&:after { left: -@num-pixels + @arrow-position + 1px; } // triangle internal
}
Then to move a .dropdown-menu
with an id of dropdown-menu-x
for example, you can do:
#dropdown-menu-x {
.dropdown-menu-shift( -100px );
}
Your Javascript should be
<script>
$("#intro").owlCarousel({
// Most important owl features
//Autoplay
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true
)}
</script>
User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:
Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:
Fill in the form, click next and then you automatically go to this page:
Choose to add existing files and you go to this page:
You use those commands and you upload the existing files to Bitbucket. After that, the files are online.
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
I've had the same issue before. After analyzing my code, I realized that attempting to reset the iterator inside of loops slightly increases the time complexity and it also makes the code a bit ugly.
Open the file and save the rows to a variable in memory.
# initialize list of rows
rows = []
# open the file and temporarily name it as 'my_file'
with open('myfile.csv', 'rb') as my_file:
# set up the reader using the opened file
myfilereader = csv.DictReader(my_file)
# loop through each row of the reader
for row in myfilereader:
# add the row to the list of rows
rows.append(row)
Now you can loop through rows anywhere in your scope without dealing with an iterator.
In pandas 0.20.2
you can do:
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
is_string_dtype(df['A'])
>>>> True
is_numeric_dtype(df['B'])
>>>> True
So your code becomes:
for y in agg.columns:
if (is_string_dtype(agg[y])):
treat_str(agg[y])
elif (is_numeric_dtype(agg[y])):
treat_numeric(agg[y])
Virtual scrolling is another way to improve scrolling performance when dealing with huge lists and large dataset.
One way to implement this is by using Angular Material md-virtual-repeat
as it is demonstrated on this Demo with 50,000 items
Taken straight from the documentation of virtual repeat:
Virtual repeat is a limited substitute for ng-repeat that renders only enough dom nodes to fill the container and recycling them as the user scrolls.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
This can be a pure CSS solution. Given:
<ul class="tileMe">
<li>item 1<li>
<li>item 2<li>
<li>item 3<li>
</ul>
The CSS would be:
.tileMe li {
display: inline;
float: left;
}
Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:
<li><a class="tile" href="home">item 1</a></li>
and add the following CSS:
.tile a {
display: block;
padding: 10px;
border: 1px solid red;
margin-right: 5px;
}
The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.
Requiring 900 weight is not a weirdness but a intentional restriction added by FontAwesome (since they share the same unicode but just different font-weight) so that you are not hacking your way into using the 'solid' and 'light' icons, most of which are available only in the paid 'Pro' version.
except:
accepts all exceptions, whereas
except Exception as e:
only accepts exceptions that you're meant to catch.
Here's an example of one that you're not meant to catch:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
Here's a quick list:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
except BaseException:
to point out that you know what you're doing.
All exceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception
.
\sf
function_name in psql yields editable source code of a single function.
From https://www.postgresql.org/docs/9.6/static/app-psql.html:
\sf[+] function_description This command fetches and shows the definition of the named function, in the form of a CREATE OR REPLACE FUNCTION command.
If + is appended to the command name, then the output lines are numbered, with the first line of the function body being line 1.
Simplest way:
var uriSource = new Uri("image path here");
image1.Source = new BitmapImage(uriSource);
Arrays.asList can help here:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
Try closing and reopening the file, then press Ctrl+F11
.
Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.
Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.
You are using incorrect overload. You should use this overload
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
And the correct code would be
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Note that extra parameter at the end.
For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object
overload that you are trying to use.
If you're using Cordova with Sencha Touch and you're using the normal Sencha Touch navigation/title bars, you can just stretch the navbar and reposition the content within the navbar so it looks at home on iOS 7. Just add this into app.js
(after your last Ext.Viewport.add
line) :
// Adjust toolbar height when running in iOS to fit with new iOS 7 style
if (Ext.os.is.iOS && Ext.os.version.major >= 7) {
Ext.select(".x-toolbar").applyStyles("height: 62px; padding-top: 15px;");
}
(Source: http://lostentropy.com/2013/09/22/ios-7-status-bar-fix-for-sencha-touch-apps/)
This is a bit hacky, I know, but it saves dealing with it at the Objective-C level. It won't be much good for those not using Sencha Touch with Cordova, though.
Same comment as Philip Kirkbride. It wasn't a permission issue, but using the Arduino IDE downloaded from their website solved my problem. Thanks! Michael
Add the following code before you instantiate your web service client:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Or for backward compatibility with TLS 1.1 and prior:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
Late answer, I know but I too wanted this so I could log the SQL. The following is short and meets my needs.
The following produces SQL you can copy/paste in SSMS (it replaces the parameters with the values properly). You can add more types but this meets all I use in this case.
private static void LogSQL(SqlCommand cmd)
{
string query = cmd.CommandText;
foreach (SqlParameter prm in cmd.Parameters)
{
switch (prm.SqlDbType)
{
case SqlDbType.Bit:
int boolToInt = (bool)prm.Value ? 1 : 0;
query = query.Replace(prm.ParameterName, string.Format("{0}", (bool)prm.Value ? 1 : 0));
break;
case SqlDbType.Int:
query = query.Replace(prm.ParameterName, string.Format("{0}", prm.Value));
break;
case SqlDbType.VarChar:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
default:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
}
}
// the following is my how I write to my log - your use will vary
logger.Debug("{0}", query);
return;
}
Now I can log the SQL just before I execute it:
LogSQL(queryCmd)
queryCmd.ExecuteNonQuery()
As above @niravdesai said App-prefs.
I found that App-Prefs:
works for both iOS 9, 10 and 11. devices tested.
where as prefs:
only works on iOS 9.
If you have a typescript file, you have to instruct the webpack to resolve them by using below code in webpack.config.js
module.exports={
...
resolve:{
extensions:['.ts','.tsx';]
}
}
There is also a case when you want to refresh only specific iframe on page and not the full page.
You do is as follows:
public void refreshIFrameByJavaScriptExecutor(String iFrameId){
String script= "document.getElementById('" + iFrameId+ "').src = " + "document.getElementById('" + iFrameId+ "').src";
((IJavaScriptExecutor)WebDriver).ExecuteScript(script);
}
Honestly, I have difficulty implementing it because there's barely any tutorials I've searched that displays writing the keys into the files. The accepted answer was "fine". But for me I had to improve it so that both keys gets saved into two separate files. I've written a helper class so y'all just gotta copy and paste it. Hope this helps lol.
using Microsoft.Win32;
using System;
using System.IO;
using System.Security.Cryptography;
namespace RsaCryptoExample
{
class RSAFileHelper
{
readonly string pubKeyPath = "public.key";//change as needed
readonly string priKeyPath = "private.key";//change as needed
public void MakeKey()
{
//lets take a new CSP with a new 2048 bit rsa key pair
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);
//how to get the private key
RSAParameters privKey = csp.ExportParameters(true);
//and the public key ...
RSAParameters pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
File.WriteAllText(pubKeyPath, pubKeyString);
}
string privKeyString;
{
//we need some buffer
var sw = new StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, privKey);
//get the string from the stream
privKeyString = sw.ToString();
File.WriteAllText(priKeyPath, privKeyString);
}
}
public void EncryptFile(string filePath)
{
//converting the public key into a string representation
string pubKeyString;
{
using (StreamReader reader = new StreamReader(pubKeyPath)){pubKeyString = reader.ReadToEnd();}
}
//get a stream from the string
var sr = new StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters((RSAParameters)xs.Deserialize(sr));
byte[] bytesPlainTextData = File.ReadAllBytes(filePath);
//apply pkcs#1.5 padding and encrypt our data
var bytesCipherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
string encryptedText = Convert.ToBase64String(bytesCipherText);
File.WriteAllText(filePath,encryptedText);
}
public void DecryptFile(string filePath)
{
//we want to decrypt, therefore we need a csp and load our private key
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
string privKeyString;
{
privKeyString = File.ReadAllText(priKeyPath);
//get a stream from the string
var sr = new StringReader(privKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
RSAParameters privKey = (RSAParameters)xs.Deserialize(sr);
csp.ImportParameters(privKey);
}
string encryptedText;
using (StreamReader reader = new StreamReader(filePath)) { encryptedText = reader.ReadToEnd(); }
byte[] bytesCipherText = Convert.FromBase64String(encryptedText);
//decrypt and strip pkcs#1.5 padding
byte[] bytesPlainTextData = csp.Decrypt(bytesCipherText, false);
//get our original plainText back...
File.WriteAllBytes(filePath, bytesPlainTextData);
}
}
}
I find that if you already have a specific list of values, that the way described by @S. Lotts is the best; however, the way described below works well to get all variables and Classes added throughout the code WITHOUT the need to provide variable name though you can specify them if you want. Code can be extend to exclude Classes.
import types
import math # mainly showing that you could import what you will before d
# Everything after this counts
d = dict(globals())
def kv_test(k,v):
return (k not in d and
k not in ['d','args'] and
type(v) is not types.FunctionType)
def magic_print(*args):
if len(args) == 0:
return {k:v for k,v in globals().iteritems() if kv_test(k,v)}
else:
return {k:v for k,v in magic_print().iteritems() if k in args}
if __name__ == '__main__':
foo = 1
bar = 2
baz = 3
print magic_print()
print magic_print('foo')
print magic_print('foo','bar')
Output:
{'baz': 3, 'foo': 1, 'bar': 2}
{'foo': 1}
{'foo': 1, 'bar': 2}
var listItems= "";
var jsonData = jsonObj.d;
for (var i = 0; i < jsonData.Table.length; i++){
listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
$("#<%=DLState.ClientID%>").html(listItems);
Example
<html>
<head></head>
<body>
<select id="DLState">
</select>
</body>
</html>
/*javascript*/
var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
{"stateid" : "3","statename" : "Karnataka"},
{"stateid" : "4","statename" : "Andaman and Nicobar"},
{"stateid" : "5","statename" : "Andhra Pradesh"},
{"stateid" : "6","statename" : "Arunachal Pradesh"}]}
$(document).ready(function(){
var listItems= "";
for (var i = 0; i < jsonList.Table.length; i++){
listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
}
$("#DLState").html(listItems);
});
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.
Here is an example using openssl_encrypt
//Encryption:
$textToEncrypt = "My Text to Encrypt";
$encryptionMethod = "AES-256-CBC";
$secretHash = "encryptionhash";
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);
//Decryption:
$decryptedText = openssl_decrypt($encryptedText, $encryptionMethod, $secretHash, 0, $iv);
print "My Decrypted Text: ". $decryptedText;
Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.
The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:
def keysInDict(dataDict, parent=[]):
if not isinstance(dataDict, dict):
return [tuple(parent)]
else:
return reduce(list.__add__,
[keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])
One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).
def dict_to_df(dataDict):
ret = []
for k in keysInDict(dataDict):
v = np.array( getFromDict(dataDict, k), )
v = pd.DataFrame(v)
v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
ret.append(v)
return reduce(pd.DataFrame.join, ret)
Here is how to do it in Unity:
(Modified answer from @markmuetz so be sure to upvote his answer)
int[,] rawNodes = new int[,]
{
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 }
};
private void Start()
{
int rowLength = rawNodes.GetLength(0);
int colLength = rawNodes.GetLength(1);
string arrayString = "";
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
arrayString += string.Format("{0} ", rawNodes[i, j]);
}
arrayString += System.Environment.NewLine + System.Environment.NewLine;
}
Debug.Log(arrayString);
}
More portable to use ed; some systems don't support \n in sed
printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename
CREATE SCHEMA is a synonym for CREATE DATABASE. CREATE DATABASE Syntax
I guess this is a better way to view a stored procedure's code:
sp_helptext <name of your sp>
There is a difference between hashCode() and identityHashCode() returns. It is possible that for two unequal (tested with ==) objects o1, o2 hashCode() can be the same. See the example below how this is true.
class SeeDifferences
{
public static void main(String[] args)
{
String s1 = "stackoverflow";
String s2 = new String("stackoverflow");
String s3 = "stackoverflow";
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
System.out.println(System.identityHashCode(s3));
if (s1 == s2)
{
System.out.println("s1 and s2 equal");
}
else
{
System.out.println("s1 and s2 not equal");
}
if (s1 == s3)
{
System.out.println("s1 and s3 equal");
}
else
{
System.out.println("s1 and s3 not equal");
}
}
}
This will return the matching word or an error if no match is found. For this example I used the following.
List of words to search for: G1:G7
Cell to search in: A1
=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))
Enter as an array formula by pressing Ctrl+Shift+Enter.
This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX()
function, throwing an error.
To return the row number of a matching word, you can use the following:
=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))
This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1
if no match is found.
You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i)
as parameters and perform the code there:
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
new Image().src = url[i] + $(this).attr("href");
}
}
...
success: function(data){
image_link(data, i)
}
There is no way.
This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.
If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern
attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.
For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}">
could be adequate. It is of course implementation-dependent how it will be handled.
public SmartSaverCals(Context context)
{
this.context= context;
}
add public to Your constructor.in my case problem solved
I think you can try this for calling in from a class
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
*----------------Sorry I oversight, for static function already answered the question by adrift*
System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Update
I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()
Solution (tested in static webmethod)
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
Worked
You can always do
git clone git://repo.org/fossproject.git && rm -rf fossproject/.git
df = pd.concat([df['a'], df.b.apply(pd.Series)], axis=1)
I simply use the -subj
parameter adding the machines ip address. So solved with one command only.
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -sha256 -subj '/CN=my-domain.com/subjectAltName=DNS.1=192.168.0.222/' -keyout my-domain.key -out my-domain.crt
You can add others attributes like C, ST, L, O, OU, emailAddress to generate certs without being prompted.
If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if
To prevent JUnit from instantiating your test base class just make it
public abstract class MyTestBaseClass { ... whatever... }
(@Ignore reports it as ignored which I reserve for temporarily ignored tests.)
I had the same issue but in this case microsoft-ace-oledb-12-0-provider was already installed on my machine and working fine for other application developed.
The difference between those application and the one with I had the problem was the Old Applications were running on "Local IIS" whereas the one with error was on "IIS Express(running from Visual Studio"). So what I did was-
- Right Click on Project Name.
- Go to Properties
- Go to Web Tab on the right.
- Under Servers select Local IIS and click on Create Virtual Directory button.
- Run the application again and it worked.
The query()
function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql
_x000D_
_x000D_
function insertAtCaret(text) {_x000D_
const textarea = document.querySelector('textarea')_x000D_
textarea.setRangeText(_x000D_
text,_x000D_
textarea.selectionStart,_x000D_
textarea.selectionEnd,_x000D_
'end'_x000D_
)_x000D_
}_x000D_
_x000D_
setInterval(() => insertAtCaret('Hello'), 3000)
_x000D_
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
_x000D_
_x000D_
_x000D_
Repair the database by your domain provider cpanel.
Or see if you didnt merged something in the phpMyAdmin
public static boolean BFS(ListNode n, int x){
if(n==null){
return false;
}
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>();
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
return true;
}
while(tmp != null){
for(ListNode<Integer> child: n.getChildren()){
if(child.val == x){
return true;
}
q.enqueue(child);
}
tmp = q.dequeue();
}
return false;
}
The -I
directive does the job:
gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c
Other option is not to use crontab -e
at all. Instead I used:
(crontab -l && echo "1 1 * * * /path/to/my/script.sh") | crontab -
Notice that whatever you print before | crontab -
will replace the entire crontab file, so use crontab -l && echo "<your new schedule>"
to get the previous content and the new schedule.
export class ClassComponent implements OnInit {
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
checkCurrentLession(current){
this.classes.forEach((obj)=>{
if(obj.currentLession == current){
return true;
}
});
return false;
}
<ul class="table lessonOverview">
<li>
<p>Lesson 1</p>
<button [routerLink]="['/lesson1']"
[disabled]="checkCurrentLession(1)" class="primair">
Start lesson</button>
</li>
<li>
<p>Lesson 2</p>
<button [routerLink]="['/lesson2']"
[disabled]="!checkCurrentLession(2)" class="primair">
Start lesson</button>
</li>
</ul>
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
Just for completeness, you don't actually have to add it to your HTML (which is unknown http-equiv in HTML5)
Do this and never look back (first example for apache, second for nginx)
Header set X-UA-Compatible "IE=Edge,chrome=1"
add_header X-UA-Compatible "IE=Edge,chrome=1";
You can find what is the php.ini file used:
Next, you can find the information in the Loaded Configuration file (so here it's /user/local/etc/php/php.ini)
Sometimes, you have indicated (none), in this case you just have to put your custom php.ini that you can find here: http://git.php.net/?p=php-src.git;a=blob;f=php.ini-production;hb=HEAD
I hope this answer will help.
If your values are hashable (ie. strings), then you can simply compare the ItemsView of the two dicts.
https://docs.python.org/3/library/stdtypes.html#dict-views
set_with_unique_key_value_pairs = dict1.items() ^ dict2.items()
set_with_matching_key_value_pairs = dict1.items() & dict2.items()
Any set
operations are available to you.
Since you might not care about keys in this case, you can also just use the ValuesView (again, provided the values are hashable).
set_with_matching_values = dict1.values() & dict2.values()
float b = (float)Math.ceil(a);
or
float b = (float)Math.round(a);
Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).
Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.
Try
SELECT NAME, count(*) as NUM FROM tbl GROUP BY NAME
To add to @akilat90's update about sklearn.metrics.plot_confusion_matrix
:
You can use the ConfusionMatrixDisplay
class within sklearn.metrics
directly and bypass the need to pass a classifier to plot_confusion_matrix
. It also has the display_labels
argument, which allows you to specify the labels displayed in the plot as desired.
The constructor for ConfusionMatrixDisplay
doesn't provide a way to do much additional customization of the plot, but you can access the matplotlib axes obect via the ax_
attribute after calling its plot()
method. I've added a second example showing this.
I found it annoying to have to rerun a classifier over a large amount of data just to produce the plot with plot_confusion_matrix
. I am producing other plots off the predicted data, so I don't want to waste my time re-predicting every time. This was an easy solution to that problem as well.
Example:
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
Example using ax_
:
cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
cmd.ax_.set(xlabel='Predicted', ylabel='True')
SKU can also refer to a unique identifier or code that refers to the particular stock keeping unit. These codes are not regulated or standardized. When a company receives items from a vendor, it has a choice of maintaining the vendor's SKU or creating its own.[2] This makes them distinct from Global Trade Item Number (GTIN), which are standard, global, tracking units. Universal Product Code (UPC), International Article Number (EAN), and Australian Product Number (APN) are special cases of GTINs.
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
Use control+option+L to auto import the package and auto remove unused packages on Mac
textBox1.Text = "Line1" + Environment.NewLine + "Line2";
Also the markup needs to include TextMode="MultiLine" (otherwise it shows text as one line)
<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>
Jonty, I'm struggling with this too.
I think there's a clue in here:
otool -L /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
/Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle:
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/libruby.1.dylib (compatibility version 1.8.0, current version 1.8.7)
libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)
Notice the path to the dylib is, uh, rather short?
I'm trying to figure out where the gem install instructions are leaving off the dylib path, but it's slow going as I have never built a gem myself.
I'll post more if I find more!
Add
LD_LIBRARY_PATH="/path/you/want1:/path/you/want/2"
to /etc/environment
See the Ubuntu Documentation.
CORRECTION: I should take my own advice and actually read the documentation. It says that this does not apply to LD_LIBRARY_PATH: Since Ubuntu 9.04 Jaunty Jackalope, LD_LIBRARY_PATH cannot be set in $HOME/.profile, /etc/profile, nor /etc/environment files. You must use /etc/ld.so.conf.d/.conf configuration files.* So user1824407's answer is spot on.
You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.
To escape '
you simly need to put another before: ''
As the second answer shows it's possible to escape single quote like this:
select 'it''s escaped'
result will be
it's escaped
If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).
e.g. instead of doing
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)
try this:
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'
sh jmeter.sh
Interestingly putting <httpCookies httpOnlyCookies="false"/>
doesn't seem to disable httpOnlyCookies
in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.
Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on forums.asp.net
The command:
mvn install:install-file
Typically installs the artifact in your local repository, so you shouldn't need to download it. However, if you want to share your artifact with others, you will need to deploy the artifact to a central repository see the deploy plugin for more details.
Additionally adding a dependency to your POM will automatically fetch any third-party artifacts you need when you build your project. I.e. This will download the artifact from the central repository.
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
output=[]
trends=list(set(trends))
I am not familiar with this plugin, but we quite successfully use Bitbucket and Jenkins together, however we poll for changes instead of having them pushed from BitBucket (due to the fact our build server is hidden behind a company firewall). This approach may work for you if you are still having problems with the current approach.
This document on Setting up SSH for Git & Mercurial on Linux covers the details of what you need to do to be able to communicate between your build server and Bitbucket over SSH. Once this is done, with the Git Plugin installed, go to your build configuration and select 'Git' under Source Code Management, and enter the ssh URL of your repository as the repository URL. Finally, in the Build Triggers section, select Poll SCM and set the poll frequency to whatever you require.
for converting dd/mm/yyyy
to mm/dd/yyyy
=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))
Atomicity atomic (default)
Atomic is the default: if you don’t type anything, your property is atomic. An atomic property is guaranteed that if you try to read from it, you will get back a valid value. It does not make any guarantees about what that value might be, but you will get back good data, not just junk memory. What this allows you to do is if you have multiple threads or multiple processes pointing at a single variable, one thread can read and another thread can write. If they hit at the same time, the reader thread is guaranteed to get one of the two values: either before the change or after the change. What atomic does not give you is any sort of guarantee about which of those values you might get. Atomic is really commonly confused with being thread-safe, and that is not correct. You need to guarantee your thread safety other ways. However, atomic will guarantee that if you try to read, you get back some kind of value.
nonatomic
On the flip side, non-atomic, as you can probably guess, just means, “don’t do that atomic stuff.” What you lose is that guarantee that you always get back something. If you try to read in the middle of a write, you could get back garbage data. But, on the other hand, you go a little bit faster. Because atomic properties have to do some magic to guarantee that you will get back a value, they are a bit slower. If it is a property that you are accessing a lot, you may want to drop down to nonatomic to make sure that you are not incurring that speed penalty. Access
courtesy https://academy.realm.io/posts/tmi-objective-c-property-attributes/
Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.
So — if you define an atomic property in Objective-C it will remain atomic when used by Swift.
courtesy https://medium.com/@YogevSitton/atomic-vs-non-atomic-properties-crash-course-d11c23f4366c
TryParse and the Exception Tax
Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.
This is the easiest way that worked for me: To install PHP 5.6 on CentOS 6 or 7:
CentOS 6. Enter the following commands in the order shown:
yum -y update
yum -y install epel-release
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
wget https://centos6.iuscommunity.org/ius-release.rpm
rpm -Uvh ius-release*.rpm
yum -y update
yum -y install php56u php56u-opcache php56u-xml php56u-mcrypt php56u-gd php56u-devel php56u-mysql php56u-intl php56u-mbstring php56u-bcmath
CentOS 7. Enter the following commands in the order shown:
yum -y update
yum -y install epel-release
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
wget https://centos7.iuscommunity.org/ius-release.rpm
rpm -Uvh ius-release*.rpm
yum -y update
yum -y install php56u php56u-opcache php56u-xml php56u-mcrypt php56u-gd php56u-devel php56u-mysql php56u-intl php56u-mbstring php56u-bcmath
Sorry - I'm unable to post the source URL - due to reputation
If you create your test classes in a seperate folder which you then add to your build path,
Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.
But dont forget to remove the folder from the build path for your release build.
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
Using btoa
with unescape
and encodeURIComponent
didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:
base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
}));
You can use the IsNullOrEmpty
static method:
[string]::IsNullOrEmpty(...)
There should be no difference, but your tuple method is wrong, try:
a_list.append(tuple([3, 4]))
Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.
Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:
As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the
CreateThread
function will not setup the stack correctly for the C runtime library. You should use_beginthreadex
instead, which is (almost) completely compatible withCreateThread
.
When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:
Naming.rebind("rmi://localhost:8080/AddService"
,addService);
Thus the server binds both the IP = 127.0.0.1 and the port 8080.
But on the client side I had used:
AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
+"/AddService");
Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:
AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
+"/AddService");
and everything worked fine.
Use ,
as format specifier:
>>> format(10000.21, ',')
'10,000.21'
Alternatively you can also use str.format
instead of format
:
>>> '{:,}'.format(10000.21)
'10,000.21'
With matplotlib.ticker.FuncFormatter
:
...
ax.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()
You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.
In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.
select
p.product_id,
p.type_id,
p.product_name,
p.type,
case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
Product p
inner join Product_Type pt on
pt.type_id = p.type_id
left join Product_ArtistAuthor paa on
paa.artist_id = p.artist_id
where
p.product_id = $pid
I used a left join since I don't know the business logic.
Yes , You can use conditional statement with EJS like if else , ternary operator or even switch case also
For Example
Ternary operator :
<%- role == 'Admin' ? 'Super Admin' : role == 'subAdmin' ? 'Sub Admin' : role %>
Switch Case
<% switch (role) {
case 'Admin' : %>
Super Admin
<% break;
case 'eventAdmin' : %>
Event Admin
<% break;
case 'subAdmin' : %>
Sub Admin
<% break;
} %>
A solution by using the new ConstraintLayout
is wrapping the ConstraintLayout
in a LinearLayout
with minHeight and minWidth fixed. Without the wrapping, ConstraintLayout is not getting the right size for the Dialog.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="1000dp"
android:minHeight="1000dp"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_color"
android:orientation="vertical">
<!-- some constrained views -->
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Open in new tab using javascript
<button onclick="window.open('https://www.our-url.com')" id="myButton"
class="btn request-callback" >Explore More </button>
There's nothing wrong with using isinstance
as long as it's not redundant. If a variable should only be a list/tuple then document the interface and just use it as such. Otherwise a check is perfectly reasonable:
if isinstance(a, collections.Iterable):
# use as a container
else:
# not a container!
This type of check does have some good use-cases, such as with the standard string startswith / endswith methods (although to be accurate these are implemented in C in CPython using an explicit check to see if it's a tuple - there's more than one way to solve this problem, as mentioned in the article you link to).
An explicit check is often better than trying to use the object as a container and handling the exception - that can cause all sorts of problems with code being run partially or unnecessarily.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
In Java SE you need software to run the program like if you have developed a desktop application and if you want to share the application with other machines all the machines have to install the software for running the application. But in Java EE there is no software needed to install in all the machines. Java EE has the forward capabilities. This is only one simple example. There are lots of differences.
jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:
$("a.directions-link").attr("href", function(i, href) {
return href + '?q=testing';
});
That loops over all the elements too, so no need for $.each
I needed to start/stop background music in my application when first activity opens and closes or when any activity is paused by home button and then resumed from task manager. Pure playback stopping/resuming in Activity.onPause()
and Activity.onResume()
interrupted the music for a while, so I had to write the following code:
@Override
public void onResume() {
super.onResume();
// start playback here (if not playing already)
}
@Override
public void onPause() {
super.onPause();
ActivityManager manager = (ActivityManager) this.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(Integer.MAX_VALUE);
boolean is_finishing = this.isFinishing();
boolean is_last = false;
boolean is_topmost = false;
for (ActivityManager.RunningTaskInfo task : tasks) {
if (task.topActivity.getPackageName().startsWith("cz.matelier.skolasmyku")) {
is_last = task.numRunning == 1;
is_topmost = task.topActivity.equals(this.getComponentName());
break;
}
}
if ((is_finishing && is_last) || (!is_finishing && is_topmost && !mIsStarting)) {
mIsStarting = false;
// stop playback here
}
}
which interrupts the playback only when application (all its activities) is closed or when home button is pressed. Unfortunatelly I didn't manage to change order of calls of onPause()
method of the starting activity and onResume()
of the started actvity when Activity.startActivity()
is called (or detect in onPause()
that activity is launching another activity other way) so this case have to be handled specially:
private boolean mIsStarting;
@Override
public void startActivity(Intent intent) {
mIsStarting = true;
super.startActivity(intent);
}
Another drawback is that this requires GET_TASKS
permission added to AndroidManifest.xml
:
<uses-permission
android:name="android.permission.GET_TASKS"/>
Modifying this code that it only reacts on home button press is straighforward.
The ngIf
directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf
evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
<!-- when $scope.myValue is truthy (element is restored) -->
<div ng-if="1"></div>
<!-- when $scope.myValue is falsy (element is removed) -->
<div ng-if="0"></div>
When an element is removed using ngIf
its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf
inherits from its parent scope using prototypal inheritance.
If ngModel
is used within ngIf
to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.
<input type="text" ng-model="data">
<div ng-if="true">
<input type="text" ng-model="data">
</div>
To get around this situation and update the model in the parent scope from inside the child scope, use an object:
<input type="text" ng-model="data.input">
<div ng-if="true">
<input type="text" ng-model="data.input">
</div>
Or, $parent
variable to reference the parent scope object:
<input type="text" ng-model="data">
<div ng-if="true">
<input type="text" ng-model="$parent.data">
</div>
The ngShow
directive shows or hides the given HTML element based on the expression provided to the ngShow
attribute. The element is shown or hidden by removing or adding the ng-hide
CSS class onto the element. The .ng-hide
CSS class is predefined in AngularJS and sets the display style to none (using an !important
flag).
<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="1"></div>
<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="0" class="ng-hide"></div>
When the ngShow
expression evaluates to false
then the ng-hide
CSS class is added to the class
attribute on the element causing it to become hidden. When true
, the ng-hide
CSS class is removed from the element causing the element not to appear hidden.
I came across this one while debugging a virtualmin/apache related error.
In my case, I am running virtualmin and had in my virtual machine's php.ini safe_mode=On.
In my Virtual Machine's error log, I was getting the fcgi Connection reset by peer: mod_fcgid: error reading data from FastCGI server
In my main apache error log I was getting: PHP Fatal error: Directive 'safe_mode' is no longer available in PHP in Unknown on line 0
In my case, I simply set safe_mode = Off in my php.ini and restarted apache.
stackoverflow.com/questions/18683177/where-to-start-with-deprecated-directive-safe-mode-on-line-0-in-apache-error
I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.
Including the option -NoNewWindow
gives me an error: Start-Process : This command cannot be executed due to the error: Access is denied.
The only way I could get it to work was to call:
Start-Process <path to exe> -Wait
You can use regular expressions for this, so I think this is what you want:
select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.
There is nothing in include/require that prohibits you from using absolute an path. so your example
include('/includes/header.php');
should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)
This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.
This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.
as for the '.'
syntax:
/home/username/public_html <- absolute path public_html <- relative path ./public_html <- same as the path above ../username/public_html <- another relative path
However, I usually use a slightly different option:
require_once(__DIR__ . '/Factories/ViewFactory.php');
With this edition, you specify an absolute path, relative to the file that contains the require_once()
statement.
you want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:
"classes.php"
include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';
Then you just need:
require_once('classes.php');
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
PURE JAVASCRIPT SCROLLER CLASS
This is an old question but I thought I could answer with some fancy stuff and some more options to play with if you want to have a bit more control over the animation.
Here it is a pure JS Class to take care of the scrolling for you:
SEE DEMO AT CODEPEN OR GO TO THE BOTTOM AND RUN THE SINPET
// ------------------- USE EXAMPLE ---------------------
// *Set options
var options = {
'showButtonAfter': 200, // show button after scroling down this amount of px
'animate': "linear", // [false|normal|linear] - for false no aditional settings are needed
'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
'steps': 20, // the more steps per loop the slower animation gets
'ms': 10 // the less ms the quicker your animation gets
},
'linear': { // applys only if [animate: linear] - set scroll px|ms
'px': 30, // the more px the quicker your animation gets
'ms': 10 // the less ms the quicker your animation gets
},
};
// *Create new Scroller and run it.
var scroll = new Scroller(options);
scroll.init();
FULL CLASS SCRIPT + USE EXAMPLE:
// PURE JAVASCRIPT (OOP)_x000D_
_x000D_
function Scroller(options) {_x000D_
this.options = options;_x000D_
this.button = null;_x000D_
this.stop = false;_x000D_
}_x000D_
_x000D_
Scroller.prototype.constructor = Scroller;_x000D_
_x000D_
Scroller.prototype.createButton = function() {_x000D_
_x000D_
this.button = document.createElement('button');_x000D_
this.button.classList.add('scroll-button');_x000D_
this.button.classList.add('scroll-button--hidden');_x000D_
this.button.textContent = "^";_x000D_
document.body.appendChild(this.button);_x000D_
}_x000D_
_x000D_
Scroller.prototype.init = function() {_x000D_
this.createButton();_x000D_
this.checkPosition();_x000D_
this.click();_x000D_
this.stopListener();_x000D_
}_x000D_
_x000D_
Scroller.prototype.scroll = function() {_x000D_
if (this.options.animate == false || this.options.animate == "false") {_x000D_
this.scrollNoAnimate();_x000D_
return;_x000D_
}_x000D_
if (this.options.animate == "normal") {_x000D_
this.scrollAnimate();_x000D_
return;_x000D_
}_x000D_
if (this.options.animate == "linear") {_x000D_
this.scrollAnimateLinear();_x000D_
return;_x000D_
}_x000D_
}_x000D_
Scroller.prototype.scrollNoAnimate = function() {_x000D_
document.body.scrollTop = 0;_x000D_
document.documentElement.scrollTop = 0;_x000D_
}_x000D_
Scroller.prototype.scrollAnimate = function() {_x000D_
if (this.scrollTop() > 0 && this.stop == false) {_x000D_
setTimeout(function() {_x000D_
this.scrollAnimate();_x000D_
window.scrollBy(0, (-Math.abs(this.scrollTop()) / this.options.normal['steps']));_x000D_
}.bind(this), (this.options.normal['ms']));_x000D_
}_x000D_
}_x000D_
Scroller.prototype.scrollAnimateLinear = function() {_x000D_
if (this.scrollTop() > 0 && this.stop == false) {_x000D_
setTimeout(function() {_x000D_
this.scrollAnimateLinear();_x000D_
window.scrollBy(0, -Math.abs(this.options.linear['px']));_x000D_
}.bind(this), this.options.linear['ms']);_x000D_
}_x000D_
}_x000D_
_x000D_
Scroller.prototype.click = function() {_x000D_
_x000D_
this.button.addEventListener("click", function(e) {_x000D_
e.stopPropagation();_x000D_
this.scroll();_x000D_
}.bind(this), false);_x000D_
_x000D_
this.button.addEventListener("dblclick", function(e) {_x000D_
e.stopPropagation();_x000D_
this.scrollNoAnimate();_x000D_
}.bind(this), false);_x000D_
_x000D_
}_x000D_
_x000D_
Scroller.prototype.hide = function() {_x000D_
this.button.classList.add("scroll-button--hidden");_x000D_
}_x000D_
_x000D_
Scroller.prototype.show = function() {_x000D_
this.button.classList.remove("scroll-button--hidden");_x000D_
}_x000D_
_x000D_
Scroller.prototype.checkPosition = function() {_x000D_
window.addEventListener("scroll", function(e) {_x000D_
if (this.scrollTop() > this.options.showButtonAfter) {_x000D_
this.show();_x000D_
} else {_x000D_
this.hide();_x000D_
}_x000D_
}.bind(this), false);_x000D_
}_x000D_
_x000D_
Scroller.prototype.stopListener = function() {_x000D_
_x000D_
// stop animation on slider drag_x000D_
var position = this.scrollTop();_x000D_
window.addEventListener("scroll", function(e) {_x000D_
if (this.scrollTop() > position) {_x000D_
this.stopTimeout(200);_x000D_
} else {_x000D_
//..._x000D_
}_x000D_
position = this.scrollTop();_x000D_
}.bind(this, position), false);_x000D_
_x000D_
// stop animation on wheel scroll down_x000D_
window.addEventListener("wheel", function(e) {_x000D_
if (e.deltaY > 0) this.stopTimeout(200);_x000D_
}.bind(this), false);_x000D_
}_x000D_
_x000D_
Scroller.prototype.stopTimeout = function(ms) {_x000D_
this.stop = true;_x000D_
// console.log(this.stop); //_x000D_
setTimeout(function() {_x000D_
this.stop = false;_x000D_
console.log(this.stop); //_x000D_
}.bind(this), ms);_x000D_
}_x000D_
_x000D_
Scroller.prototype.scrollTop = function() {_x000D_
var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;_x000D_
return curentScrollTop;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
// ------------------- USE EXAMPLE ---------------------_x000D_
// *Set options_x000D_
var options = {_x000D_
'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
_x000D_
'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
'steps': 20, // the more steps per loop the slower animation gets_x000D_
'ms': 10 // the less ms the quicker your animation gets_x000D_
},_x000D_
'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
'px': 30, // the more px the quicker your animation gets_x000D_
'ms': 10 // the less ms the quicker your animation gets_x000D_
},_x000D_
};_x000D_
// *Create new Scroller and run it._x000D_
var scroll = new Scroller(options);_x000D_
scroll.init();
_x000D_
/* CSS */_x000D_
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);_x000D_
body {_x000D_
font-family: 'Open Sans', sans-serif;_x000D_
font-size: 1.2rem;_x000D_
line-height: 2rem;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
padding: 0 25%;_x000D_
}_x000D_
.scroll-button {_x000D_
font-size: 1.2rem;_x000D_
line-height: 2rem;_x000D_
padding: 10px;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: black;_x000D_
color: white;_x000D_
border-radius: 50%;_x000D_
position: fixed;_x000D_
right: 20px;_x000D_
bottom: 20px;_x000D_
visibility: visible;_x000D_
filter: alpha(opacity=50);_x000D_
filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=50);_x000D_
opacity: 0.5;_x000D_
cursor: pointer;_x000D_
transition: all 1.2s;_x000D_
-webkit-transition: all 1.2s;_x000D_
-moz-transition: all 1.2s;_x000D_
-ms-transition: all 1.2s;_x000D_
-o-transition: all 1.2s;_x000D_
}_x000D_
.scroll-button:hover {_x000D_
filter: alpha(opacity=100);_x000D_
filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);_x000D_
opacity: 1;_x000D_
}_x000D_
.scroll-button--hidden {_x000D_
filter: alpha(opacity=0);_x000D_
filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
_x000D_
<h1>Scroll down by 200px for button to appear</h1>_x000D_
<ul>_x000D_
<li>Cross-browser</li>_x000D_
<li>Copy/Paste solution</li>_x000D_
<li>3 animate modes: <b>["normal"|"linear"|false]</b></li>_x000D_
<li>Customize your aniamtion with aveilable settings - make it snapy or fluent</li>_x000D_
<li>Double click to skip animation</li>_x000D_
<li>Every next single click adds initial speed</li>_x000D_
<li>Stop scroll animation by draging down the scroll bar</li>_x000D_
<li>Stop scroll animation by mouse wheel down</li>_x000D_
<li>Animated button fade-in-out on scroll</li>_x000D_
</ul>_x000D_
_x000D_
<br />_x000D_
<br />_x000D_
<pre>_x000D_
// ------------------- USE EXAMPLE ---------------------_x000D_
// *Set options_x000D_
var options = {_x000D_
'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
_x000D_
'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
'steps': 20, // the more steps the slower animation gets_x000D_
'ms': 20 // the less ms the quicker your animation gets_x000D_
}, _x000D_
'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
'px': 55, // the more px the quicker your animation gets_x000D_
'ms': 10 // the less ms the quicker your animation gets_x000D_
}, _x000D_
};_x000D_
_x000D_
// *Create new Scroller and run it._x000D_
var scroll = new Scroller(options);_x000D_
scroll.init();_x000D_
</pre>_x000D_
<br />_x000D_
<br />_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae illo nobis quo autem molestias voluptatum quam, amet ipsum debitis, iure animi illum soluta eaque qui perspiciatis harum, sequi nesciunt.</span><span>Quisquam nesciunt aspernatur a possimus pariatur enim architecto. Hic aperiam sit repellat doloremque vel est soluta et assumenda dolore, sint sapiente porro, quam impedit. Sint praesentium quas excepturi, voluptatem dicta!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate, porro nisi molestias minima corrupti tempore, dolorum fugiat ipsam dicta doloremque accusamus atque consequatur iusto natus, mollitia distinctio odit dolor tempora.</span><span>Perferendis a in laudantium accusantium, dolorum eius placeat velit porro similique, eum cumque veniam neque aspernatur architecto suscipit rem laboriosam voluptates laborum? Voluptates tempora necessitatibus animi nostrum quod, maxime odio.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil accusantium, itaque corporis repellat pariatur soluta officia perspiciatis in reprehenderit facere, incidunt saepe excepturi. Inventore atque ex illo, ipsam at deserunt.</span><span>Laborum inventore officia, perspiciatis cumque magni consequatur iste accusantium soluta, nesciunt blanditiis voluptatibus adipisci laudantium mollitia minus quia necessitatibus voluptates. Minima unde quos impedit necessitatibus aspernatur minus maiores ipsa eligendi!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate nesciunt, explicabo similique, quo maxime modi, aliquid, voluptatibus repellendus dolorum placeat mollitia ea dicta quia laboriosam alias dignissimos ipsam tenetur. Nulla.</span><span>Vel maiores necessitatibus odio voluptate debitis, error in accusamus nulla, eum, nemo et ea commodi. Autem numquam at, consequatur temporibus. Mollitia placeat nobis blanditiis impedit distinctio! Ad, incidunt fugiat sed.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam voluptatum, odio quam omnis iste laudantium, itaque architecto, eos ullam debitis delectus sapiente nemo autem reprehenderit. Dolorem quidem facere ipsam! Nisi.</span><span>Vitae quaerat modi voluptatibus ratione numquam? Sapiente aliquid officia pariatur quibusdam aliquam id expedita non recusandae, cumque deserunt asperiores. Corrupti et doloribus aspernatur ipsum asperiores, ipsa unde corporis commodi reiciendis?</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima adipisci minus iste, nesciunt itaque quisquam quidem voluptatum assumenda rerum aliquid, excepturi voluptatem tempora. Possimus ratione alias a error vel, rem.</span><span>Officia esse error accusantium veritatis ad, et sit animi? Recusandae mollitia odit tenetur ad cumque maiores eligendi blanditiis nobis hic tempora obcaecati consequatur commodi totam, debitis, veniam, ducimus molestias ut.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quibusdam, tempora cupiditate quaerat tempore ullam delectus voluptates optio eum placeat provident consequatur iure reprehenderit vero quae sapiente architecto earum nemo.</span><span>Quis molestias sint fuga doloribus, necessitatibus nulla. Esse ipsa, itaque asperiores. Tempora a sequi nobis cumque incidunt aspernatur, pariatur rem voluptatibus. Atque veniam magnam, ea laudantium ipsum reprehenderit sapiente repellendus.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, pariatur at explicabo aliquid repudiandae vero eum quasi totam voluptates iusto unde ad repellendus ipsam et voluptatem hic adipisci! Vero, nobis!</span><span>Consequatur eligendi quo quas omnis architecto dolorum aperiam doloremque labore, explicabo enim incidunt vitae saepe, quod soluta illo odit provident amet beatae quasi animi. Similique nostrum molestiae animi corrupti qui?</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias quis, tempora laborum incidunt qui fuga adipisci doloremque iusto commodi vitae est, nemo iure placeat ut sit optio, consequuntur voluptas impedit.</span><span>Eos officiis, hic esse unde eaque, aut tenetur voluptate quam sint vel exercitationem totam dolor odio soluta illo praesentium non corrupti! Consequuntur velit, mollitia excepturi. Minus, veniam accusantium! Aliquam, ea!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit quis reiciendis veritatis expedita velit vitae amet magni sunt rerum in blanditiis aut tempore quia fugiat, voluptates officia quaerat quam id.</span><span>Sapiente tempore repudiandae, quae doloremque ullam odio quia ea! Impedit atque, ipsa consequatur quis obcaecati voluptas necessitatibus, cupiditate sunt amet ab modi illum inventore, a dolor enim similique architecto est!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque non aliquam, sit illo quas deserunt esse nobis reprehenderit quidem fuga beatae eligendi reiciendis omnis qui repellat velit earum blanditiis possimus.</span><span>Provident aspernatur ducimus, illum beatae debitis vitae non dolorum rem officia nostrum natus accusantium perspiciatis ad soluta maiores praesentium eveniet qui hic quis at quaerat ea perferendis. Ut, aut, natus.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione corrupti quibusdam, sed hic veniam. Perspiciatis ex, quod architecto natus autem totam at commodi excepturi maxime pariatur corporis, veritatis vero, praesentium.</span><span>Nesciunt suscipit, nobis eos perferendis ex quaerat inventore nihil qui magnam saepe rerum velit reiciendis ipsam deleniti ducimus eligendi odio eius minima vero, nisi voluptates amet eaque, iste, labore laudantium.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, voluptas accusantium ad omnis velit distinctio! Adipisci magnam nihil nostrum molestiae rem dolores, ut ad nemo, dolor quos itaque maiores quaerat!</span><span>Quia ad suscipit reprehenderit vitae inventore eius non culpa maiores omnis sit obcaecati vel placeat quibusdam, ipsa exercitationem nam odit, magni nobis. Quam quas, accusamus expedita molestiae asperiores eaque ex?</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum explicabo doloribus nihil iusto quasi vel expedita dignissimos amet mollitia, temporibus aut atque architecto assumenda dolorum nam velit deserunt totam numquam.</span><span>Ab perferendis labore, quae. Quidem architecto quo officia deserunt ea doloribus libero molestias id nisi perferendis eum porro, quibusdam! Odit aliquid placeat rem aut officia minus sit esse eos obcaecati!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi nostrum repellendus placeat, unde aperiam. Fuga, voluptas, minima. Debitis nemo ducimus itaque laboriosam error quaerat reprehenderit quo animi incidunt. Nulla, quis!</span><span>Explicabo assumenda dicta ratione? Tempora commodi asperiores, explicabo doloremque eius quia impedit possimus architecto sit nemo odio eum fuga minima dolor iste mollitia sequi dolorem perspiciatis unde quisquam laborum soluta.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam officia corporis, reiciendis laudantium, voluptate voluptates necessitatibus assumenda, delectus quisquam velit deserunt! Reprehenderit, vel quaerat accusantium nesciunt libero animi. Sequi, eveniet?</span><span>Animi natus pariatur porro, alias, veniam aut est tempora adipisci molestias harum modi cumque assumenda enim! Expedita eveniet autem illum rerum nostrum ipsum alias neque aut, dolorum impedit pariatur non?</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis aliquid rerum, odio veniam ipsam ad officia quos repellat ex aperiam voluptatum optio est animi possimus minus. Sapiente voluptates amet dolorem.</span><span>Illo necessitatibus similique asperiores inventore ut cumque nihil assumenda debitis explicabo rerum, dolorum molestiae culpa accusantium. Nisi doloremque optio provident blanditiis, eum ipsam asperiores, consequatur aliquam vel sit mollitia sunt.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, totam harum perferendis. Minus ea perferendis laboriosam, iste, qui corrupti, quas veritatis omnis officiis animi fuga perspiciatis impedit! Error, harum, voluptas.</span><span>Omnis laborum, cum mollitia facilis ipsa unde distinctio maxime nesciunt illum perspiciatis ut officiis, eligendi numquam dolorem quod modi ipsam est rerum perferendis repellendus totam. Maxime excepturi culpa alias labore.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit deleniti, odit sit consequatur dolorum omnis repellendus, alias vel ullam numquam. Nostrum obcaecati hic, possimus delectus nam atque aliquid explicabo cum.</span><span>Explicabo tenetur minima consequatur, aliquam, laudantium non consequuntur facilis sint, suscipit debitis ex atque mollitia magni quod repellat ratione dolorum excepturi molestiae cumque iusto eos unde? Voluptatum dolores, porro provident!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At laboriosam fuga aperiam eveniet, obcaecati esse, nulla porro iure molestiae praesentium sint fugiat ea voluptate suscipit voluptates mollitia, voluptatibus. Autem, non.</span><span>Numquam velit culpa tempora ratione ipsum minus modi in? Nisi reiciendis, voluptate voluptatem maxime repellat quae odio, repellendus aliquid laborum dolorem. Labore, fuga ea minima explicabo quae voluptatum necessitatibus, similique.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, rerum dolorum nemo error fugiat ut, modi, architecto libero maxime laborum repellendus doloribus neque aperiam adipisci quaerat obcaecati deserunt consequuntur amet!</span><span>Sint, assumenda nisi obcaecati doloremque iste. Perspiciatis accusantium, distinctio impedit cum esse recusandae sunt. Officiis culpa dolore eius, doloribus natus, dolorum excepturi vitae fugiat ullam provident harum! Suscipit, assumenda, harum.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, nihil tenetur tempore eligendi qui nesciunt consequatur delectus accusantium consectetur ipsa, nulla doloribus dolores rerum corporis, laborum, laboriosam hic mollitia repellat.</span><span>Ab deleniti vitae blanditiis quod tenetur! Voluptatem temporibus ab eaque quis? Quis odio aliquid harum temporibus totam, ipsa eius iusto fugiat enim in, quibusdam molestiae aliquam consequatur nulla, consequuntur sint.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum odit praesentium quos, earum nesciunt laudantium illo tempora eligendi, porro doloremque mollitia neque aperiam inventore nam maxime dolor labore aspernatur molestias.</span><span>Voluptatibus provident hic cupiditate placeat, ut reprehenderit nisi eum, dolores ad sed quis. Doloribus molestiae, quae rem odit expedita soluta, facilis animi corporis velit ut in, recusandae harum laboriosam veritatis.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repudiandae molestias magnam delectus veritatis labore, corporis dicta officia quos, ad corrupti odit! Ad hic officia maxime eveniet consectetur similique adipisci!</span><span>Quia at, nesciunt aliquid delectus ex alias voluptas maxime hic esse. Incidunt, laborum quos mollitia dolores et! Voluptas commodi asperiores, fugit quidem quis corporis, a eaque, animi, autem deserunt repellendus.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi quas, voluptas hic minima inventore optio, id quidem placeat necessitatibus omnis voluptatibus vitae mollitia tempora consequuntur consequatur, illo facilis accusamus illum.</span><span>Voluptates consequuntur ipsam odit. Eius quis ipsam vitae, nihil molestias perferendis corporis recusandae consequatur vero iure blanditiis quas adipisci quos voluptatem rem illo voluptate. Eveniet officiis iure sit laborum veniam.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit a quis cumque nostrum quisquam molestiae pariatur, asperiores natus necessitatibus adipisci illum cupiditate nam vero, tempora excepturi laborum, earum. Voluptates, nobis.</span><span>Pariatur suscipit, hic blanditiis libero, iusto, quam cupiditate nam error id asperiores repellat ab consequatur vitae ipsa voluptatem totam magni reiciendis expedita maxime dolor! Minus explicabo quas, laborum ab omnis!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore qui ad assumenda placeat optio illo molestias corporis dolorum cum. Doloribus eius autem obcaecati minima, asperiores iure dignissimos ducimus suscipit dolorem.</span><span>Blanditiis earum accusamus eaque temporibus necessitatibus voluptatum dolorem enim debitis inventore assumenda quae error perspiciatis aut, nulla delectus quam ipsa sapiente ea aliquam laboriosam repudiandae. Nesciunt praesentium, beatae eos quasi!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate dicta voluptate impedit? Ad voluptatum dicta earum perferendis asperiores. Dolore distinctio modi expedita consequatur provident perspiciatis neque totam rerum placeat quas.</span><span>Eveniet optio est possimus iste accusantium ipsum illum. Maiores saepe repudiandae facere, delectus iure dolorem vitae nihil pariatur minima, reprehenderit eligendi dolore impedit, nisi doloribus quidem similique. Optio, delectus, minus.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste ex molestiae architecto enim nihil tempore, atque consequuntur doloribus recusandae sed consequatur veniam quos, in consectetur perspiciatis magni nostrum ab voluptates.</span><span>Nisi quos mollitia quis in maiores asperiores labore deserunt! Voluptate voluptas adipisci qui hic officia molestias, laborum necessitatibus sint nam vel minus incidunt perspiciatis recusandae sunt, rerum suscipit doloremque possimus!</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At nihil perferendis quae quidem facilis aliquid pariatur possimus hic asperiores, recusandae exercitationem adipisci atque laborum, delectus, odit ab reprehenderit distinctio dolor.</span><span>Non excepturi quos aspernatur repudiandae laboriosam, unde molestias, totam, sapiente harum accusamus delectus laborum ipsam velit amet nisi! Consectetur aliquam provident voluptatibus saepe repudiandae eveniet laborum beatae, animi, voluptate dolores.</span></p>_x000D_
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque magni, eum ipsa, veritatis facere voluptatem dolorum nobis neque minus debitis asperiores iste. Pariatur sequi quam, tempora. Dignissimos, esse similique tempora.</span><span>Ex delectus excepturi autem sunt, nemo repudiandae, recusandae nostrum accusantium nobis temporibus magnam eligendi similique veritatis deleniti, eaque blanditiis possimus at! Repellat alias laboriosam ipsum commodi dolorem, corporis dolore suscipit!</span></p>
_x000D_
I found the best solution for this problem by using ON with $(document).
$(document).on('click', '#yourid', function() { alert("hello"); });
for id start with see below:
$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });
finally after 1 week I not need to add onclick triger. I hope this will help many people
Not the most elegant way but this worked for me:
var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);
function formatDate(ms) {
var date = new Date(parseInt(ms));
var hour = date.getHours();
var mins = date.getMinutes() + '';
var time = "AM";
// find time
if (hour >= 12) {
time = "PM";
}
// fix hours format
if (hour > 12) {
hour -= 12;
}
else if (hour == 0) {
hour = 12;
}
// fix minutes format
if (mins.length == 1) {
mins = "0" + mins;
}
// return formatted date time string
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}
jquery will provide you with this and more ...
if($("#something").val()){ //do stuff}
It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.
jQuery(document).ready(function() {
/* finds closest element with class divright/left and
makes all checkboxs inside that div class the same as selectAll...
*/
$("#selectAll").click(function() {
$(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
});
});
One example, if you need to reference/join the same data set multiple times you can do so by defining a CTE. Therefore, it can be a form of code re-use.
An example of self referencing is recursion: Recursive Queries Using CTE
For exciting Microsoft definitions Taken from Books Online:
A CTE can be used to:
Create a recursive query. For more information, see Recursive Queries Using Common Table Expressions.
Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.
Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access.
Reference the resulting table multiple times in the same statement.
Your code can be narrowed down to
Sub DeleteTableRows(ByRef Table As ListObject)
On Error Resume Next
'~~> Clear Header Row `IF` it exists
Table.DataBodyRange.Rows(1).ClearContents
'~~> Delete all the other rows `IF `they exist
Table.DataBodyRange.Offset(1, 0).Resize(Table.DataBodyRange.Rows.Count - 1, _
Table.DataBodyRange.Columns.Count).Rows.Delete
On Error GoTo 0
End Sub
Edit:
On a side note, I would add proper error handling if I need to intimate the user whether the first row or the other rows were deleted or not
If you have a new database and you make a fresh clean import, the problem may come from inserting data that contains a '0' incrementation and this would transform to '1' with AUTO_INCREMENT
and cause this error.
My solution was to use in the sql import file.
SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';
# First we obtain de timezone info o some datatime variable
tz_info = your_timezone_aware_variable.tzinfo
# Now we can subtract two variables using the same time zone info
# For instance
# Lets obtain the Now() datetime but for the tz_info we got before
diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable
Conclusion: You must mange your datetime variables with the same time info
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
A possibility is that the element is currently unclickable because it is not visible. Reasons for this may be that another element is covering it up or it is not in view, i.e. it is outside the currently view-able area.
Try this
from selenium.webdriver.common.action_chains import ActionChains
button = driver.find_element_by_class_name(u"infoDismiss")
driver.implicitly_wait(10)
ActionChains(driver).move_to_element(button).click(button).perform()
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
The method above will bring you something like this:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
From here you can navigate backwards using System.IO.Directory.GetParent:
_filePath = Directory.GetParent(_filePath).FullName;
1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:
_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
Hope it helps.
The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.
Character Devices
Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).
TTY
/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty
, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty
, your subsequent input gets duplicated (until you press Ctrl-C).
/dev/tty
doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0
is normally your serial port)
This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :
/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).
Here is the man page: http://linux.die.net/man/4/tty
For N bins, the bin edges are specified by list of N+1 values where the first N give the lower bin edges and the +1 gives the upper edge of the last bin.
Code:
from numpy import np; from pylab import *
bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.linspace(min_edge, max_edge, Nplus1)
Note that linspace produces array from min_edge to max_edge broken into N+1 values or N bins
Just do
find . -name '*.pdf'|xargs rm
I wanted to work out a solution by myself, but my brain tripped and fell on the way. I think it works, but don't ask me to explain it in the morning. :P
DECLARE @table AS TABLE
(
Number int not null
);
insert into @table select 2;
insert into @table select 4;
insert into @table select 9;
insert into @table select 15;
insert into @table select 22;
insert into @table select 26;
insert into @table select 37;
insert into @table select 49;
DECLARE @Count AS INT
SELECT @Count = COUNT(*) FROM @table;
WITH MyResults(RowNo, Number) AS
(
SELECT RowNo, Number FROM
(SELECT ROW_NUMBER() OVER (ORDER BY Number) AS RowNo, Number FROM @table) AS Foo
)
SELECT AVG(Number) FROM MyResults WHERE RowNo = (@Count+1)/2 OR RowNo = ((@Count+1)%2) * ((@Count+2)/2)
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
As you can see, the difference really lies in lib.js
, not main1.js
.
To summarize:
import
-ed variables, no matter how you declare the corresponding variables in the module.let
-vs-const
semantics applies to the declared variable in the module.
const
, it cannot be reassigned or rebound in anywhere.let
, it can only be reassigned in the module (but not the user). If it is changed, the import
-ed variable changes accordingly.Try this:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
For under API 21
Create custom style RadioButton style.xml
<style name="RadioButton" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/green</item>
<item name="android:textColorSecondary">@color/mediumGray</item>
<item name="colorControlNormal">@color/red</item>
</style>
In layout use theme:
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/RadioButton" />
For API 21 and more
Just use buttonTint
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@color/green" />
I had solved it on iPad. Try, if it works also on OSX.
body, html { position: fixed; }
Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).
In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content>
can be still scrollable.
I think that the "right" solution here is to add your proprietary libraries to your own repository. It should be simple: create pom for your library project and publish the compiled version on your repository. Add this repository to the list of repositories for your mail project and run build. I believe it will work for you.
You can do the following to install java 8 on your machine. First get the link of tar
that you want to install. You can do this by:
- go to java downloads page and find the appropriate download.
- Accept the license agreement and download it.
- In the download page in your browser right click and
copy link address
.
Then in your terminal:
$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
Control size and maintain proportion :
#your-img {
height: auto;
width: auto;
max-width: 300px;
max-height: 300px;
}
Here is how I do it:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MainFrame implements ActionListener{
/**
*
*/
/**
* @param args
*/
public static void main(String[] args) {
String appdata = System.getenv("APPDATA");
String iconPath = appdata + "\\JAPP_icon.png";
File icon = new File(iconPath);
if(!icon.exists()){
FileDownloaderNEW fd = new FileDownloaderNEW();
fd.download("http://icons.iconarchive.com/icons/artua/mac/512/Setting-icon.png", iconPath, false, false);
}
JFrame frm = new JFrame("Test");
ImageIcon imgicon = new ImageIcon(iconPath);
JButton bttn = new JButton("Kill");
MainFrame frame = new MainFrame();
bttn.addActionListener(frame);
frm.add(bttn);
frm.setIconImage(imgicon.getImage());
frm.setSize(100, 100);
frm.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
and here is the downloader:
import java.awt.GridLayout;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
public class FileDownloaderNEW extends JFrame {
private static final long serialVersionUID = 1L;
public static void download(String a1, String a2, boolean showUI, boolean exit)
throws Exception
{
String site = a1;
String filename = a2;
JFrame frm = new JFrame("Download Progress");
JProgressBar current = new JProgressBar(0, 100);
JProgressBar DownloadProg = new JProgressBar(0, 100);
JLabel downloadSize = new JLabel();
current.setSize(50, 50);
current.setValue(43);
current.setStringPainted(true);
frm.add(downloadSize);
frm.add(current);
frm.add(DownloadProg);
frm.setVisible(showUI);
frm.setLayout(new GridLayout(1, 3, 5, 5));
frm.pack();
frm.setDefaultCloseOperation(3);
try
{
URL url = new URL(site);
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0.0F;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int i = 0;
while ((i = in.read(data, 0, 1024)) >= 0)
{
totalDataRead += i;
float prog = 100.0F - totalDataRead * 100.0F / filesize;
DownloadProg.setValue((int)prog);
bout.write(data, 0, i);
float Percent = totalDataRead * 100.0F / filesize;
current.setValue((int)Percent);
double kbSize = filesize / 1000;
String unit = "kb";
double Size;
if (kbSize > 999.0D) {
Size = kbSize / 1000.0D;
unit = "mb";
} else {
Size = kbSize;
}
downloadSize.setText("Filesize: " + Double.toString(Size) + unit);
}
bout.close();
in.close();
System.out.println("Took " + System.nanoTime() / 1000000000L / 10000L + " seconds");
}
catch (Exception e)
{
JOptionPane.showConfirmDialog(
null, e.getMessage(), "Error",
-1);
} finally {
if(exit = true){
System.exit(128);
}
}
}
}
The error message the OP is encountering is just an Eclipse feature. If you are willing to tie your code to a specific maker (and even version) of the JVM, you can effectively use method sun.reflect.Reflection.getCallerClass()
. You can then compile the code outside of Eclipse or configure it not to consider this diagnostic an error.
The worse Eclipse configuration is to disable all occurrences of the error by:
Project Properties
/ Java Compiler
/ Errors/Warnings
/ Enable project specific settings
set to checked / Deprecated and restrited API
/ Forbidden reference (access rules)
set to Warning
or Ignore
.
The better Eclipse configuration is to disable a specific occurrence of the error by:
Project Properties
/ Java Build Path
/ Libraries
/ JRE System Library
expand / Access rules:
select / Edit...
/ Add...
/ Resolution:
set to Discouraged
or Accessible
/ Rule Pattern
set to sun/reflect/Reflection
.
If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!
countDownTimer() async {
int timerCount;
for (int x = 5; x > 0; x--) {
await Future.delayed(Duration(seconds: 1)).then((_) {
setState(() {
timerCount -= 1;
});
});
}
}
You had the identity
node as a child of authentication
node. That was the issue. As in the example above, authentication
and identity
nodes must be children of the system.web
node
You have to give the dictionary a type
// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()
If the compiler can infer the type, you can use the shorter syntax
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
svn add filename.html
svn commit -m"your comment"
You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
Perhaps you can try the SQL Server Publishing Wizard http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en
It has a wizard that helps you script insert statements.
without site name
{{Storage::url($photoLink)}}
if you want to add site name to it example to append on api JSON felids
public function getPhotoFullLinkAttribute()
{
return env('APP_URL', false).Storage::url($this->attributes['avatar']) ;
}
android:scaleType ="centerInside" --> this line use to center an image,, but you need to keep height and width of an image as wrap_context
<ImageView
android:id ="@+id/imageView6"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:scaleType ="centerInside"
android:layout_marginTop ="20dp"
app:srcCompat ="@drawable/myimage" />
When using laravel framework, I had some issues with using a route->back() function since it erased my hash. In order to keep my hash, I created a simple function:
$(function() {
if (localStorage.getItem("hash") ){
location.hash = localStorage.getItem("hash");
}
});
and I set it in my other JS function like this:
localStorage.setItem("hash", myvalue);
You can name your local storage values any way you like; mine named hash
.
Therefore, if the hash is set on PAGE1 and then you navigate to PAGE2; the hash will be recreated on PAGE1 when you click Back on PAGE2.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
I tried the below and it worked like a charm :)
rec_list = ['[email protected]', '[email protected]']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
It'll be tricky to rearrange your code to make this work, but I'll try :)
So, put this at the top of your code:
<?php require_once('mysql.php'); ?>
The top of the file should look like:
<?php require_once('mysql.php'); ?>
<html>
<head>
<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>
Then, create a file called mysql.php in the same directory that the file which contains the code you quoted is in.
Put this is mysql.php:
<?php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('ultankc');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid ID specified.");
}
$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
$res = mysql_fetch_assoc($result);
$date = date("l F d Y", $res['timestamp']);
$title = $res['title'];
$entry = $res['entry'];
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
$category = mysql_fetch_array($get_categories);
?>
Well, hope that helped :)
A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.
The approach is wrong, you need to apply the border-radius
to the container div
instead of the actual image.
This would work:
.image-cropper {
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
border-radius: 50%;
}
img {
display: inline;
margin: 0 auto;
height: 100%;
width: auto;
}
_x000D_
<div class="image-cropper">
<img src="https://via.placeholder.com/150" class="rounded" />
</div>
_x000D_
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
In your code behind file, have a public variable
public partial class _Default : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
// your code that at one points sets the variable
this.clients = "abc";
}
}
now in your design code, just assign that to something, like:
<div>
<p><%= clients %></p>
</div>
or even a javascript variable
<script type="text/javascript">
var clients = '<%= clients %>';
</script>
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
Please try this its working for me
BigDecimal bd ;
String value = "2000.00";
bd = new BigDecimal(value);
BigDecimal currency = bd;
radiobuttonlist.selected <value>
to process with your code.
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
See Android arsenal (category Graphics) for more libraries.
print("hello" + ' '*50 + "world")
By using System.Windows.Forms.Timer
class you can achieve what you need.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
By using stop() method you can stop timer.
t.Stop();
You need to change the loop from for ($i=1; $i<count($files); $i++)
to for ($i=0; $i<count($files); $i++)
:
So the correct code is
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
print $image ."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
?>
Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.
/**
* @param configFilePath
* @param ipAddress
* @param userId
* @param password
* @throws MalformedURLException
*/
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
configFilePath = aConfigFilePath;
baseUri = "https://" + ipAddress + ":" + PORT + "/";
restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
}
ClientHttpRequestFactory createSecureTransport(String username,
String password, String host, int port) {
HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
HttpClient client = HttpClientBuilder.create()
.setSSLHostnameVerifier(nullHostnameVerifier)
.setSSLContext(createContext())
.setDefaultCredentialsProvider(credentialsProvider).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(client);
return requestFactory;
}
private SSLContext createContext() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
SSLContext.setDefault(sc);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return sc;
} catch (Exception e) {
}
return null;
}
goto cpanel and login as Main Admin or Super Administrator
find SSH/Shell Access ( you will find under the security tab of cpanel )
now give the username and password of Super Administrator as root
or whatyougave
note: do not give any username, cos, it needs permissions
once your into console type
type ' mysql
' and press enter now you find youself in
mysql>
/* and type here like */
mysql> set global net_buffer_length=1000000;
Query OK, 0 rows affected (0.00 sec)
mysql> set global max_allowed_packet=1000000000;
Query OK, 0 rows affected (0.00 sec)
Now upload and enjoy!!!
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
public static class TimeSpanFormattingExtensions
{
public static string ToReadableString(this TimeSpan span)
{
return string.Join(", ", span.GetReadableStringElements()
.Where(str => !string.IsNullOrWhiteSpace(str)));
}
private static IEnumerable<string> GetReadableStringElements(this TimeSpan span)
{
yield return GetDaysString((int)Math.Floor(span.TotalDays));
yield return GetHoursString(span.Hours);
yield return GetMinutesString(span.Minutes);
yield return GetSecondsString(span.Seconds);
}
private static string GetDaysString(int days)
{
if (days == 0)
return string.Empty;
if (days == 1)
return "1 day";
return string.Format("{0:0} days", days);
}
private static string GetHoursString(int hours)
{
if (hours == 0)
return string.Empty;
if (hours == 1)
return "1 hour";
return string.Format("{0:0} hours", hours);
}
private static string GetMinutesString(int minutes)
{
if (minutes == 0)
return string.Empty;
if (minutes == 1)
return "1 minute";
return string.Format("{0:0} minutes", minutes);
}
private static string GetSecondsString(int seconds)
{
if (seconds == 0)
return string.Empty;
if (seconds == 1)
return "1 second";
return string.Format("{0:0} seconds", seconds);
}
}
Here is an example of how to use strtok borrowed from MSDN.
And the relevant bits, you need to call it multiple times. The token
char* is the part you would stuff into an array (you can figure that part out).
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict.
For example, with numpy you would do something like
import numpy
a = numpy.empty((10, 10))
a.fill(foo)
Just reimport didn't work. Following worked for me.
File -> Invalidate Caches /Restart
Then
Build -> Rebuild Project
That will reimport maven project.
This can be something to start with:
import configparser
config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path']) # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/' # update
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create
with open('FILE.INI', 'w') as configfile: # save
config.write(configfile)
You can find more at the official configparser documentation.
LONG VERSION
src: https://en.wikipedia.org/wiki/C_date_and_time_functions
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
time_t current_time;
char* c_time_string;
/* Obtain current time. */
current_time = time(NULL);
if (current_time == ((time_t)-1))
{
(void) fprintf(stderr, "Failure to obtain the current time.\n");
exit(EXIT_FAILURE);
}
/* Convert to local time format. */
c_time_string = ctime(¤t_time);
if (c_time_string == NULL)
{
(void) fprintf(stderr, "Failure to convert the current time.\n");
exit(EXIT_FAILURE);
}
/* Print to stdout. ctime() has already added a terminating newline character. */
(void) printf("Current time is %s", c_time_string);
exit(EXIT_SUCCESS);
}
The output is:
Current time is Thu Sep 15 21:18:23 2016
SHORT VERSION:
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[]) {
time_t current_time;
time(¤t_time);
printf("%s", ctime(¤t_time));
The output is:
Current time is Thu Jan 28 15:22:31 2021
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}
Deleting submodule dir and its contents ("external/pyfacebook" folder) if it exists before git submodule add ...
might fix problems.
git clone --single-branch --branch <branchname> <remote-repo>
The --single-branch
option is valid from version 1.7.10 and later.
Please see also the other answer which many people prefer.
You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url
you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.
Again, that is not to say git clone --branch
is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.
The image trick is cool but in my tests it was loading before some ajax calls I wanted to be complete.
The proper solution in 2017 is to use a worker (http://caniuse.com/#feat=webworkers).
The worker will look like:
/**
* This function performs a synchronous request
* and returns an object contain informations about the download
* time and size
*/
function measure(filename) {
var xhr = new XMLHttpRequest();
var measure = {};
xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
measure.start = (new Date()).getTime();
xhr.send(null);
measure.end = (new Date()).getTime();
measure.len = parseInt(xhr.getResponseHeader('Content-Length') || 0);
measure.delta = measure.end - measure.start;
return measure;
}
/**
* Requires that we pass a base url to the worker
* The worker will measure the download time needed to get
* a ~0KB and a 100KB.
* It will return a string that serializes this informations as
* pipe separated values
*/
onmessage = function(e) {
measure0 = measure(e.data.base_url + '/test/0.bz2');
measure100 = measure(e.data.base_url + '/test/100K.bz2');
postMessage(
measure0.delta + '|' +
measure0.len + '|' +
measure100.delta + '|' +
measure100.len
);
};
The js file that will invoke the Worker:
var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
base_url: base_url
});
w.onmessage = function(event) {
if (event.data) {
set_cookie(event.data);
}
};
Code taken from a Plone package I wrote:
Through this code, you can get click count on a button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Button</title>
<link rel="stylesheet" type="text/css" href="css/button.css">
</head>
<body>
<script src="js/button.js" type="text/javascript"></script>
<button id="btn" class="btnst" onclick="myFunction()">0</button>
</body>
</html>
----------JAVASCRIPT----------
let count = 0;
function myFunction() {
count+=1;
document.getElementById("btn").innerHTML = count;
}
YOUR-COMMAND &> YOUR-LOG.log &
This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on
SET STATISTICS TIME ON
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
SET STATISTICS TIME OFF;
And see the message tab it will look like this:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 10 ms.
(778 row(s) affected)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
Another way ..
<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />
Simple to understand. In Below code, maxKey is the key which is holding the max value.
int maxKey = 0;
int maxValue = 0;
for(int i : birds.keySet())
{
if(birds.get(i) > maxValue)
{
maxKey = i;
maxValue = birds.get(i);
}
}
What you're looking for is called a watchpoint.
Usage
(gdb) watch foo
: watch the value of variable foo
(gdb) watch *(int*)0x12345678
: watch the value pointed by an address, casted to whatever type you want
(gdb) watch a*b + c/d
: watch an arbitrarily complex expression, valid in the program's native language
Watchpoints are of three kinds:
You may choose the more appropriate for your needs.
For more information, check this out.
By C89, variable can only be defined at the top of a block.
if (a == 1)
int b = 10; // it's just a statement, syntacitially error
if (a == 1)
{ // refer to the beginning of a local block
int b = 10; // at the top of the local block, syntacitially correct
} // refer to the end of a local block
if (a == 1)
{
func();
int b = 10; // not at the top of the local block, syntacitially error, I guess
}
The best way is:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
Update
In the context file this mock must be listed before any autowired field depending on it is declared.
according to documentation you should just
{ path: '**', component: DefaultLayoutComponent }
on your app-routing.module.ts source: https://angular.io/guide/router
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
Try this
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.