The pragmatic regex (<[^>]+) style=".*?"
will solve this problem in all reasonable cases. The part of the match that is not the first captured group should be removed, like this:
$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $input);
Match a <
followed by one or more "not >
" until we come to space
and the style="..."
part. The /i
makes it work even with STYLE="..."
. Replace this match with $1
, which is the captured group. It will leave the tag as is, if the tag doesn't include style="..."
.
You can also simply use the jQuery plugin and package for TinyMCE it sorts out these kinds of issues.
Just posting in case it helps someone. For me, the following code worked perfect:
$(document).ready(function(){
$("#payment_status_div").hide();
var iframe = $('#FileFrame').contents();
iframe.find("#take_payment").click(function(){
$("#payment_status_div").show("slow");
});
});
Where 'FileFrame' is the iframe id and 'take_payment' is the button inside iframe. Since my form inside the iframe is posted to a different domain, when used load, I got an error message saying:
Blocked a frame with origin "https://www.example.com" from accessing a frame with origin "https://secure-test.worldpay.com". Protocols, domains, and ports must match.
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
If you use both finish and exit your app will close complitely
finish();
System.exit(0);
Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):
function mapNonNull(arr, cb) {_x000D_
return arr.reduce(function (accumulator, value, index, arr) {_x000D_
var result = cb.call(null, value, index, arr);_x000D_
if (result != null) {_x000D_
accumulator.push(result);_x000D_
}_x000D_
_x000D_
return accumulator;_x000D_
}, []);_x000D_
}_x000D_
_x000D_
var result = mapNonNull(["a", "b", "c"], function (value) {_x000D_
return value === "b" ? null : value; // exclude "b"_x000D_
});_x000D_
_x000D_
console.log(result); // ["a", "c"]
_x000D_
For Mac users:
1) Install @angular/cli globally
$ sudo npm install -g @angular/cli
/usr/local/Cellar/node/10.0.0/bin/ng -> /usr/local/Cellar/node/10.0.0/lib/node_modules/@angular/cli/bin/ng
2) Create alias for ng
alias ng="/usr/local/Cellar/node/10.0.0/lib/node_modules/@angular/cli/bin/ng"
Done
I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.
If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.
As an example, see it here a JavaScript that make select like editable.
Like said here and below, a failed request (i.e. the server is not found) returns false, no HTTP status code, since a reply has never been received.
Call curl_error()
.
Use the constructor overload which takes a Comparator<? super E> comparator
and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)
As has been said elsewhere: offer
and add
are just different interface method implementations. In the JDK source I've got, add
calls offer
. Although add
and offer
have potentially different behaviour in general due to the ability for offer
to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue
which is unbounded.
Here's an example of a priority queue sorting by string length:
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
// StringLengthComparator.java
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() - y.length(),
// which would be more efficient.
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
Here is the output:
short
medium
very long indeed
Both "git add *" and "git add SocialApp" called from top directory should add recursively all directories.
Probably you have no files in SocialApp/SourceCode/DevTrunk/SocialApp and this is the reason.
Try to call "touch SocialApp/SourceCode/DevTrunk/SocialApp/.temporary" (and check .gitignore) and then try git add again.
The query should be:
(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))
You missed & and ()
ES6 one liner
const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');
In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.
SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.
To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take
2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years
Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.
So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.
Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.
The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.
That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.
This problem happens as a result of calling a method without brackets. Take a look at the example below:
class SomeClass(object):
def __init__(self):
print 'I am starting'
def some_meth(self):
print 'I am a method()'
x = SomeClass()
''' Not adding the bracket after the method call would result in method bound error '''
print x.some_meth
''' However this is how it should be called and it does solve it '''
x.some_meth()
Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):
<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
<input type="text" name="user" ngModel required>
<button type="submit" [disabled]="loginForm.invalid">
Submit
</button>
</form>
As you can see:
Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.
If you are like me whose Java Control Panel does not show Security slider under Security Tab to change security level from High to Medium then follow these instructions: Java known bug: security slider not visible.
After installation, the checkbox to enable/disable Java and the security level slider do not appear in the Java Control Panel Security tab. This can occur with 7u10 and above.
This is due to a conflict that Java 7u10 and above have with standalone installations of JavaFX. Example: If Java 7u5 and JavaFX 2.1.1 are installed and if Java is updated to 7u11, the Java Control Panel does not show the checkbox or security slider.
It is recommended to uninstall all versions of Java and JavaFX before installing Java 7u10 and above.
Please follow the steps below for resolving this issue.
1. Remove all versions of Java and JavaFX through the Windows Uninstall Control Panel. Instructions on uninstalling Java.
2. Run the Microsoft uninstall utility to repair corrupted registry keys that prevents programs from being completely uninstalled or blocking new installations and updates.
3. Download and install the Windows offline installer package.
Encode.php
<h1>Encode HTML CODE</h1>
<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>
htmlencodeoutput.php
<?php
$code=bin2hex($_POST['inputval']);
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
$sublen=$totallen-1;
$fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";
?>
<textarea rows='20' cols='100'><?php echo $output?> </textarea>
You can encode HTML like this .
I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.
Using CSS Grid
HTML
<div class="container">
<i class="fab fa-5x fa-file"></i>
<span>text</span>
</div>
CSS
.container {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
}
The Android resource linking failed error can also appear if you have an error in any of your XML resources. In my case I was using the following line twice in one of my XML drawables in drawable folder:
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
I removed the duplicate line and the error disappeared. The error was a bit misleading:
Android resource linking failed Output: /Users/johndoe/Desktop/myapp/app/src/main/res/layout/activity_main.xml:2: error: resource drawable/bg_main (aka com.example.myproject:drawable/bg_main) not found.
According to the above error, the first thing you need to do is to proof read all the drawable resources that are accessed in the activity_main because the chances are higher that you will find the error. In the worst case scenario you might end up checking all your resource files.
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
Do something like this,
HTML :
<div style="width:500px;">
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
</div>
CSS :
div button{
display:inline-block;
}
Or
HTML :
<div style="width:500px;" id="container">
<div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
<div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
<div><button class="msgBtnBack">Back</button></div>
</div>
CSS :
#container div{
display:inline-block;
width:130px;
}
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
According to Parsing HTML documents - The end,
The browser parses the HTML source and runs deferred scripts.
A DOMContentLoaded
is dispatched at the document
when all the HTML has been parsed and have run. The event bubbles to the window
.
The browser loads resources (like images) that delay the load event.
A load
event is dispatched at the window
.
Therefore, the order of execution will be
DOMContentLoaded
event listeners of window
in the capture phaseDOMContentLoaded
event listeners of document
DOMContentLoaded
event listeners of window
in the bubble phaseload
event listeners (including onload
event handler) of window
A bubble load
event listener (including onload
event handler) in document
should never be invoked. Only capture load
listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.
window.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
/* Filter out load events not related to the document */_x000D_
if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
The short answer is “it depends.”
If you’re using bitwise operators anywhere (or if you’re referring to the length of an Array), the ranges are:
Unsigned: 0…(-1>>>0)
Signed: (-(-1>>>1)-1)…(-1>>>1)
(It so happens that the bitwise operators and the maximum length of an array are restricted to 32-bit integers.)
If you’re not using bitwise operators or working with array lengths:
Signed: (-Math.pow(2,53))…(+Math.pow(2,53))
These limitations are imposed by the internal representation of the “Number” type, which generally corresponds to IEEE 754 double-precision floating-point representation. (Note that unlike typical signed integers, the magnitude of the negative limit is the same as the magnitude of the positive limit, due to characteristics of the internal representation, which actually includes a negative 0!)
With image class name:
$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image
With image Id :
$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image
my problem was that i tried to check it with the debug.keystore , i mean running it through eclipse.I exported it with the keystore with which i published in alpha mode(it must be published before you can test it).installed it in my phone and than i could test it normally.
$('.div').html(val) will set the HTML values of all selected elements, $('.div').text(val) will set the text values of all selected elements.
I would guess that they correspond to Node#textContent and Element#innerHTML, respectively. (Gecko DOM references).
My working example of using style and android:theme simultaneously (API >= 21)
<android.support.v7.widget.SwitchCompat
android:id="@+id/wan_enable_nat_switch"
style="@style/Switch"
app:layout_constraintBaseline_toBaselineOf="@id/wan_enable_nat_label"
app:layout_constraintEnd_toEndOf="parent" />
<style name="Switch">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:paddingEnd">16dp</item>
<item name="android:focusableInTouchMode">true</item>
<item name="android:theme">@style/ThemeOverlay.MySwitchCompat</item>
</style>
<style name="ThemeOverlay.MySwitchCompat" parent="">
<item name="colorControlActivated">@color/colorPrimaryDark</item>
<item name="colorSwitchThumbNormal">@color/text_outline_not_active</item>
<item name="android:colorForeground">#42221f1f</item>
</style>
I had an issue with System.Linq not being recognized. The using
statement had a red squiggly, etc. The way I solved it was to change my website to target dotnet 3.5, then switch back to the original targeted framework (4.0 in my case).
With Bash (not POSIX) you can use process substitution to get the current line inside a variable. This enables you to use quotes to escape special characters:
while read line ; do cp "$line" ~/bar ; done < <(find . | grep foo)
You can try this, $myArray
as the Array
$filename = "mylog.txt";
$text = "";
foreach($myArray as $key => $value)
{
$text .= $key." : ".$value."\n";
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);
//if(data="undefined"){
This is an assignment statement, not a comparison. Also, "undefined"
is a string, it's a property. Checking it is like this: if (data === undefined)
(no quotes, otherwise it's a string value)
If it's not defined, you may be returning an empty string. You could try checking for a falsy
value like if (!data)
as well
in typeScript
of angular 6
, this code is working for me.
var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.
or for all values:
console.log(formData.getAll('name')); // return all values
With oracle 10.2g:
select level, sequence.NEXTVAL
from dual
connect by level <= (select max(pk) from tbl);
will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.
What I had to do is (in Javascript) is go through all pages by using a recursive function. It's dangerouse as instagram users could have thousands of pictures i a part from that (so your have to controle it) I use this code: (count parameter I think , doesn't do much)
instagramLoadDashboard = function(hash)
{
code = hash.split('=')[1];
$('#instagram-pictures .images-list .container').html('').addClass('loading');
ts = Math.round((new Date()).getTime() / 1000);
url = 'https://api.instagram.com/v1/users/self/media/recent?count=200&min_timestamp=0&max_timestamp='+ts+'&access_token='+code;
instagramLoadMediaPage(url, function(){
galleryHTML = instagramLoadGallery(instagramData);
//console.log(galleryHTML);
$('#instagram-pictures .images-list .container').html(galleryHTML).removeClass('loading');
initImages('#instagram-pictures');
IGStatus = 'loaded';
});
};
instagramLoadMediaPage = function (url, callback)
{
$.ajax({
url : url,
dataType : 'jsonp',
cache : false,
success: function(response){
console.log(response);
if(response.code == '400')
{
alert(response.error_message);
return false;
}
if(response.pagination.next_url !== undefined) {
instagramData = instagramData.concat(response.data);
return instagramLoadMediaPage(response.pagination.next_url,callback);
}
instagramData = instagramData.concat(response.data);
callback.apply();
}
});
};
instagramLoadGallery = function(images)
{
galleryHTML ='<ul>';
for(var i=0;i<images.length;i++)
{
galleryHTML += '<li><img src="'+images[i].images.thumbnail.url+'" width="120" id="instagram-'+images[i].id+' data-type="instagram" data-source="'+images[i].images.standard_resolution.url+'" class="image"/></li>';
}
galleryHTML +='</ul>';
return galleryHTML;
};
There some stuff related to print out a gallery of picture.
In new Xcode 7.0 use
//: Playground - noun: a place where people can play
import UIKit
var name = "How do you use String.substringWithRange?"
let range = name.startIndex.advancedBy(0)..<name.startIndex.advancedBy(10)
name.substringWithRange(range)
//OUT:
Read the tutorial on Java Web applications.
Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.
All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).
Here is a Tomcat tutorial.
Timestamp is a Date: https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
java.lang.Object
java.util.Date
java.sql.Timestamp
This is sufficient...
xpath xhtmlfile.xhtml '/html/head/title/text()' > titleOfXHTMLPage.txt
Create a new style
<style name="my_dialog_theme" parent="ThemeOverlay.AppCompat.Dialog">
<item name="colorAccent">@color/colorAccent</item> <!--header background-->
<item name="android:windowBackground">@color/colorPrimary</item> <!--calendar background-->
<item name="android:colorControlActivated">@color/colorAccent</item> <!--selected day-->
<item name="android:textColorPrimary">@color/colorPrimaryText</item> <!--days of the month-->
<item name="android:textColorSecondary">@color/colorAccent</item> <!--days of the week-->
</style>
Then initialize the dialog
Calendar mCalendar = new GregorianCalendar();
mCalendar.setTime(new Date());
new DatePickerDialog(mContext, R.style.my_dialog_theme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//do something with the date
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();
Result:
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....
jQuery(function ($) {
/**
* This small plugin will scrollTo a target, smoothly
*
* First argument = time to scroll to the target
* Second argument = set the hash in the current url yes or no
*/
$.fn.smoothScroll = function(t, setHash) {
// Set time to t variable to if undefined 500 for 500ms transition
t = t || 500;
setHash = (typeof setHash == 'undefined') ? true : setHash;
// Return this as a proper jQuery plugin should
return this.each(function() {
$('html, body').animate({
scrollTop: $(this).offset().top
}, t);
// Lets set the hash to the current ID since if an event was prevented this doesn't get done
if (this.id && setHash) {
window.location.hash = this.id;
}
});
};
});
Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.
(script should be within an onload section)
if (window.location.hash) {
window.scrollTo(0,0);
$(window.location.hash).smoothScroll();
}
Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.
(script should be within an onload section)
$('a[href^="#"]').click(function(e) {
e.preventDefault();
$($(this).attr('href')).smoothScroll();
});
Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/
Update
Alternative onclick handler to scroll to the top when theres only a hash:
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
// In this case we have only a hash, so maybe we want to scroll to the top of the page?
if(href.length === 1) { href = 'body' }
$(href).smoothScroll();
});
Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...
http://jsfiddle.net/sg3s/bZnWN/
Update 2
So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0);
it just scrolls the page to the left top. Added it to the code snippet above.
Another simplest way to connect is through an OdbcConnection using App.config file like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
</appSettings>
MyDB.mdb is my database file and it is present in current primary application folder with main exe file.
if your mdf file has password then use like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
</appSettings>
It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.
Pressing ESC quits from insert mode to normal mode, where you can press : to type in a command. Press i again to back to insert mode, and you are good to go.
I'm not a Vim guru, so someone else can be more experienced and give you other options.
I just had the same issue with me today. And I found it annoying. Though I have other two websites already under development from the same IIS but still was not able to create new site. Strange, but I did this.
You do not need to turn off/re-install anything other than what I have stated since it works.
Let me know if anybody had the same issue just like me and solved the same way. I think it was not the issue but a wrong way of creating website on localhost which Visual Studio rejects to open.
I hope this will help newbies.
Swift
Create UIView extension
private var bottomLineColorAssociatedKey : UIColor = .black
private var topLineColorAssociatedKey : UIColor = .black
private var rightLineColorAssociatedKey : UIColor = .black
private var leftLineColorAssociatedKey : UIColor = .black
extension UIView {
@IBInspectable var bottomLineColor: UIColor {
get {
if let color = objc_getAssociatedObject(self, &bottomLineColorAssociatedKey) as? UIColor {
return color
} else {
return .black
}
} set {
objc_setAssociatedObject(self, &bottomLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
@IBInspectable var bottomLineWidth: CGFloat {
get {
return self.bottomLineWidth
}
set {
DispatchQueue.main.async {
self.addBottomBorderWithColor(color: self.bottomLineColor, width: newValue)
}
}
}
@IBInspectable var topLineColor: UIColor {
get {
if let color = objc_getAssociatedObject(self, &topLineColorAssociatedKey) as? UIColor {
return color
} else {
return .black
}
} set {
objc_setAssociatedObject(self, &topLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
@IBInspectable var topLineWidth: CGFloat {
get {
return self.topLineWidth
}
set {
DispatchQueue.main.async {
self.addTopBorderWithColor(color: self.topLineColor, width: newValue)
}
}
}
@IBInspectable var rightLineColor: UIColor {
get {
if let color = objc_getAssociatedObject(self, &rightLineColorAssociatedKey) as? UIColor {
return color
} else {
return .black
}
} set {
objc_setAssociatedObject(self, &rightLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
@IBInspectable var rightLineWidth: CGFloat {
get {
return self.rightLineWidth
}
set {
DispatchQueue.main.async {
self.addRightBorderWithColor(color: self.rightLineColor, width: newValue)
}
}
}
@IBInspectable var leftLineColor: UIColor {
get {
if let color = objc_getAssociatedObject(self, &leftLineColorAssociatedKey) as? UIColor {
return color
} else {
return .black
}
} set {
objc_setAssociatedObject(self, &leftLineColorAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
@IBInspectable var leftLineWidth: CGFloat {
get {
return self.leftLineWidth
}
set {
DispatchQueue.main.async {
self.addLeftBorderWithColor(color: self.leftLineColor, width: newValue)
}
}
}
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.name = "topBorderLayer"
removePreviouslyAddedLayer(name: border.name ?? "")
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y : 0,width: self.frame.size.width, height: width)
self.layer.addSublayer(border)
self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 1111) )
}
func addRightBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.name = "rightBorderLayer"
removePreviouslyAddedLayer(name: border.name ?? "")
border.backgroundColor = color.cgColor
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width : width, height :self.frame.size.height)
self.layer.addSublayer(border)
self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 2222) )
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.name = "bottomBorderLayer"
removePreviouslyAddedLayer(name: border.name ?? "")
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width,width : self.frame.size.width,height: width)
self.layer.addSublayer(border)
self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 3333) )
}
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
let border = CALayer()
border.name = "leftBorderLayer"
removePreviouslyAddedLayer(name: border.name ?? "")
border.backgroundColor = color.cgColor
border.frame = CGRect(x:0, y:0,width : width, height : self.frame.size.height)
self.layer.addSublayer(border)
self.addObserver(self, forKeyPath: #keyPath(UIView.bounds), options: .new, context: UnsafeMutableRawPointer(bitPattern: 4444) )
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let objectView = object as? UIView,
objectView === self,
keyPath == #keyPath(UIView.bounds) {
switch context {
case UnsafeMutableRawPointer(bitPattern: 1111):
for border in self.layer.sublayers ?? [] {
if border.name == "topBorderLayer" {
border.frame = CGRect(x: 0, y : 0,width: self.frame.size.width, height: border.frame.height)
}
}
case UnsafeMutableRawPointer(bitPattern: 2222):
for border in self.layer.sublayers ?? [] {
if border.name == "rightBorderLayer" {
border.frame = CGRect(x: self.frame.size.width - border.frame.width, y: 0, width : border.frame.width, height :self.frame.size.height)
}
}
case UnsafeMutableRawPointer(bitPattern: 3333):
for border in self.layer.sublayers ?? [] {
if border.name == "bottomBorderLayer" {
border.frame = CGRect(x: 0, y: self.frame.size.height - border.frame.height,width : self.frame.size.width,height: border.frame.height)
}
}
case UnsafeMutableRawPointer(bitPattern: 4444):
for border in self.layer.sublayers ?? [] {
if border.name == "leftBorderLayer" {
border.frame = CGRect(x:0, y:0,width : border.frame.width, height : self.frame.size.height)
}
}
default:
break
}
}
}
func removePreviouslyAddedLayer(name : String) {
if self.layer.sublayers?.count ?? 0 > 0 {
self.layer.sublayers?.forEach {
if $0.name == name {
$0.removeFromSuperlayer()
}
}
}
}
}
Objective C
Create category class of UIView
UIView+Border.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface UIView (Border)
@property (nonatomic) IBInspectable UIColor *topLineColor;
@property (nonatomic) IBInspectable CGFloat topLineWidth;
@property (nonatomic) IBInspectable UIColor *bottomLineColor;
@property (nonatomic) IBInspectable CGFloat bottomLineWidth;
@property (nonatomic) IBInspectable UIColor *rightLineColor;
@property (nonatomic) IBInspectable CGFloat rightLineWidth;
@property (nonatomic) IBInspectable UIColor *leftLineColor;
@property (nonatomic) IBInspectable CGFloat leftLineWidth;
- (void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
@end
UIView+Border.m
static void *topBorderContext = &topBorderContext;
static void *bottomBorderContext = &bottomBorderContext;
static void *leftBorderContext = &leftBorderContext;
static void *rightBorderContext = &rightBorderContext;
static char bottomLineColorKey,topLineColorKey,rightLineColorKey,leftLineColorKey;
@implementation UIView(Utility)
@dynamic borderColor,borderWidth,cornerRadius,bottomLineWidth,topLineWidth,rightLineWidth,leftLineWidth;
-(void)setBorderColor:(UIColor *)borderColor{
[self.layer setBorderColor:borderColor.CGColor];
}
-(void)setBorderWidth:(CGFloat)borderWidth{
[self.layer setBorderWidth:borderWidth];
}
-(void)setCornerRadius:(CGFloat)cornerRadius{
[self.layer setCornerRadius:cornerRadius];
}
// for Bottom Line
- (UIColor *)bottomLineColor {
return objc_getAssociatedObject(self, &bottomLineColorKey);
}
- (void)setBottomLineColor:(UIColor *)bottomLineColor {
objc_setAssociatedObject(self, &bottomLineColorKey,
bottomLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setBottomLineWidth:(CGFloat)bottomLineWidth {
[self addBottomBorderWithColor:[self bottomLineColor] andWidth:bottomLineWidth];
}
// for top Line
- (UIColor *)topLineColor {
return objc_getAssociatedObject(self, &topLineColorKey);
}
- (void)setTopLineColor:(UIColor *)topLineColor {
objc_setAssociatedObject(self, &topLineColorKey,
topLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)setTopLineWidth:(CGFloat)topLineWidth{
[self addTopBorderWithColor:[self topLineColor] andWidth:topLineWidth];
}
// for right Line
- (UIColor *)rightLineColor {
return objc_getAssociatedObject(self, &rightLineColorKey);
}
-(void)setRightLineColor:(UIColor *)rightLineColor {
objc_setAssociatedObject(self, &rightLineColorKey,
rightLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setRightLineWidth:(CGFloat)rightLineWidth{
[self addRightBorderWithColor:[self rightLineColor] andWidth:rightLineWidth];
}
// for left Line
-(UIColor *)leftLineColor {
return objc_getAssociatedObject(self, &leftLineColorKey);
}
-(void)setLeftLineColor:(UIColor *)leftLineColor{
objc_setAssociatedObject(self, &leftLineColorKey,
leftLineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setLeftLineWidth:(CGFloat)leftLineWidth{
[self addLeftBorderWithColor:[self leftLineColor] andWidth:leftLineWidth];
}
- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
dispatch_async(dispatch_get_main_queue(), ^{
CALayer *border = [CALayer layer];
border.name = @"topBorderLayer";
[self removePreviouslyAddedLayer:border.name];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
[self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:topBorderContext];
});
}
- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
dispatch_async(dispatch_get_main_queue(), ^{
CALayer *border = [CALayer layer];
border.name = @"bottomBorderLayer";
[self removePreviouslyAddedLayer:border.name];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
[self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:bottomBorderContext];
});
}
- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
dispatch_async(dispatch_get_main_queue(), ^{
CALayer *border = [CALayer layer];
border.name = @"leftBorderLayer";
[self removePreviouslyAddedLayer:border.name];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
[self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:leftBorderContext];
});
}
- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
dispatch_async(dispatch_get_main_queue(), ^{
CALayer *border = [CALayer layer];
border.name = @"rightBorderLayer";
[self removePreviouslyAddedLayer:border.name];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
[self addObserver:self forKeyPath: @"bounds" options:NSKeyValueObservingOptionNew context:rightBorderContext];
});
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == topBorderContext) {
for (CALayer *border in self.layer.sublayers) {
if ([border.name isEqualToString:@"topBorderLayer"]) {
[border setFrame:CGRectMake(0, 0, self.frame.size.width, border.frame.size.height)];
}
}
} else if (context == bottomBorderContext) {
for (CALayer *border in self.layer.sublayers) {
if ([border.name isEqualToString:@"bottomBorderLayer"]) {
[border setFrame:CGRectMake(0, self.frame.size.height - border.frame.size.height, self.frame.size.width, border.frame.size.height)];
}
}
} else if (context == leftBorderContext) {
for (CALayer *border in self.layer.sublayers) {
if ([border.name isEqualToString:@"leftBorderLayer"]) {
[border setFrame:CGRectMake(0, 0, border.frame.size.width, self.frame.size.height)];
}
}
} else if (context == rightBorderContext) {
for (CALayer *border in self.layer.sublayers) {
if ([border.name isEqualToString:@"rightBorderLayer"]) {
[border setFrame:CGRectMake(self.frame.size.width - border.frame.size.width, 0, border.frame.size.width, self.frame.size.height)];
}
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)removePreviouslyAddedLayer:(NSString *)name {
if (self.layer.sublayers.count > 0) {
for (CALayer *layer in self.layer.sublayers) {
if ([layer.name isEqualToString:name]) {
[layer removeFromSuperlayer];
}
}
}
}
@end
Usage :- Select any control from storyboard, then show attribute inspector (Right side) You will see below image Example.(Note : Border only appear at run time.)
Now You can set any side of border colour and width.
jQuery Mobile doesn't seem to have a css class to center elements (I searched through its css).
But you can write your own additional css.
Try creating your own:
.center-button{
margin: 0 auto;
}
example HTML:
<div data-role="button" class="center-button">button text</div>
and see what happens. You might need to set text-align to center in the wrapping tag, so this might work better:
.center-wrapper{
text-align: center;
}
.center-wrapper * {
margin: 0 auto;
}
example HTML:
<div class="center-wrapper">
<div data-role="button">button text</div>
</div>
class Permutation
{
public static List<string> Permutate(string seed, List<string> lstsList)
{
loopCounter = 0;
// string s="\w{0,2}";
var lstStrs = PermuateRecursive(seed);
Trace.WriteLine("Loop counter :" + loopCounter);
return lstStrs;
}
// Recursive function to find permutation
private static List<string> PermuateRecursive(string seed)
{
List<string> lstStrs = new List<string>();
if (seed.Length > 2)
{
for (int i = 0; i < seed.Length; i++)
{
str = Swap(seed, 0, i);
PermuateRecursive(str.Substring(1, str.Length - 1)).ForEach(
s =>
{
lstStrs.Add(str[0] + s);
loopCounter++;
});
;
}
}
else
{
lstStrs.Add(seed);
lstStrs.Add(Swap(seed, 0, 1));
}
return lstStrs;
}
//Loop counter variable to count total number of loop execution in various functions
private static int loopCounter = 0;
//Non recursive version of permuation function
public static List<string> Permutate(string seed)
{
loopCounter = 0;
List<string> strList = new List<string>();
strList.Add(seed);
for (int i = 0; i < seed.Length; i++)
{
int count = strList.Count;
for (int j = i + 1; j < seed.Length; j++)
{
for (int k = 0; k < count; k++)
{
strList.Add(Swap(strList[k], i, j));
loopCounter++;
}
}
}
Trace.WriteLine("Loop counter :" + loopCounter);
return strList;
}
private static string Swap(string seed, int p, int p2)
{
Char[] chars = seed.ToCharArray();
char temp = chars[p2];
chars[p2] = chars[p];
chars[p] = temp;
return new string(chars);
}
}
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
I was facing the same problem . Solution is given below
Right click on Source Program > Properties > Configuration Properties > C/C++ > Language > Now change Open MP support flag to Yes....
You will get the desired result.
If there's any performance difference (which I doubt), it will be negligible. Concentrate on writing the simplest, most readable code you can.
Having said that, try to get over your aversion of the conditional operator - while it's certainly possible to overuse it, it can be really useful in some cases. In the specific example you gave, I'd definitely use the conditional operator.
Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.
@echo off
set /p "ipa= ENTER FOLDER NAME TO DELETE> "
set ipad="%ipa%"
IF not EXIST %ipad% GOTO notfound
IF EXIST %ipad% GOTO found
:found
echo DONOT CLOSE THIS WINDOW
md ccooppyy
xcopy %ipad%\*.* ccooppyy /s > NUL
rd %ipad% /s /q
ren ccooppyy %ipad%
cls
echo SUCCESS, PRESS ANY KEY TO EXIT
pause > NUL
exit
:notfound
echo I COULDN'T FIND THE FOLDER %ipad%
pause
exit
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
You can do the following if you already know the number of fields of the input:
client_name = raw_input("Enter you first and last name: ")
first_name, last_name = client_name.split()
and in case you want to iterate through the fields separated by spaces, you can do the following:
some_input = raw_input() # This input is the value separated by spaces
for field in some_input.split():
print field # this print can be replaced with any operation you'd like
# to perform on the fields.
A more generic use of the "split()" function would be:
result_list = some_string.split(DELIMITER)
where DELIMETER is replaced with the delimiter you'd like to use as your separator, with single quotes surrounding it.
An example would be:
result_string = some_string.split('!')
The code above takes a string and separates the fields using the '!' character as a delimiter.
If you use Babel you can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:
let x = {a: 1, b: 2, c: 3, z:26};
let {b, ...y} = x;
and it will be transpiled into:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var x = { a: 1, b: 2, c: 3, z: 26 };
var b = x.b;
var y = _objectWithoutProperties(x, ["b"]);
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
When dealing with a hash {}
, use both the key and value to the block inside the ||
.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]
Actually, all the other answers have flaws. The most reliable way is:
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
Detailed Explanation:
Using "%1"=="-b"
will flat out crash if passing argument with spaces and quotes. This is the least reliable method.
IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "a b"
b""=="-b" was unexpected at this time.
Using [%1]==[-b]
is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.
IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "-b"
(does not match, and jumps to UNKNOWN instead of SPECIFIC)
Using "%~1"=="-b"
is the most reliable. %~1
will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"
(all of the above tests work correctly)
You can also use REPLACE()
:
UPDATE Table
SET Column = REPLACE(Column, 'Test123', 'Test')
i tested this on apache2 on many different hosting and it works great.
use this htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
be sure you have enabled mod_rewirte
with a phpinfo();
then do this in config/config.php:
$config['index_url'] = '';
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
if it doesn't works yet, try to change the $config['uri_protocol']='AUTO'
to one of the listed inside application/config/config.php
file on line 40/54:
sometimes i used : REQUEST_URI
instead of AUTO
or "QUERY_STRING"
for goDaddy hostings
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
In this case , this code
{<td><span onClick={this.toggle()}>Details</span></td>}
causes toggle function to call immediately and re render it again and again thus making infinite calls.
so passing only the reference to that toggle method will solve the problem.
so ,
{<td><span onClick={this.toggle}>Details</span></td>}
will be the solution code.
If you want to use the () , you should use an arrow function like this
{<td><span onClick={()=> this.toggle()}>Details</span></td>}
In case you want to pass parameters you should choose the last option and you can pass parameters like this
{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}
In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.
The element you were trying to find wasn’t in the DOM when your script ran.
The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.
Consider the following markup; script #1 fails to find the <div>
while script #2 succeeds:
<script>_x000D_
console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
So, what should you do? You've got a few options:
Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:
<body>_x000D_
<button id="test">click me</button>_x000D_
<script>_x000D_
document.getElementById("test").addEventListener("click", function() {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
</script>_x000D_
</body><!-- closing body tag -->
_x000D_
Note: Placing scripts at the bottom is generally considered a best practice.
ready()
Defer your script until the DOM has been completely parsed, using $(handler)
:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
$("#test").click(function() {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
});_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
Note: You could simply bind to DOMContentLoaded
or window.onload
but each has its caveats. jQuery's ready()
delivers a hybrid solution.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.
jQuery's on()
performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).on("click", "#test", function(e) {_x000D_
console.log("clicked: %o", this);_x000D_
});_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document
(for demonstrative purposes), you should select the nearest reliable ancestor.
defer
attributeUse the defer
attribute of <script>
.
[
defer
, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firingDOMContentLoaded
.
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
For reference, here's the code from that external script:
document.getElementById("test").addEventListener("click", function(e){
console.log("clicked: %o", this);
});
Note: The defer
attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer
can only be used for external scripts, i.e.: those having a src
attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10
I had a routerLink="."
attribute at one of my HTML tags which caused that error
This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.
var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);
A solution is to add captures for the preceding and following text:
str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")
The cleaner solution without NullPointerException is:
map.replace(key, map.get(key) + 1);
To Read JSON File, refer this simple example
Your JSON File (StreamingAssets/Player.json)
{
"Name": "MyName",
"Level": 4
}
C# Script
public class Demo
{
public void ReadJSON()
{
string path = Application.streamingAssetsPath + "/Player.json";
string JSONString = File.ReadAllText(path);
Player player = JsonUtility.FromJson<Player>(JSONString);
Debug.Log(player.Name);
}
}
[System.Serializable]
public class Player
{
public string Name;
public int Level;
}
I do not believe this is possible. You could add class1
to all elements which also have class2
. If this is not practical to do manually, you could do it automatically with JavaScript (fairly easy to do with jQuery).
I had the same problem. I installed Eclipse 3.7 into a new folder, and created a new workspace. I launch Eclipse with a -data argument to reference the new workspace.
When I attempt to connect to the marketplace to get the SVN and Maven plugins, I get the same issues described in OP.
After a few more tries, I cleared the proxy settings for SOCKS protocol, and I was able to connect to the marketplace.
So the solution for me was to configure the manual settings for HTTP and HTTPS proxy, clear the settings for SOCKS, and restart Eclipse.
/usr/local/ssl/openssl.cnf
A path like this means the program has been compiled with either Cygwin or MSYS. If you must use this openssl
then you will need an interpreter that understands those paths, like Bash, which is provided by Cygwin or MSYS.
Another option would be to download or compile a Windows Native version of openssl
. Using that the program would instead require a path like
C:\Users\Steven\ssl\openssl.cnf
which would be better suited for the Command Prompt.
CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.
JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":
Add to your script:
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
Then just attach capitalize() to any selector:
$('#myform input').capitalize();
\bdbo\..*fn
I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform
(although I only knew car
and Platform
at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.
Here's the regex I used to find it:
\bcar\..*Platform
Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.
There is apparently some sort of network problem between you and the SQL Server.
edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.
If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?
The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof
function isJson(obj) {
var t = typeof obj;
return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}
Nobody suggested Vagrant yet, so here it is, Vagrant box for OSX
vagrant init https://vagrant-osx.nyc3.digitaloceanspaces.com/osx-sierra-0.3.1.box
vagrant up
and you have a MACOS virtual machine. But according to Apple's EULA, you still need to run it on MacOS hardware :D But anywhere, here's one to all of you geeks who wiped MacOS and installed Ubuntu :D
Unfortunately, you can't run the editors from inside using SSH X-forwarding
option.
I had a similar problem and found the following command to work:
sudo systemctl stop tomcat
After running this command you can type the following to verify that it is "disabled":
systemctl list-units
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});
Fire the below command. It gives a list of modules.
sudo apt-cache search php5-
Then fire the below command with the module name to be installed:
sudo apt-get install name of the module
For reference, see How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu.
Given the string foobarbarfoo
:
bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
(?=)
Find expression A where expression B follows:
A(?=B)
(?!)
Find expression A where expression B does not follow:
A(?!B)
(?<=)
Find expression A where expression B precedes:
(?<=B)A
(?<!)
Find expression A where expression B does not precede:
(?<!B)A
(?>)
An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
(?>foo|foot)s
applied to foots
will match its 1st alternative foo
, then fail as s
does not immediately follow, and stop as backtracking is disabledA non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
(foo|foot)s
applied to foots
will:
foo
, then fail as s
does not immediately follow in foots
, and backtrack to its 2nd alternative;foot
, then succeed as s
immediately follows in foots
, and stop.You could try setting the failOnError
property (see plugin documentation) to false
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<failOnError>false</failOnError>
</configuration>
</execution>
</executions>
</plugin>
As you can see from the docs, the default value is true
.
From the jQuery documentation:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
Balanced tree is a tree whose height is of order of log(number of elements in the tree).
height = O(log(n))
O, as in asymptotic notation i.e. height should have same or lower asymptotic
growth rate than log(n)
n: number of elements in the tree
The definition given "a tree is balanced of each sub-tree is balanced and the height of the two sub-trees differ by at most one" is followed by AVL trees.
Since, AVL trees are balanced but not all balanced trees are AVL trees, balanced trees don't hold this definition and internal nodes can be unbalanced in them. However, AVL trees require all internal nodes to be balanced.
For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.
For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective
You'll basically need to do the following:
Excel.Range allCellsRng;
string lowerRightCell = "IV65536";
allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
foreach (Range cell in allCellsRng)
{
if (null == cell.Value2 || isBlank(cell.Value2))
{
// Do something.
}
else if (isText(cell.Value2))
{
// Do something.
}
else if (isNumeric(cell.Value2))
{
// Do something.
}
}
For Excel 2007, try this MSDN reference.
The redis version on windows was published by microsoft open tech team But recently this project has been archived to https://github.com/MicrosoftArchive/redis read-only and will not update. Has stopped development
You can put the username() function in another page, and send the form to that page...
In Java 10:
String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));
Set.copyOf
returns an unmodifiable Set
containing the elements of the given Collection
.
The given Collection
must not be null
, and it must not contain any null
elements.
To start with, I do not suggest using "*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the +
sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the {x, y}
syntax to specifically specify the desired length.
However, if you really do need non-greedy repetition, I suggest consulting the all-powerful ?
. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible.
That being said, I would be very careful with the ?
as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify ((1)
(note the lack of a second rparen) as a match.
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
Use os.path.getsize(path)
which will
Return the size, in bytes, of path. Raise
OSError
if the file does not exist or is inaccessible.
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')
Or use os.stat(path).st_size
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
Or use Path(path).stat().st_size
(Python 3.4+)
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
Use this, two<anything any number of times><end of line>
's/two.*$/BLAH/g'
com.google.common.base.Strings.isNullOrEmpty(String string)
from Google Guava
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
With Underscore.js, to merge an array of objects do:
var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];
_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });
It results in:
Object {a: 1, b: 2, c: 3, d: 4}
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Login APi Put Two Parameters
{
"UserId": "1234",
"Password":"1234"
}
Login Response
{
"UserId": "1234",
"FirstName": "Keshav",
"LastName": "Gera",
"ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {
public static final String BASE_URL = "Your Base Url ";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface interface
interface APIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
Login Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("UserId")
public String UserId;
@SerializedName("FirstName")
public String FirstName;
@SerializedName("LastName")
public String LastName;
@SerializedName("ProfilePicture")
public String ProfilePicture;
@SerializedName("Password")
public String Password;
@SerializedName("ResponseCode")
public String ResponseCode;
@SerializedName("ResponseMessage")
public String ResponseMessage;
public LoginResponse(String UserId, String Password) {
this.UserId = UserId;
this.Password = Password;
}
public String getUserId() {
return UserId;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getProfilePicture() {
return ProfilePicture;
}
public String getResponseCode() {
return ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
public class MainActivity extends AppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
private void loginRetrofit2Api(String userId, String password) {
final LoginResponse login = new LoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
String responseCode = loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
public boolean checkValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
return false;
} else if (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
return false;
}
return true;
}
}
CommonMethod.java
public class CommonMethod {
public static final String DISPLAY_MESSAGE_ACTION =
"com.codecube.broking.gcm";
public static final String EXTRA_MESSAGE = "message";
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connectivityManager
= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLogin"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:padding="5dp"
android:background="@mipmap/ic_launcher_round"
/>
<TextView
android:id="@+id/txtLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgLogin"
android:layout_centerHorizontal="true"
android:text="Holostik Track and Trace"
android:textSize="20dp"
android:visibility="gone" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:layout_marginTop="8dp"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:fontFamily="sans-serif"
android:gravity="top"
android:hint="Login ID"
android:maxLines="10"
android:paddingLeft="@dimen/edit_input_padding"
android:paddingRight="@dimen/edit_input_padding"
android:paddingTop="@dimen/edit_input_padding"
android:singleLine="true"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout1"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rel12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
>
<Button
android:id="@+id/loginSub"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/border_button"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginRight="10dp"
android:text="Login"
android:textColor="#ffffff" />
</RelativeLayout>
</LinearLayout>
If i
is the int
, then
char c = i;
makes it a char
. You might want to add a check that the value is <128
if it comes from an untrusted source. This is best done with isascii
from <ctype.h>
, if available on your system (see @Steve Jessop's comment to this answer).
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.
I would suggest you consider a method like
IntegerUtilities.isValidInteger(String s)
which you then implement as you see fit. If you want the result carried back - perhaps because you use Integer.parseInt() anyway - you can use the array trick.
IntegerUtilities.isValidInteger(String s, int[] result)
where you set result[0] to the integer value found in the process.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
Please go to File| Settings | Tools | Python Integrated Tools and change the default test runner to py.test. Then you'll get the py.test option to create tests instead of the unittest one.
Mac OS : Big Sur
First Priority
sudo xcode-select --reset
sudo xcodebuild -license
Second Priority
xcode-select --install
try this
CSS add your code
.select_join option{
font-size:13px;
}
You want to set the first character of the string to zero, like this:
char myString[10];
myString[0] = '\0';
(Or myString[0] = 0;
)
Or, actually, on initialisation, you can do:
char myString[10] = "";
But that's not a general way to set a string to zero length once it's been defined.
Use the -f
option to git tag
:
-f
--force
Replace an existing tag with the given name (instead of failing)
You probably want to use -f
in conjunction with -a
to force-create an annotated tag instead of a non-annotated one.
Delete the tag on any remote before you push
git push origin :refs/tags/<tagname>
Replace the tag to reference the most recent commit
git tag -fa <tagname>
Push the tag to the remote origin
git push origin master --tags
Here are a few points:
You could consider upgrading to HttpClient 4 (generally speaking, if you can, I don't think version 3 is still actively supported).
A 500 status code is a server error, so it might be useful to see what the server says (any clue in the response body you're printing?). Although it might be caused by your client, the server shouldn't fail this way (a 4xx error code would be more appropriate if the request is incorrect).
I think setDoAuthentication(true)
is the default (not sure). What could be useful to try is pre-emptive authentication works better:
client.getParams().setAuthenticationPreemptive(true);
Otherwise, the main difference between curl -d ""
and what you're doing in Java is that, in addition to Content-Length: 0
, curl also sends Content-Type: application/x-www-form-urlencoded
. Note that in terms of design, you should probably send an entity with your POST
request anyway.
A better way to write the async function would be by returning a pending Promise from the start and then handling both rejections and resolutions within the callback of the promise, rather than just spitting out a rejected promise on error. Example:
async foo(id: string): Promise<A> {
return new Promise(function(resolve, reject) {
// execute some code here
if (success) { // let's say this is a boolean value from line above
return resolve(success);
} else {
return reject(error); // this can be anything, preferably an Error object to catch the stacktrace from this function
}
});
}
Then you just chain methods on the returned promise:
async function bar () {
try {
var result = await foo("someID")
// use the result here
} catch (error) {
// handle error here
}
}
bar()
Source - this tutorial:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Neither of these answers get to the core reason refresh tokens exist. Obviously, you can always get a new access-token/refresh-token pair by sending your client credentials to the auth server - that's how you get them in the first place.
So the sole purpose of the refresh token is to limit the use of the client credentials being sent over the wire to the auth service. The shorter the TTL of the access-token, the more often the client credentials will have to be used to obtain a new access-token, and therefore the more opportunities attackers have to compromise the client credentials (although this may be super difficult anyway if asymmetric encryption is being used to send them). So if you have a single-use refresh-token, you can make the TTL of access-tokens arbitrarily small without compromising the client credentials.
It's related about revert origin : to set origin when the object is drag : just use $(this).data("draggable").originalPosition = {top:0, left:0};
For example : i use like this
drag: function() {
var t = $(this);
left = parseInt(t.css("left")) * -1;
if(left > 0 ){
left = 0;
t.draggable( "option", "revert", true );
$(this).data("draggable").originalPosition = {top:0, left:0};
}
else t.draggable( "option", "revert", false );
$(".slider-work").css("left", left);
}
According to the docker-compose reference,
Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).
My docker-compose.yml
looks like:
mysql:
image: mysql:5.7
ports:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
-------------------------------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:32769->3306/tcp
Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.
Ports are not exposed to host machines, only exposed to other services.
mysql:
image: mysql:5.7
expose:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
---------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 3306/tcp
In recent versions of Docker, expose
doesn't have any operational impact anymore, it is just informative. (see also)
If a single byte is used to store a character, there are 256 possible combinations, and thereby you can save 256 different characters. Collation is the pattern which defines the characters and the rules by which they are compared and sorted.
1252, which is the Latin1 (ANSI), is the most common. Single-byte character sets are also inadequate to store all the characters used by many languages. For example, some Asian languages have thousands of characters, so they must use two bytes per character.
When systems using multiple code pages are used in a network, it becomes difficult to manage communication. To standardize things, the ISO and Unicode consortium introduced the Unicode. Unicode uses two bytes to store each character. That is 65,536 different characters can be defined, so almost all the characters can be covered with Unicode. If two computers use Unicode, every symbol will be represented in the same way and no conversion is needed - this is the idea behind Unicode.
SQL Server has two categories of character datatypes:
If we need to save character data from multiple countries, always use Unicode.
letronje's solution only works for very simple pages. document.body.innerHTML +=
takes the HTML text of the body, appends the iframe HTML, and sets the innerHTML of the page to that string. This will wipe out any event bindings your page has, amongst other things. Create an element and use appendChild
instead.
$.post('/create_binary_file.php', postData, function(retData) {
var iframe = document.createElement("iframe");
iframe.setAttribute("src", retData.url);
iframe.setAttribute("style", "display: none");
document.body.appendChild(iframe);
});
Or using jQuery
$.post('/create_binary_file.php', postData, function(retData) {
$("body").append("<iframe src='" + retData.url+ "' style='display: none;' ></iframe>");
});
What this actually does: perform a post to /create_binary_file.php with the data in the variable postData; if that post completes successfully, add a new iframe to the body of the page. The assumption is that the response from /create_binary_file.php will include a value 'url', which is the URL that the generated PDF/XLS/etc file can be downloaded from. Adding an iframe to the page that references that URL will result in the browser promoting the user to download the file, assuming that the web server has the appropriate mime type configuration.
Based in @Daniel answer I did:
for remote in \`git branch | grep -v master\`
do
git push -u origin $remote
done
OK this does fix it I tried it today Sept 5-2012 but you have to be sure to check out the demo
The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...
9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins
here is the link to the Demo It works great heres the code I used
title_dialog.modal();
title_dialog.modalResponsiveFix({})
title_dialog.touchScroll();
Actually you can do with VS Code the following:
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
For windows server I think u can use this:
<?php
echo exec('getmac');
?>
for last 7 characters
$newstring = substr($dynamicstring, -7);
$newstring : 5409els
for first 7 characters
$newstring = substr($dynamicstring, 0, 7);
$newstring : 2490slk
Use the enumerate()
function to generate the index along with the elements of the sequence you are looping over:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
Try creating a new pivot table, and not just refreshing.
I had a case where I forgot to add in a few dates. After adding them in I updated the pivot table range and hit refresh. They appeared at the end of the pivot table, out of order. I then tried to simply create a new pivot table and the dates where all in order.
That's a very general question. One answer is: "it depends what kind of UUID you wish to generate". But a better one is this: "Well, before I answer, can you tell us why you need to code up your own UUID generation algorithm instead of calling the UUID generation functionality that most modern operating systems provide?"
Doing that is easier and safer, and since you probably don't need to generate your own, why bother coding up an implementation? In that case, the answer becomes use whatever your O/S, programming language or framework provides. For example, in Windows, there is CoCreateGuid or UuidCreate or one of the various wrappers available from the numerous frameworks in use. In Linux there is uuid_generate.
If you, for some reason, absolutely need to generate your own, then at least have the good sense to stay away from generating v1 and v2 UUIDs. It's tricky to get those right. Stick, instead, to v3, v4 or v5 UUIDs.
Update:
In a comment, you mention that you are using Python and link to this. Looking through the interface provided, the easiest option for you would be to generate a v4 UUID (that is, one created from random data) by calling uuid.uuid4()
.
If you have some data that you need to (or can) hash to generate a UUID from, then you can use either v3 (which relies on MD5) or v5 (which relies on SHA1). Generating a v3 or v5 UUID is simple: first pick the UUID type you want to generate (you should probably choose v5) and then pick the appropriate namespace and call the function with the data you want to use to generate the UUID from. For example, if you are hashing a URL you would use NAMESPACE_URL
:
uuid.uuid3(uuid.NAMESPACE_URL, 'https://ripple.com')
Please note that this UUID will be different than the v5 UUID for the same URL, which is generated like this:
uuid.uuid5(uuid.NAMESPACE_URL, 'https://ripple.com')
A nice property of v3 and v5 URLs is that they should be interoperable between implementations. In other words, if two different systems are using an implementation that complies with RFC4122, they will (or at least should) both generate the same UUID if all other things are equal (i.e. generating the same version UUID, with the same namespace and the same data). This property can be very helpful in some situations (especially in content-addressible storage scenarios), but perhaps not in your particular case.
In your layout XML:
<TextView
android:id="@+id/myAwesomeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
Then, in your activity class:
// globally
TextView myAwesomeTextView = (TextView)findViewById(R.id.myAwesomeTextView);
//in your OnCreate() method
myAwesomeTextView.setText("My Awesome Text");
I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch
, then remove them manually, but this will not work well if there are a lot.
Here is a solution that utilizes bash arrays to capture all files.
# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)
git rm –-cached "${rmlist[@]}"
git commit -m 'ignore update'
For me this single line solution works very well
XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument
Just ask it for the objectForKey:@"b"
. If it returns nil
, no object is set at that key.
if ([xyz objectForKey:@"b"]) {
NSLog(@"There's an object set for key @\"b\"!");
} else {
NSLog(@"No object set for key @\"b\"");
}
Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];
. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).
I encountered the same issue. I found the reason is that I had a slightly-outdated python six package.
>>> import html5lib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/html5lib/__init__.py", line 16, in <module>
from .html5parser import HTMLParser, parse, parseFragment
File "/usr/local/lib/python2.7/site-packages/html5lib/html5parser.py", line 2, in <module>
from six import with_metaclass, viewkeys, PY3
ImportError: cannot import name viewkeys
Upgrading your six package will solve the issue:
sudo pip install six=1.10.0
If you're using version 3.x of Bootstrap, the correct way to do this now is:
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
Scroll down to the events section to learn more.
http://getbootstrap.com/javascript/#modals-usage
This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.
A modification of the code by @CarloCannas:
public static void sudo(String...strings) {
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
(You are welcome to find a better place for outputStream.close())
Usage example:
private static void suMkdirs(String path) {
if (!new File(path).isDirectory()) {
sudo("mkdir -p "+path);
}
}
Update: To get the result (the output to stdout), use:
public static String sudoForResult(String...strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try{
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e){
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
The utility to silently close a number of Closeables (So?ket may be no Closeable) is:
public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
Log.d("closing: "+x);
if (x instanceof Closeable) {
((Closeable)x).close();
} else if (x instanceof Socket) {
((Socket)x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket)x).close();
} else {
Log.d("cannot close: "+x);
throw new RuntimeException("cannot close "+x);
}
} catch (Throwable e) {
Log.x(e);
}
}
}
}
}
classList
DOM API:A very convenient manner of adding and removing classes is the classList
DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
"Sed ut perspiciatis unde omnis _x000D_
iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
voluptatem quia voluptas _x000D_
</div>_x000D_
_x000D_
<button onclick="addClass()">AddClass</button>_x000D_
_x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
_x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
_x000D_
typeof:
var foo;
if (typeof foo == "undefined"){
//do stuff
}
CSS Grid layout
Like tables, grid layout enables an author to align elements into columns and rows.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
To change the column sizes, take a look at the grid-template-columns
property.
dl {_x000D_
display: grid;_x000D_
grid-template-columns: max-content auto;_x000D_
}_x000D_
_x000D_
dt {_x000D_
grid-column-start: 1;_x000D_
}_x000D_
_x000D_
dd {_x000D_
grid-column-start: 2;_x000D_
}
_x000D_
<dl>_x000D_
<dt>Mercury</dt>_x000D_
<dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd>_x000D_
<dt>Venus</dt>_x000D_
<dd>Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.</dd>_x000D_
<dt>Earth</dt>_x000D_
<dd>Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.</dd>_x000D_
</dl>
_x000D_
You can use string.punctuation with built-in NLTK stopwords list:
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation
words = tokenize(text)
wordsWOStopwords = removeStopWords(words)
def tokenize(text):
sents = sent_tokenize(text)
return [word_tokenize(sent) for sent in sents]
def removeStopWords(words):
customStopWords = set(stopwords.words('english')+list(punctuation))
return [word for word in words if word not in customStopWords]
NLTK stopwords complete list
A possible solution for this is that you most probably not bundling your application first, perform the following steps and then deploy your app-debug.apk to your device
$ cd myproject
$ react-native start > /dev/null 2>&1 &
$ curl "http://localhost:8081/index.android.bundle?platform=android" -o "android/app/src/main/assets/index.android.bundle"
(if the folder assets
does not exists create it)
Then run from project root
$> (cd android/ && ./gradlew assembleDebug)
install the created apk to you device, from location: android/app/build/outputs/apk/app-debug.apk
let me know if that fixes your issue
EDIT:
You can simply put it to your package.json as a script to automate it, I believe it will be fixed in upcoming releases of react-native and will be executed prior assembling the final APK, hence this won't be needed (I hope as well)
put :
"scripts": {
"build": "(cd android/ && ./gradlew assembleDebug)",
"start": "node node_modules/react-native/local-cli/cli.js start",
"bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --sourcemap-output android/app/src/main/assets/index.android.map --assets-dest android/app/src/main/res/"
},
or as mentioned the curl equivalent, but for most cases the above is more robust
There are a lot of great answers here, but this is the approach I took for an Appium test where acting on a single element can result in going to different application states based on the user's settings. While it doesn't follow the conventions of OP's example, I hope it helps someone.
public <T extends MobilePage> T tapSignInButton(Class<T> type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//signInButton.click();
return type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
}
If you don't want to throw the errors you can catch them like so:
public <T extends MobilePage> T tapSignInButton(Class<T> type) {
// signInButton.click();
T returnValue = null;
try {
returnValue = type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
If you have ArrayList then convert into Array[Object]
ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt =
conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();
First off, when you call getElementById
, you need to provide an id. o_O
The only item in your dom with an id is the table
element. If you can, you could add ids (make sure they are unique) to your tr
elements.
Alternatively, you can use getElementsByTagName('tr')
to get a list of tr
elements in your document, and then get the number of tds.
var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);
At this point, pieces
is an array and pieces.length
contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]
. If there are no commas or spaces it will simply output the string as it was given.
alert(pieces[pieces.length-1]); // alerts "today?"
I had a slightly different requirement, whereby I had to selectively transpose columns into rows.
The table had columns:
create table tbl (ID, PreviousX, PreviousY, CurrentX, CurrentY)
I needed columns for Previous
and Current
, and rows for X
and Y
. A Cartesian product generated on a static table worked nicely, eg:
select
ID,
max(case when metric='X' then PreviousX
case when metric='Y' then PreviousY end) as Previous,
max(case when metric='X' then CurrentX
case when metric='Y' then CurrentY end) as Current
from tbl inner join
/* Cartesian product - transpose by repeating row and
picking appropriate metric column for period */
( VALUES (1, 'X'), (2, 'Y')) AS x (sort, metric) ON 1=1
group by ID
order by ID, sort
It would help to have sample information about your output. Recursively using rbind
on bigger and bigger things is not recommended. My first guess at something that would help you:
z <- list(1:3,4:6,7:9)
do.call(rbind,z)
See a related question for more efficiency, if needed.
There are some references and pointers in the comments on this page at PHP.net:
Torsten says
"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."
Jetboy says
"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.
Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
I had this issue while adding some packages from nuget and forgot to do an update
So first do an update of all packages installed in the project
Update-Package
In the Global.asax.cs add the following
BundleTable.EnableOptimizations = true;
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
Client Side
Data needs to be grouped in an object array as payload - Indata
:
var Indata = {'product': $scope.product, 'product2': $scope.product2 };
Pass the payload through $http.post
as the second argument:
$http.post("http://localhost:53263/api/Products/", Indata).then(function (data, status, headers, config) {
alert("success");
},function (data, status, headers, config) {
alert("error");
});
Server Side
Create a Data Transfer Object(DTO) class as such:
public class ExampleRequest {
public string product {get; set;};
public string product2 {get; set;};
}
The class below accepts DTO with the same property names which the payload is carrying.
public void Post(ExampleRequest request)
{
var productRepository = new ProductRepository();
var newProduct = productRepository.Save(request.product);
}
In above class, request
contains 2 properties with values of product
and product2
Copy & paste this method & used It like:
[lblText setFrame:CGRectMake(lblText.frame.origin.x, lblText.frame.origin.y, width, [self getLabelHeight:lblText])];
- (CGFloat)getLabelHeight:(UILabel*)label
{
CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [label.text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:label.font}
context:context].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}
Use the onConfigurationChanged method of Activity. See the following code:
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.
Hope this will help you... :)
take a look at generic method to print all elements in an array
but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.
This worked for me: :)
ALTER TABLE your_table_name ADD COLUMN new_column_name int;
Just set in XAML:
<TextBox IsReadOnly="True" Style="{x:Null}" />
So that text will not be grayed-out.
Directly from ngStyle
docs:
Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.
<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>
So you could do this:
<div ng-style="{'background-color': data.backgroundCol}"></div>
Hope this helps!
There are two options for this problem.
1) git rebase
2) git merge
Only diff with above both in case of merge, will have extra commit in history
1) git checkout branch(b1,b2,b3)
2) git rebase origin/master (In case of conflicts resolve locally by doing git rebase --continue)
3) git push
Alternatively, git merge option is similar fashion
1) git checkout "your_branch"(b1,b2,b3)
2) git merge master
3) git push
I think you are editing something in the windows registry but that has no effect on the path.
Try this:
How to Add, Remove or Edit Environment variables in Windows 7
the variable of interest is the PATH
also you can type on the command line:
Set PATH=%PATH%;(your new path);
DateFormatter
has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
This solved my problem completely:
.gm-style-iw {
overflow: visible !important;
height: auto !important;
width: auto !important;
}
The accepted solution have following drawbacks:
If your keys do not require to type password, I suggest following solution. Add the following to your .bash_profile
very end (edit key list to your needs):
exec ssh-agent $BASH -s 10<&0 << EOF
ssh-add ~/.ssh/your_key1.rsa \
~/.ssh/your_key2.rsa &> /dev/null
exec $BASH <&10-
EOF
It have following advantages:
It have possible disadvantages:
ssh-add
command will influence only one session, which is in fact an issue only in very untypical circumstances;Note that several ssh-agent
processes is not a disadvantage, because they don't take more memory or CPU time.
To get the occurrences of the object from the list directly:
int noOfOccurs = Collections.frequency(animals, "bat");
To get the occurrence of the Object collection inside list, override the equals method in the Object class as:
@Override
public boolean equals(Object o){
Animals e;
if(!(o instanceof Animals)){
return false;
}else{
e=(Animals)o;
if(this.type==e.type()){
return true;
}
}
return false;
}
Animals(int type){
this.type = type;
}
Call the Collections.frequency as:
int noOfOccurs = Collections.frequency(animals, new Animals(1));
Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:
String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));
P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)
You should create a StreamReader
around the stream, then call ReadToEnd
.
You should consider calling WebClient.DownloadString
instead.
You could use a do ... while
loop instead of a while
loop, so that rs.next()
is called after the loop is executed, like this:
if (!rs.next()) { //if rs.next() returns false
//then there are no rows.
System.out.println("No records found");
}
else {
do {
// Get data from the current row and use it
} while (rs.next());
}
Or count the rows yourself as you're getting them:
int count = 0;
while (rs.next()) {
++count;
// Get data from the current row and use it
}
if (count == 0) {
System.out.println("No records found");
}
.val()
is for input elements, use .html()
instead
Type "ctor" + TAB + TAB (hit the Tab key twice). This will create the default constructor for the class you are in:
public MyClass()
{
}
It seems that in some cases you will have to press TAB twice.
Here is another iteration solution for modern browsers:
Object.keys(obj)
.filter((k, i) => i >= 100 && i < 300)
.forEach(k => console.log(obj[k]));
Or without the filter function:
Object.keys(obj).forEach((k, i) => {
if (i >= 100 && i < 300) {
console.log(obj[k]);
}
});
However you must consider that properties in JavaScript object are not sorted, i.e. have no order.
Can't hurt to post another view since there's still not an official way to do this. Wrote a lightweight jQuery plugin with which you can define a background radial gradient and a transition speed. This basic usage will then let it fade in, optimised with requestAnimationFrame (very smooth) :
$('#element').gradientFade({
duration: 2000,
from: '(20,20,20,1)',
to: '(120,120,120,0)'
});
http://codepen.io/Shikkediel/pen/xbRaZz?editors=001
Keeps original background and all properties intact. Also has highlight tracking as a setting :
Create a ThreadSafeInvoke.snippet file, and then you can just select the update statements, right click and select 'Surround With...' or Ctrl-K+S:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>ThreadsafeInvoke</Title>
<Shortcut></Shortcut>
<Description>Wraps code in an anonymous method passed to Invoke for Thread safety.</Description>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[
Invoke( (MethodInvoker) delegate
{
$selected$
});
]]>
</Code>
</Snippet>
</CodeSnippet>
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
In the below, @i will return 2727
DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'
SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.
Create a reverse dictionary using the calendar
module (which, like any module, you will need to import):
{month: index for index, month in enumerate(calendar.month_abbr) if month}
In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do
dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)
Tried pushy's answer above and it worked for the most part. However, in certain circumstances, I would see this exception:
java.lang.String cannot be cast to java.lang.ProcessEnvironment$Variable
This turns out to happen when the method was called more than once, owing to the implementation of certain inner classes of ProcessEnvironment.
If the setEnv(..)
method is called more than once, when the keys are retrieved from the theEnvironment
map, they are now strings (having been put in as strings by the first invocation of setEnv(...)
) and cannot be cast to the map's generic type, Variable,
which is a private inner class of ProcessEnvironment.
A fixed version (in Scala), is below. Hopefully it isn't too difficult to carry over into Java.
def setEnv(newenv: java.util.Map[String, String]): Unit = {
try {
val processEnvironmentClass = JavaClass.forName("java.lang.ProcessEnvironment")
val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
theEnvironmentField.setAccessible(true)
val variableClass = JavaClass.forName("java.lang.ProcessEnvironment$Variable")
val convertToVariable = variableClass.getMethod("valueOf", classOf[java.lang.String])
convertToVariable.setAccessible(true)
val valueClass = JavaClass.forName("java.lang.ProcessEnvironment$Value")
val convertToValue = valueClass.getMethod("valueOf", classOf[java.lang.String])
convertToValue.setAccessible(true)
val sampleVariable = convertToVariable.invoke(null, "")
val sampleValue = convertToValue.invoke(null, "")
val env = theEnvironmentField.get(null).asInstanceOf[java.util.Map[sampleVariable.type, sampleValue.type]]
newenv.foreach { case (k, v) => {
val variable = convertToVariable.invoke(null, k).asInstanceOf[sampleVariable.type]
val value = convertToValue.invoke(null, v).asInstanceOf[sampleValue.type]
env.put(variable, value)
}
}
val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
theCaseInsensitiveEnvironmentField.setAccessible(true)
val cienv = theCaseInsensitiveEnvironmentField.get(null).asInstanceOf[java.util.Map[String, String]]
cienv.putAll(newenv);
}
catch {
case e : NoSuchFieldException => {
try {
val classes = classOf[java.util.Collections].getDeclaredClasses
val env = System.getenv()
classes foreach (cl => {
if("java.util.Collections$UnmodifiableMap" == cl.getName) {
val field = cl.getDeclaredField("m")
field.setAccessible(true)
val map = field.get(env).asInstanceOf[java.util.Map[String, String]]
// map.clear() // Not sure why this was in the code. It means we need to set all required environment variables.
map.putAll(newenv)
}
})
} catch {
case e2: Exception => e2.printStackTrace()
}
}
case e1: Exception => e1.printStackTrace()
}
}
Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.
Please, both ranges should have the same number of cells.
Sub Copy_Filtered_Cells()
Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range
'Selection.SpecialCells(xlCellTypeVisible).Select
'Set from = Selection.SpecialCells(xlCellTypeVisible)
Set temp = Application.InputBox("Copy Range :", Type:=8)
Set from = temp.SpecialCells(xlCellTypeVisible)
Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)
For Each cell In from
cell.Copy
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub
Enjoy!
Set and Map are non-linear data structure. List is linear data structure.
The tree data structure SortedSet
and SortedMap
interfaces implements TreeSet
and TreeMap
respectively using used Red-Black tree implementation algorithm. So it ensure that there are no duplicated items (or keys in case of Map
).
List
is already maintains an ordered collection and index-based data structure, trees are no index-based data structures.Tree
by definition cannot contain duplicates.List
we can have duplicates, so there is no TreeList
(i.e. no SortedList
).java.util.Collections.sort()
. It sorts the specified list into ascending order, according to the natural ordering of its elements.You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.
Subclass of RelativeLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with "Percent" suffix.
<android.support.percent.PercentRelativeLayout
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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>
The Percent package provides APIs to support adding and managing percentage based dimensions in your app.
To use, you need to add this library to your Gradle dependency list:
dependencies {
compile 'com.android.support:percent:22.2.0'//23.1.1
}
Either of the two should do the trick -
char *readFile(char *fileName)
{
FILE *file;
char *code = malloc(1000 * sizeof(char));
char *p = code;
file = fopen(fileName, "r");
do
{
*p++ = (char)fgetc(file);
} while(*p != EOF);
*p = '\0';
return code;
}
char *readFile(char *fileName)
{
FILE *file;
int i = 0;
char *code = malloc(1000 * sizeof(char));
file = fopen(fileName, "r");
do
{
code[i++] = (char)fgetc(file);
} while(code[i-1] != EOF);
code[i] = '\0'
return code;
}
Like the other posters have pointed out, you need to ensure that the file size does not exceed 1000 characters. Also, remember to free the memory when you're done using it.
A sidenote to consider, you can store arrays in Postgres.
I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915
) and make sure you add other jar
files present in lib and ooxml-lib
folders.
Hope this helps!!!:)
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value
, PHP looks for file named script.php?parameter=value
, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=...
or $GLOBALS[]=...
or other way you like.
This jQuery-based answer posted by @user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in @B_N 's comment: it failed detecting CapsLock while you press Shift:
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
|| ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
alert('caps is on');
}
});
Like this, it will work even while pressing Shift.
If you just want to make the error disappear, and you don't need the extension, then by all means comment the line out in php.ini
. But if you actually want to fix the problem here is some additional info.
There are various causes for this based on the exact module, but there are also some general guidelines.
phpinfo()
and look for extension_dir
under the Core
section. This is where your modules should be located.For instance,
/usr/lib/php/modules
for Unix/Linux.
Installation on *nix (PEAR)
Installation of extensions on Windows
I had similar problem. I r?n npm cache clear
, closed android SDK manager(which was open before) and re-ran npm install -g cordova
and that was enough to solve the problem.
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation: https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps
You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.
Copied from MySQL documentation
As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
* How often do you commit? As often as one would press ctrl + s?
As often as possible. Code doesn't exist unless it is under source control :)
Frequent commits (thereafter smaller change sets) allows you to integrate your changes easily and increase chances to not break something.
Other people noted that you should commit when you have a functional piece of code, however I find it useful to commit slightly more often. Few times I noticed that I use source control as a quick undo/redo mechanism.
When I work on my own branch I prefer to commit as much as possible (literally as often as I press ctrl+s).
* What is a Branch and what is a Tag and how do you control them?
Read SVN book - it is a place you should start with when learning SVN:
* What goes into the SVN?
Documentation, small binaries required for build and other stuff that have some value go to source control.
Here is example of using separated parallel
and for
here. In short it can be used for dynamic allocation of OpenMP thread-private arrays before executing for
cycle in several threads.
It is impossible to do the same initializing in parallel for
case.
UPD: In the question example there is no difference between single pragma and two pragmas. But in practice you can make more thread aware behavior with separated parallel and for directives. Some code for example:
#pragma omp parallel
{
double *data = (double*)malloc(...); // this data is thread private
#pragma omp for
for(1...100) // first parallelized cycle
{
}
#pragma omp single
{} // make some single thread processing
#pragma omp for // second parallelized cycle
for(1...100)
{
}
#pragma omp single
{} // make some single thread processing again
free(data); // free thread private data
}
Another great solution for this is Srobbin's Backstretch which can be applied to the body or any element on the page - http://srobbin.com/jquery-plugins/backstretch/
Add to this class in the .css file:
.row {
margin-left: -20px;
*zoom: 1;
margin-top: 50px;
}
or make a new class and add it to the element
.rowSpecificFormName td {
margin-top: 50px;
}
That would be the ALL_DIRECTORIES view:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_1075.htm#i1576965
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Here's an approach using generators:
function* square(n) {
for (var i = 0; i < n; i++ ) yield i*i;
}
Then you can write
console.log(...square(7));
Another idea is:
[...Array(5)].map((_, i) => i*i)
Array(5)
creates an unfilled five-element array. That's how Array
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)
or, we could take advantage of the second argument to Array#from
to skip the map
and write
Array.from(Array(5), (_, i) => i*i)
A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)
In case you are using extending the dialog the use:
requestWindowFeature(Window.FEATURE_NO_TITLE);
The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.
http://linuxcommand.org/lc3_man_pages/readh.html
-e use Readline to obtain the line in an interactive shell
Change your read to read -e and annoying line input hang goes away.
1 To 1 Relationships in SQL are made by merging the field of both table in one !
I know you can split a Table in two entity with a 1 to 1 relation. Most of time you use this because you want to use lazy loading on "heavy field of binary data in a table".
Exemple: You have a table containing pictures with a name column (string), maybe some metadata column, a thumbnail column and the picture itself varbinary(max). In your application, you will certainly display first only the name and the thumbnail in a collection control and then load the "full picture data" only if needed.
If it is what your are looking for. It is something called "table splitting" or "horizontal splitting".
https://visualstudiomagazine.com/articles/2014/09/01/splitting-tables.aspx
These all seem like very complicated answers for a very simple function:
public bool IsWindows7
{
get
{
return (Environment.OSVersion.Version.Major == 6 &
Environment.OSVersion.Version.Minor == 1);
}
}
(For future references)
I think it's because there's differences in Application Context and Activity Context, as explained here: http://www.doubleencore.com/2013/06/context/
Which means that we can't show dialog using Application Context. That's it.