try this:
$("#mydate").datepicker("setDate",'1d');
Your second for loop should have j++ instead of i++
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
Use the System.Environment class.
The methods
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
and
System.Environment.SetEnvironmentVariable(variable, value [, Target])
will do the job for you.
The optional parameter Target
is an enum of type EnvironmentVariableTarget
and it can be one of: Machine
, Process
, or User
. If you omit it, the default target is the current process.
Specific font
Setting a specific font in Swift is done like this:
let myFont = UIFont(name: "Helvetica", size: 17)
If you don't know the name, you can get a list of the available font names like this:
print(UIFont.familyNames())
Or an even more detailed list like this:
for familyName in UIFont.familyNames() {
print(UIFont.fontNamesForFamilyName(familyName))
}
But the system font changes from version to version of iOS. So it would be better to get the system font dynamically.
System font
let myFont = UIFont.systemFontOfSize(17)
But we have the size hard-coded in. What if the user's eyes are bad and they want to make the font larger? Of course, you could make a setting in your app for the user to change the font size, but this would be annoying if the user had to do this separately for every single app on their phone. It would be easier to just make one change in the general settings...
Dynamic font
let myFont = UIFont.preferredFont(forTextStyle: .body)
Ah, now we have the system font at the user's chosen size for the Text Style we are working with. This is the recommended way of setting the font. See Supporting Dynamic Type for more info on this.
you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.
Account account = new Account(1122, 20000, 4.5);
double sB = Account.withdraw(account.getBalance(), 2500);
double eB = Account.deposit(sB, 3000);
System.out.println("Balance is " + eB);
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
account.setDateCreated(new Date());
System.out.println("The account was created " + account.getDateCreated());
If you don't want bars you can plot it like this:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()
plt.plot(X,Y)
plt.show()
I believe this is the easiest way to do it:
$lines = explode('???',wordwrap($string, $length, '???'));
$newstring = $lines[0] . ' • • •';
I'm using the special characters to split the text and cut it.
You're doing only one mistake.
use replaceAll()
function over there.
e.g.
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );
If you check out the help of the unittest module it tells you about several combinations that allow you to run test case classes from a module and test methods from a test case class.
python3 -m unittest -h
[...]
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
```lang-none
It does not require you to define a `unittest.main()` as the default behaviour of your module.
How about using spread operator as a parameter? The same block can be called with Multiple parameters. All the parameters are added into an array and inside the method you can loop in based on the length.
function mName(...opt){
console.log(opt);
}
mName(1,2,3,4); //[1,2,3,4]
mName(1,2,3); //[1,2,3]
I guess now we can use plain iloc
with range
for this.
chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
df_subset = df.iloc[start:start + chunk_size]
process_data(df_subset)
....
I disagree with that this:
String s = myObj == null ? "" : myObj.ToString();
is a hack in any way. I think it's a good example of clear code. It's absolutely obvious what you want to achieve and that you're expecting null.
UPDATE:
I see now that you were not saying that this was a hack. But it's implied in the question that you think this way is not the way to go. In my mind it's definitely the clearest solution.
Useful topic thanks.
If you want like me remove leadings zero you can use that :
DECLARE @MyFloat [float];
SET @MyFloat = 1000109360.050;
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(STR(@MyFloat, 38, 16), '0', ' '))), ' ', '0'),'.',' ')),' ',',')
If you want to support Internet Explorer 7+ (no quirks, compatibility and other pain), last Chrome, last Safari, last Firefox and no iframes - this will be enough:
is_loaded = false
callbacks = []
loaded = ->
is_loaded = true
for i in [0...callbacks.length]
callbacks[i].call document
callbacks = []
content_loaded = ->
document.removeEventListener "DOMContentLoaded", content_loaded, true
loaded()
state_changed = ->
if document.readyState is "complete"
document.detachEvent "onreadystatechange", state_changed
loaded()
if !!document.addEventListener
document.addEventListener "DOMContentLoaded", content_loaded, true
else
document.attachEvent "onreadystatechange", state_changed
dom_ready = (callback) ->
if is_loaded
callback.call document
else
callbacks.push callback
The expression 'AND' and 'OR' and 'NOT'
always evaluates to 'NOT'
, so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
You can use the wmic command:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
one quick addendum regarding: usually you put those forward references into a header file belonging to the .c(pp) file where the function/variable etc. is implemented. in your example it would look like this: add.h:
extern int add(int a, int b);
the keyword extern states that the function is actually declared in an external file (could also be a library etc.). your main.c would look like this:
#include #include "add.h" int main() { . . .
A self contained solution in iOS 10, Swift 3 :
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "tel://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
}
}
}
You should be able to use callNumber("7178881234")
to make a call.
I think that still there isnt any answer here with easy and readable working example. Use MutationObserver interface
to detect DOM changes, like this:
var observer = new MutationObserver(function(mutations) {_x000D_
if ($("p").length) {_x000D_
console.log("Exist, lets do something");_x000D_
observer.disconnect(); _x000D_
//We can disconnect observer once the element exist if we dont want observe more changes in the DOM_x000D_
}_x000D_
});_x000D_
_x000D_
// Start observing_x000D_
observer.observe(document.body, { //document.body is node target to observe_x000D_
childList: true, //This is a must have for the observer with subtree_x000D_
subtree: true //Set to true if changes must also be observed in descendants._x000D_
});_x000D_
_x000D_
$(document).ready(function() {_x000D_
$("button").on("click", function() {_x000D_
$("p").remove();_x000D_
setTimeout(function() {_x000D_
$("#newContent").append("<p>New element</p>");_x000D_
}, 2000);_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button>New content</button>_x000D_
<div id="newContent"></div>
_x000D_
Note: Spanish Mozilla docs about
MutationObserver
are more detailed if you want more information.
Appending single space to output file with stream variable.
// declare output file stream varaible and open file
ofstream fout;
fout.open("flux_capacitor.txt");
fout << var << " ";
Maybe this answer is so late, but it's useful.
to do it,we have 3 steps:
1- Create a modal structure in HTML.
2- Create a button to call a function in java script, to open modal and set display:none
in CSS .
3- Call this button by function in code behind .
you can see these steps in below snippet :
HTML modal:
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">
Registration done Successfully</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblMessage" runat="server" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close</button>
<button type="button" class="btn btn-primary">
Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Hidden Button:
<button type="button" style="display: none;" id="btnShowPopup" class="btn btn-primary btn-lg"
data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
Script Code:
<script type="text/javascript">
function ShowPopup() {
$("#btnShowPopup").click();
}
</script>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
this.lblMessage.Text = "Your Registration is done successfully. Our team will contact you shotly";
}
this solution is one of any solutions that I used it .
Updated for Angular 5
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector : '[href]'
})
export class HrefDirective {
@Input() public href: string | undefined;
@HostListener('click', ['$event']) public onClick(event: Event): void {
if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
event.preventDefault();
}
}
}
This is the modified version of @d60402's answer: https://stackoverflow.com/a/15573121/4747587
Do everything mentioned there. But instead of having a Base Activity
and making that as a parent for every activity and the overriding the onResume()
and onPause
, do the below:
In your application class, add the line:
registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback);
This callback
has all the activity lifecycle methods and you can now override onActivityResumed()
and onActivityPaused()
.
Take a look at this Gist: https://gist.github.com/thsaravana/1fa576b6af9fc8fff20acfb2ac79fa1b
In the error message shown:
Error response from daemon: Cannot start container foo_1: \ exec: "grunt serve": executable file not found in $PATH
It is complaining that it cannot find the executable grunt serve
, not that it could not find the executable grunt
with the argument serve
. The most likely explanation for that specific error is running the command with the json syntax:
[ "grunt serve" ]
in something like your compose file. That's invalid since the json syntax requires you to split up each parameter that would normally be split by the shell on each space for you. E.g.:
[ "grunt", "serve" ]
The other possible way you can get both of those into a single parameter is if you were to quote them into a single arg in your docker run
command, e.g.
docker run your_image_name "grunt serve"
and in that case, you need to remove the quotes so it gets passed as separate args to the run command:
docker run your_image_name grunt serve
For others seeing this, the executable file not found
means that Linux does not see the binary you are trying to run inside your container with the default $PATH
value. That could mean lots of possible causes, here are a few:
Did you remember to include the binary inside your image? If you run a multi-stage image, make sure that binary install is run in the final stage. Run your image with an interactive shell and verify it exists:
docker run -it --rm your_image_name /bin/sh
Your path when shelling into the container may be modified for the interactive shell, particularly if you use bash, so you may need to specify the full path to the binary inside the container, or you may need to update the path in your Dockerfile with:
ENV PATH=$PATH:/custom/dir/bin
The binary may not have execute bits set on it, so you may need to make it executable. Do that with chmod:
RUN chmod 755 /custom/dir/bin/executable
If you run the image with a volume, that volume can overlay the directory where the executable exists in your image. Volumes do not merge with the image, they get mounted in the filesystem tree same as any other Linux filesystem mount. That means files from the parent filesystem at the mount point are no longer visible. (Note that named volumes are initialized by docker from the image content, but this only happens when the named volume is empty.) So the fix is to not mount volumes on top of paths where you have executables you want to run from the image.
I have found following way to fix this issue... I hope this can help you.
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
def is_prime(x):
n = 2
if x < n:
return False
else:
while n < x:
print n
if x % n == 0:
return False
break
n = n + 1
else:
return True
I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.
I managed to get it to work by adding both the height
and min-height
properties to the CSS class.
The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:
.flex-container {
display: flex;
flex-direction: column;
min-height: 100px;
height: 100px;
}
Hope this helps!
You may use Fernet as follows:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
encrypt_value = f.encrypt(b"YourString")
f.decrypt(encrypt_value)
It is an approach to incrementally add the cron job:
ssh USER_NAME@$PRODUCT_IP nohup "echo '*/2 * * * * ping -c2 PRODUCT_NAME.com >> /var/www/html/test.html' | crontab -u USER_NAME -"
The easiest way I've seen is to use Google Fonts.
Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.
Then add this to your custom.css:
h1, h2, h3, h4, h5, h6 {
font-family: 'Your Font' !important;
}
p, div {
font-family: 'Your Font' !important;
}
or
body {
font-family: 'Your Font' !important;
}
If you build packages from scratch:
Specifically, if you build bash
from source, install docs, including man pages, will fail (silently) without makeinfo
available.
There are two ways to exit a method early (without quitting the program):
return
keyword.Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
}
return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
Environment.Newline
instead of "\r\n"
.The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
If this problem still happens, it might be because of a JDK of version equal or greater than 11.
The tools.jar
archive has been removed from the lib folder in those JDK's (see this answer to a similar question).
In that case, try to use other versions of the libraries, that do not rely on the com.sun:tools
library.
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
Helpful trick I thought I'd share on this old thread.
You can see how much memory is being used and adjust things accordingly using the Show memory indicator
setting.
It shows up in the lower right of the window.
You can use a character class:
/[^\s\\]/
matches anything that is not a whitespace character nor a \
. Here's another example:
[abc]
means "match a
, b
or c
"; [^abc]
means "match any character except a
, b
or c
".
Use Bash and the date command to convert from an ISO-like format to the one you want. I wanted an org-mode date format (and list item), so I did this:
echo + [$(date -d "$(git log --pretty=format:%ai -1)" +"%Y-%m-%d %a %H:%M")] \
$(git log --pretty=format:"%h %s" --abbrev=12 -1)
And the result is for example:
+ [2015-09-13 Sun 22:44] 2b0ad02e6cec Merge pull request #72 from 3b/bug-1474631
1) It is good to have your property file in classpath but you can place it anywhere in project.
Below is how you load property file from classpath and read all properties.
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "path to property file";
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) Property files have the extension as .properties
There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.
Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.
Old question but I upgrade the answers supporting Android prior and post 4.2 and considering all recent changes according to Android developers blog
Plus I leave a working example on my github repo.
import java.nio.charset.Charset;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
*
* @author: Ricardo Champa
*
*/
public class MyCipher {
private final static String ALGORITHM = "AES";
private String mySecret;
public MyCipher(String mySecret){
this.mySecret = mySecret;
}
public MyCipherData encryptUTF8(String data){
try{
byte[] bytes = data.toString().getBytes("utf-8");
byte[] bytesBase64 = Base64.encodeBase64(bytes);
return encrypt(bytesBase64);
}
catch(Exception e){
MyLogs.show(e.getMessage());
return null;
}
}
public String decryptUTF8(byte[] encryptedData, IvParameterSpec iv){
try {
byte[] decryptedData = decrypt(encryptedData, iv);
byte[] decodedBytes = Base64.decodeBase64(decryptedData);
String restored_data = new String(decodedBytes, Charset.forName("UTF8"));
return restored_data;
} catch (Exception e) {
MyLogs.show(e.getMessage());;
return null;
}
}
//AES
private MyCipherData encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//solved using PRNGFixes class
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] data = cipher.doFinal(clear);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
return new MyCipherData(data, iv);
}
private byte[] decrypt(byte[] raw, byte[] encrypted, IvParameterSpec iv) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
private byte[] getKey() throws Exception{
byte[] keyStart = this.mySecret.getBytes("utf-8");
KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
// if (android.os.Build.VERSION.SDK_INT >= 17) {
// sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
// } else {
// sr = SecureRandom.getInstance("SHA1PRNG");
// }
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
}
////////////////////////////////////////////////////////////
private MyCipherData encrypt(byte[] data) throws Exception{
return encrypt(getKey(),data);
}
private byte[] decrypt(byte[] encryptedData, IvParameterSpec iv) throws Exception{
return decrypt(getKey(),encryptedData, iv);
}
}
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
You could try catching the onload event. And stopping the propagation dependent on some flag.
var changeHash = false;
$('ul.questions li a').click(function(event) {
var $this = $(this)
$('.tab').hide(); //you can improve the speed of this selector.
$($this.attr('href')).fadeIn('slow');
StopEvent(event); //notice I've changed this
changeHash = true;
window.location.hash = $this.attr('href');
});
$(window).onload(function(event){
if (changeHash){
changeHash = false;
StopEvent(event);
}
}
function StopEvent(event){
event.preventDefault();
event.stopPropagation();
if ($.browser.msie) {
event.originalEvent.keyCode = 0;
event.originalEvent.cancelBubble = true;
event.originalEvent.returnValue = false;
}
}
Not tested, so can't say if it would work
select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0
[::-1] gives a slice of the string a. the full syntax is a[begin:end:step]
which gives a[begin], a[begin+step], ... a[end-1]. WHen step is negative, you start at end and move to begin.
Finally, begin defaults to the beginning of the sequence, end to the end, and step to -1.
//GET CONTACTLIST WITH ALL FIELD...
public ArrayList < ContactItem > getReadContacts() {
ArrayList < ContactItem > contactList = new ArrayList < > ();
ContentResolver cr = getContentResolver();
Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (mainCursor != null) {
while (mainCursor.moveToNext()) {
ContactItem contactItem = new ContactItem();
String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
//ADD NAME AND CONTACT PHOTO DATA...
contactItem.setDisplayName(displayName);
contactItem.setPhotoUrl(displayPhotoUri.toString());
if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//ADD PHONE DATA...
ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
PhoneContact phoneContact = new PhoneContact();
String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneContact.setPhone(phone);
arrayListPhone.add(phoneContact);
}
}
if (phoneCursor != null) {
phoneCursor.close();
}
contactItem.setArrayListPhone(arrayListPhone);
//ADD E-MAIL DATA...
ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (emailCursor != null) {
while (emailCursor.moveToNext()) {
EmailContact emailContact = new EmailContact();
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailContact.setEmail(email);
arrayListEmail.add(emailContact);
}
}
if (emailCursor != null) {
emailCursor.close();
}
contactItem.setArrayListEmail(arrayListEmail);
//ADD ADDRESS DATA...
ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (addrCursor != null) {
while (addrCursor.moveToNext()) {
PostalAddress postalAddress = new PostalAddress();
String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
postalAddress.setCity(city);
postalAddress.setState(state);
postalAddress.setCountry(country);
arrayListAddress.add(postalAddress);
}
}
if (addrCursor != null) {
addrCursor.close();
}
contactItem.setArrayListAddress(arrayListAddress);
}
contactList.add(contactItem);
}
}
if (mainCursor != null) {
mainCursor.close();
}
return contactList;
}
//MODEL...
public class ContactItem {
private String displayName;
private String photoUrl;
private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public ArrayList<PhoneContact> getArrayListPhone() {
return arrayListPhone;
}
public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
this.arrayListPhone = arrayListPhone;
}
public ArrayList<EmailContact> getArrayListEmail() {
return arrayListEmail;
}
public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
this.arrayListEmail = arrayListEmail;
}
public ArrayList<PostalAddress> getArrayListAddress() {
return arrayListAddress;
}
public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
this.arrayListAddress = arrayListAddress;
}
}
public class EmailContact
{
private String email = "";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public class PhoneContact
{
private String phone="";
public String getPhone()
{
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class PostalAddress
{
private String city="";
private String state="";
private String country="";
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Might help some else - I came here because I missed putting two // after http:. This is what I had:
http:/abc.my.domain.com:55555/update
>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']
You want to set the execution policy on your machine using Set-ExecutionPolicy:
Set-ExecutionPolicy Unrestricted
You may want to investigate the various execution policies to see which one is right for you. Take a look at the "help about_signing
" for more information.
Don't hardcode the character encoding of your environment inside your script; print Unicode text directly instead:
assert isinstance(text, unicode) # or str on Python 3
print(text)
If your output is redirected to a file (or a pipe); you could use PYTHONIOENCODING
envvar, to specify the character encoding:
$ PYTHONIOENCODING=utf-8 python your_script.py >output.utf8
Otherwise, python your_script.py
should work as is -- your locale settings are used to encode the text (on POSIX check: LC_ALL
, LC_CTYPE
, LANG
envvars -- set LANG
to a utf-8 locale if necessary).
A helper function to do the job:
function setDirtyForm(form) {
angular.forEach(form.$error, function(type) {
angular.forEach(type, function(field) {
field.$setDirty();
});
});
return form;
}
Assuming there are a few ignore directories, why not use "git status node/logs/" which will tell you what files are to be added? In the directory I have a text file that is not part of status output, e.g.:
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
(use "git add ..." to include in what will be committed)
node/logs/.gitignore
.gitignore is:
*
!.gitignore
In order to avoid changing anything in your code, simply update your MySQL server to at least 5.7.7
Reference this for more info : https://laravel-news.com/laravel-5-4-key-too-long-error
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':
std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()
Full example prog:
#include <algorithm>
#include <string>
#include <iostream>
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "Will print true if 'prefix' is a prefix of string" << std::endl;
return -1;
}
std::string prefix(argv[1]);
std::string toCheck(argv[2]);
if (prefix.length() > toCheck.length()) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "'prefix' is longer than 'string'" << std::endl;
return 2;
}
if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
return 0;
} else {
std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
return 1;
}
}
Edit:
As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:
std::equal(prefix.begin(), prefix.end(), toCheck.begin())
Full example prog:
#include <algorithm>
#include <string>
#include <iostream>
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "Will print true if 'prefix' is a prefix of string"
<< std::endl;
return -1;
}
std::string prefix(argv[1]);
std::string toCheck(argv[2]);
if (prefix.length() > toCheck.length()) {
std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
<< "'prefix' is longer than 'string'" << std::endl;
return 2;
}
if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
<< '"' << std::endl;
return 0;
} else {
std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
<< toCheck << '"' << std::endl;
return 1;
}
}
I just recently had this issue and I didn't even believe it was my mistype:
Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)
And actually it was! I just accidentally typed "." rather than ","...
This error might also occur when you have a large project with many modules. Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".
app.js
angular
.module('thisApp', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
index.html
<html>
<body ng-app='thisApp' ng-controller='ContactController>
...
<script type="text/javascript" src="assets/js/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
Short answer: One package per module/feature, possibly with sub-packages. Put closely related things together in the same package. Avoid circular dependencies between packages.
Long answer: I agree with most of this article
Try to check the limits of your SQL database. Maybe you'r exceeding the field limit for this row.
I have used Botan to perform this operation and others before. AraK has pointed out Crypto++. I guess both libraries are perfectly valid. Now it is up to you :-).
Put the list in an array, use JavaScript's .sort()
, which is by default alphabetical, then convert the array back to a list.
Instead of redis-cli
you can simply use nc
!
nc -v --ssl redis.mydomain.com 6380
Then submit the commands.
From the diff man page:
-q
Report only whether the files differ, not the details of the differences.
-r
When comparing directories, recursively compare any subdirectories found.
Example command:
diff -qr dir1 dir2
Example output (depends on locale):
$ ls dir1 dir2
dir1:
same-file different only-1
dir2:
same-file different only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2
In mac osx , you can use the following command:
system_profiler SPUSBDataType
Consider the following ComplexType AuthorType
used by author
element
<xsd:complexType name="AuthorType">
<!-- compositor goes here -->
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="phone" type="tns:Phone"/>
</xsd:sequence>
<xsd:attribute name="id" type="tns:AuthorId"/>
</xsd:complexType>
<xsd:element name="author" type="tns:AuthorType"/>
If elementFormDefault="unqualified"
then following XML Instance is valid
<x:author xmlns:x="http://example.org/publishing">
<name>Aaron Skonnard</name>
<phone>(801)390-4552</phone>
</x:author>
the authors's name attribute is allowed without specifying the namespace(unqualified). Any elements which are a part of <xsd:complexType>
are considered as local to complexType.
if elementFormDefault="qualified"
then the instance should have the local elements qualified
<x:author xmlns:x="http://example.org/publishing">
<x:name>Aaron Skonnard</name>
<x:phone>(801)390-4552</phone>
</x:author>
please refer this link for more details
for me replace doesn't work... try this code:
str = str.split(""").join('"');
When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here
If you look at the source code you can see that I am calling the Twitter API using .getJSON.
So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)
//JAVASCRIPT
$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
alert('Your name is '+res.fullname);
});
//SERVER SIDE
<?php
$fname = $_GET['firstname'];
if($fname=='Jeff')
{
//header("Content-Type: application/json");
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
}
?>
Note the ?callback=? and +res.fullname
You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
i also suppose you want to center the image, so the code would be :
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output
You use the modf
function:
double integral;
double fractional = modf(some_double, &integral);
You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.
You have at least three options. I have presented them in order of usage preference.
Method 1 - You can use the SC tool (Sc.exe) included in the Resource Kit. (included with Windows 7/8)
Open a Command Prompt and enter
sc delete <service-name>
Tool help snippet follows:
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
delete----------Deletes a service (from the registry).
Method 2 - use delserv
Download and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.
Method 3 - manually delete registry entries (Note that this backfires in Windows 7/8)
Windows services are registered under the following registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)
In my case issue occurred after following:
I selected proxy settings from Android Studio settings when I was working in a network behind a proxy. When I disconnected from that network and connected to home network which doesn't have a proxy, I removed the proxy settings from Android Studio, but gradle seemed to take the old proxy settings.
The problem was that gradle had also saved the proxy settings in following file when I set proxy settings in Android Studio, but it hasn't got removed when I removed proxy settings from Android Studio.
%HOME%\.gradle\gradle.properties
When I removed the proxy settings from this file, gradle sync worked again.
VB sample:
@Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})
Sample Css:
.someClass
{
color: Green !important;
}
In my case, I found that I need the !important attribute to over ride the site.css a:link css class
I think it would be best to follow the pattern for Override Object#Equals()
For a better description: Read Bill Wagner's Effective C# - Item 9 I think
public override Equals(object obOther)
{
if (null == obOther)
return false;
if (object.ReferenceEquals(this, obOther)
return true;
if (this.GetType() != obOther.GetType())
return false;
# private method to compare members.
return CompareMembers(this, obOther as ThisClass);
}
Update-Dec 2011:
You can either use (on the h4 elements, as they are block by default)
display: inline-block;
Or you can float the elements to the left/rght
float: left;
Just don't forget to clear the floats after
clear: left;
More visual example for the float left/right option as shared below by @VSB:
<h4> _x000D_
<div style="float:left;">Left Text</div>_x000D_
<div style="float:right;">Right Text</div>_x000D_
<div style="clear: left;"/>_x000D_
</h4>
_x000D_
Client
Do not set the content-type header.
// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');
fetch("api/SampleData",
{
body: formData,
method: "post"
});
Server
Use the FromForm
attribute to specify that binding source is form data.
[Route("api/[controller]")]
public class SampleDataController : Controller
{
[HttpPost]
public IActionResult Create([FromForm]UserDto dto)
{
return Ok();
}
}
public class UserDto
{
public string Name { get; set; }
public string Password { get; set; }
}
Is just casting the value returned by time()
#include <stdio.h>
#include <time.h>
int main(void) {
printf("Timestamp: %d\n",(int)time(NULL));
return 0;
}
what you want?
$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167
To get microseconds since the epoch, from C11 on, the portable way is to use
int timespec_get(struct timespec *ts, int base)
Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime
or gettimeofday
(marked obsolete in POSIX.1-2008, which recommends clock_gettime
).
The code for both functions is nearly identical:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
int main(void) {
struct timespec tms;
/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */
/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
int64_t micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;
/* round up if necessary */
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return 0;
}
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
Use variable capture to "pass in" parameters.
var x = rawData;
Task.Run(() =>
{
// Do something with 'x'
});
You also could use rawData
directly but you must be careful, if you change the value of rawData
outside of a task (for example a iterator in a for
loop) it will also change the value inside of the task.
I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"
startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
What you need:
1) A private and a public key.
They have this symbol in your keychain:
2) A certificate made from the signing request of those keys
3) A provisioning profile linked to that certificate
Let's say you change computers and want to set up Xcode with provisioning profiles again. How do you do it?
Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]
You can listen resize
event and fire where some dimension change
directive
(function() {
'use strict';
angular
.module('myApp.directives')
.directive('resize', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
function onResize(){
// uncomment for only fire when $window.innerWidth change
// if (scope.width !== $window.innerWidth)
{
scope.width = $window.innerWidth;
scope.$digest();
}
};
function cleanUp() {
angular.element($window).off('resize', onResize);
}
angular.element($window).on('resize', onResize);
scope.$on('$destroy', cleanUp);
}
}]);
})();
In html
<div class="row" resize> ,
<div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod">
<h4 ng-bind="::v.known_as"></h4>
</div>
</div>
Controller :
$scope.$watch('width', function(old, newv){
console.log(old, newv);
})
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow
and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
This works for me in 2015 :
li {_x000D_
-webkit-column-break-inside: avoid;_x000D_
/* Chrome, Safari, Opera */_x000D_
page-break-inside: avoid;_x000D_
/* Firefox */_x000D_
break-inside: avoid;_x000D_
/* IE 10+ */_x000D_
}_x000D_
.x {_x000D_
-moz-column-count: 3;_x000D_
column-count: 3;_x000D_
width: 30em;_x000D_
}
_x000D_
<div class='x'>_x000D_
<ul>_x000D_
<li>Number one</li>_x000D_
<li>Number two</li>_x000D_
<li>Number three</li>_x000D_
<li>Number four is a bit longer</li>_x000D_
<li>Number five</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
ContextLoaderListener
has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml
You can customize this by using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>
on web.xml
, or remove this listener if you don't need one.
If you are using Entity framework, then try removing property from DbContext which uses your complex model as Entity I had same problem when mapping multiple model into a viewmodel named Entity
public DbSet<Entity> Entities { get; set; }
Removing the entry from DbContext fixed my error.
There is a small handful of programs that do that... TowerJ is one that comes to mind (I'll let you Google for it) but it costs significant money.
The most useful reference for this topic I found is at: http://mindprod.com/jgloss/nativecompiler.html
it mentions a few other products, and alternatives to achieve the same purpose.
Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).
Run both in the repo you're trying to recover.
Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.
fsck_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git fsck --full --no-dangling 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null
and
unpack_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git unpack-objects -r < "$1" 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
for p in $1/objects/pack/pack-*.pack; do
echo "$p"
unpack_rm_corrupted "$p"
done
float RandomFloat(float min, float max)
{
float r = (float)rand() / (float)RAND_MAX;
return min + r * (max - min);
}
Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.
Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):
input {
width: 20px;
position: relative;
left: 200px;
vertical-align: middle;
}
label {
width: 200px;
position: relative;
left: -20px;
display: inline-block;
vertical-align: middle;
}
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.
You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).
You can do this by calling the constructor each time with is slightly better
var tupleList = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "cow" ),
new Tuple<int, string>( 5, "chickens" ),
new Tuple<int, string>( 1, "airplane" )
};
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.
In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.
None of the above had worked for me. This had been working for me prior to today. I then realized I had been working with creating a hosted connection on my laptop and had Shared an internet connection with my Wireless Network Connection.
To fix my issue:
Go to Control Panel > Network and Internet > Network Connections
Right click on any secondary Wireless Network Connection you may have (mine was named Wireless Network Connection 2) and click 'Properties'.
Go to the 'Sharing' tab at the top.
Uncheck the box that states 'Allow other network users to connect through this computer's Internet connection'.
Hit OK > then Apply.
Hope this helps!
Not really related to this answer, but I'd ditch git pull
, which just runs git fetch
followed by git merge
. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:
git fetch origin # update all our origin/* remote-tracking branches
git checkout demo # if needed -- your example assumes you're on it
git merge origin/demo # if needed -- see below
git checkout master
git merge origin/master
git merge -X theirs demo # but see below
git push origin master # again, see below
The most interesting part here is git merge -X theirs
. As root545 noted, the -X
options are passed on to the merge strategy, and both the default recursive
strategy and the alternative resolve
strategy take -X ours
or -X theirs
(one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.
A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours
) version and the other (also called remote or --theirs
) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.
These changes are what you see in git diff
output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).
If the changes happen on different lines—for instance, we change color
to colour
on line 17 and they change fred
to barney
on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.
The -X ours
and -X theirs
options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo
(theirs) into master
(ours) and want the changes from demo
, you would want -X theirs
.
Blindly applying -X
, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:
int i;
In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i
as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X
option is no help here since the changes are on different lines.
If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit
to the git merge
command. We'll leave the details for all of this to other postings.
1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X
arguments.
There are three merges in both of our command sequences. The first is to bring origin/demo
into the local demo
(yours uses git pull
which, if your Git is very old, will fail to update origin/demo
but will produce the same end result). The second is to bring origin/master
into master
.
It's not clear to me who is updating demo
and/or master
. If you write your own code on your own demo
branch, and others are writing code and pushing it to the demo
branch on origin
, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase
instead. On the other hand, if you never do any of your own commits on demo
, you don't even need a demo
branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo
: this will fast-forward your demo
to match the updated origin/demo
if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).
This same logic applies to master
, although you are doing the merge on master
, so you definitely do need a master
. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master
.
Let's say that you never do your own commits on demo
. In this case we can ditch the name demo
entirely:
git fetch origin # update origin/*
git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"
git merge -X theirs origin/demo || die "complex merge conflict"
git push origin master
If you are doing your own demo
branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only
depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only
may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).
There are padding built into various classes.
For example:
A asp.net web forms app:
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.
However with bootstrap
<div class="checkbox-inline">
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>
This created the space, if you don't want the text bold, that class=checkbox
Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC
you cannot add a background image to an html
newsletter which is to be viewed in outlook. It just wont work, as they ignore the property.
You can only have block colours (background-color
) behind text.
Outlook doesn't support the following CSS:
azimuth
background-attachment
background-image
background-position
background-repeat
border-spacing
bottom
caption-side
clear
clip
content
counter-increment
counter-reset
cue-before, cue-after, cue
cursor
display
elevation
empty-cells
float
font-size-adjust
font-stretch
left
line-break
list-style-image
list-style-position
marker-offset
max-height
max-width
min-height
min-width
orphans
outline
outline-color
outline-style
outline-width
overflow
overflow-x
overflow-y
pause-before, pause-after, pause
pitch
pitch-range
play-during
position
quotes
richness
right
speak
speak-header
speak-numeral
speak-punctuation
speech-rate
stress
table-layout
text-shadow
text-transform
top
unicode-bidi
visibility
voice-family
volume
widows
word-spacing
z-index
Source: http://msdn.microsoft.com/en-us/library/aa338201.aspx
UPDATE - July 2015
I thought it best to update this list as it gets the odd upvote every now and then - a great link to current email client support is available here: https://www.campaignmonitor.com/css/
The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:
from tkinter import *
import time
def update_clock():
timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
font='Times 25') # change the text of the time_label according to the current time
root.after(100, update_clock) # reschedule update_clock function to update time_label every 100 ms
root = Tk() # create the root window
timer_label = Label(root, justify='center') # create the label for timer
timer_label.pack() # show the timer_label using pack geometry manager
root.after(0, update_clock) # schedule update_clock function first call
root.mainloop() # start the root window mainloop
The correct version of your script is as follows;
FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done
However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.
ThomasH has already added a good answer, but I want to show what happens:
>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]
I guess Python parses the list comprehension from left to right. This means, the first for
loop that occurs will be executed first.
The second "problem" of this is that b
gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4]
.
You can be selective of what div or part of your page can have checkboxes checked and which don't. I came across the scenario where I have two forms in my page and one have prefilled values(for update) and other need to be filled fresh.
$('#newFormId input[type=checkbox]').attr('checked',false);
this will make only checkboxes in form with id newFormId as unchecked.
Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:
// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");
For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open
options for customization.
Update:
You would need something along:
$(document).ready(function() {
$(".product-item").click(function() {
var productLink = $(this).find("a");
productLink.attr("target", "_blank");
window.open(productLink.attr("href"));
return false;
});
});
Note the usage of .attr()
:
$element.attr("attribute_name") // Get value of attribute.
$element.attr("attribute_name", attribute_value) // Set value of attribute.
This is an altered version of @Martin Thoma's answer for GTK3. I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.
#!/usr/bin/python3
from gi.repository import Gtk, Gdk
import sys
from time import sleep
class Hello(Gtk.Window):
def __init__(self):
super(Hello, self).__init__()
clipboardText = sys.argv[1]
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(clipboardText, -1)
clipboard.store()
def main():
Hello()
if __name__ == "__main__":
main()
You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.
On a fresh ubuntu 16.04 installation, I found that I had to install the python-gobject
package for it to work without a module import error.
I too got the similar problem and I did like below..
Rt click the project, navigate to Run As --> click 6 Maven Clean and your build will be success..
Some of the solutions here assumes that there is reference to the root node, some assumes that tree is a BST.
Sharing my solution using hashmap, without reference to root
node and tree can be BST or non-BST:
var leftParent : Node? = left
var rightParent : Node? = right
var map = [data : Node?]()
while leftParent != nil {
map[(leftParent?.data)!] = leftParent
leftParent = leftParent?.parent
}
while rightParent != nil {
if let common = map[(rightParent?.data)!] {
return common
}
rightParent = rightParent?.parent
}
If you're using node:
values.js
:export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js
):
import { someValues } from './values'
console.log(someValues);
For those using jQuery there's a convenient method: http://api.jquery.com/change/
My Solution
public class CalendarUtils {
public static String dateFormat = "dd-MM-yyyy hh:mm";
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
public static String ConvertMilliSecondsToFormattedDate(String milliSeconds){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(milliSeconds));
return simpleDateFormat.format(calendar.getTime());
}
}
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
window load will wait for all resources to be loaded.
document ready waits for the document to be initialized.
unload well, waits till the document is being unloaded.
the order is: document ready, window load, ... ... ... ... window unload.
always use document ready unless you need to wait for your images to load.
shorthand for document ready:
$(function(){
// yay!
});
(function( $ ) {
$.fn.keepRatio = function(which) {
var $this = $(this);
var w = $this.width();
var h = $this.height();
var ratio = w/h;
$(window).resize(function() {
switch(which) {
case 'width':
var nh = $this.width() / ratio;
$this.css('height', nh + 'px');
break;
case 'height':
var nw = $this.height() * ratio;
$this.css('width', nw + 'px');
break;
}
});
}
})( jQuery );
$(document).ready(function(){
$('#foo').keepRatio('width');
});
Working example: http://jsfiddle.net/QtftX/1/
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
var welcomeMessage = 'Hello ' + (username ? username : 'guest');
You can use:
var welcomeMessage = 'Hello ' + (username || 'guest');
This is Javascripts equivallent of PHP's shorthand ternary operator ?:
Or even:
var welcomeMessage = 'Hello ' + (username || something || maybethis || 'guest');
It evaluates the variable, and if it's false or unset, it goes on to the next.
Here's my take at random plain password generation helper.
It ensures that password has numbers, upper and lower case letters as well as a minimum of 3 special characters.
Length of the password will be between 11 and 30.
function plainPassword(): string
{
$numbers = array_rand(range(0, 9), rand(3, 9));
$uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
$lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
$special = array_rand(array_flip(['@', '#', '$', '!', '%', '*', '?', '&']), rand(3, 5));
$password = array_merge(
$numbers,
$uppercase,
$lowercase,
$special
);
shuffle($password);
return implode($password);
}
Since you are setting the layout explicitly you might want to try and put it in the default /layout folder not in the /layout-land since that is if you want Android to automatically handle rotation for you.
There is a conflict between (Safari) and (Opera) and (Chrome) !!!
The above codes couldn't work properly
This is my code, and it works very well without any conflict:
function ExactBrowserName()
{
$ExactBrowserNameUA=$_SERVER['HTTP_USER_AGENT'];
if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
// OPERA
$ExactBrowserNameBR="Opera";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
// CHROME
$ExactBrowserNameBR="Chrome";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
// INTERNET EXPLORER
$ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
// FIREFOX
$ExactBrowserNameBR="Firefox";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
// SAFARI
$ExactBrowserNameBR="Safari";
} else {
// OUT OF DATA
$ExactBrowserNameBR="OUT OF DATA";
};
return $ExactBrowserNameBR;
}
Passphrases can be added to an existing key or changed without regenerating the key pair:
Note This will work if keys doesn't had a passphrase, otherwise you'll get this: Enter old passphrase:
then Bad passphrase
$ ssh-keygen -p
Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
Key has comment '/Users/tekkub/.ssh/id_rsa'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
If your key had passphrase
then, There's no way to recover the passphrase for a pair of SSH keys. In that case you have to create a new pair of SSH keys.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD
for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD
is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!or:
YYYY-MM-DDTHH:MM:SS
for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T
as delimiter between the date and time portion of your DATETIME
.This is valid for SQL Server 2000 and newer.
So in your concrete case - use these strings:
insert into table1 values('2012-02-21T18:10:00', '2012-01-01T00:00:00');
and you should be fine (note: you need to use the international 24-hour format rather than 12-hour AM/PM format for this).
Alternatively: if you're on SQL Server 2008 or newer, you could also use the DATETIME2
datatype (instead of plain DATETIME
) and your current INSERT
would just work without any problems! :-) DATETIME2
is a lot better and a lot less picky on conversions - and it's the recommend date/time data types for SQL Server 2008 or newer anyway.
SELECT
CAST('02-21-2012 6:10:00 PM' AS DATETIME2), -- works just fine
CAST('01-01-2012 12:00:00 AM' AS DATETIME2) -- works just fine
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD
format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
If you spawn threads in Application_Start
, they will still be executing in the application pool's AppDomain
.
If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET
will recycle the entire AppDomain
.
When that happens, any threads that you started from that AppDomain
, including those from Application_Start
, will be aborted.
Lots more on application pools and recycling in this question: What exactly is Appdomain recycling
If you are trying to run a long-running process within IIS/ASP.NET
, the short answer is usually "Don't". That's what Windows Services are for.
To start launch the sms activity all you need is this:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
You can add extras to populate your own message and such like this
sendIntent.putExtra("sms_body", x);
then just startActivity with the intent.
startActivity(sendIntent);
Have you tried using :
git dif | grep -B <number of before lines to show> <regex>
In my case, i try to search where do i put a debug statement in the many files, i need to see which file already got this debug statement like this :
git diff | grep -B 5 dd\(
using Android ViewModel & SavedStateHandle to persist the serializable data
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
binding.setViewModel(new ViewModelProvider(this).get(ViewModel.class));
binding.setLifecycleOwner(this);
setContentView(binding.getRoot());
}
public static class ViewModel extends AndroidViewModel {
//This field SURVIVE the background process reclaim/killing & the configuration change
public final SavedStateHandle savedStateHandle;
//This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change
public final MutableLiveData<String> inputText2 = new MutableLiveData<>();
public ViewModel(@NonNull Application application, SavedStateHandle savedStateHandle) {
super(application);
this.savedStateHandle = savedStateHandle;
}
}
}
in layout file
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.xxx.viewmodelsavedstatetest.MainActivity.ViewModel" />
</data>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="This field SURVIVE the background process reclaim/killing & the configuration change"
android:text='@={(String)viewModel.savedStateHandle.getLiveData("activity_main/inputText", "")}' />
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData("activity_main/progress", 50)}' />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="This field SURVIVE the background process reclaim/killing & the configuration change"
android:text='@={(String)viewModel.savedStateHandle.getLiveData("activity_main/inputText", "")}' />
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress='@={(Integer)viewModel.savedStateHandle.getLiveData("activity_main/progress", 50)}' />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="This field NOT SURVIVE the background process reclaim/killing but SURVIVE the configuration change"
android:text='@={viewModel.inputText2}' />
</LinearLayout>
</layout>
Test:
1. start the test activity
2. press home key to go home
3. adb shell kill <the test activity process>
4. open recent app list and restart the test activity
For me the problem was a configuration file that was missing an Element.
Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.
library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3)
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')
Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.
At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
window.pageXOffset
first and uses that if it exists.document.documentElement.scrollLeft
.document.documentElement.clientLeft
if it exists.The subtraction of document.documentElement.clientLeft
/ Top
only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
I post you a piece of code which show a way how to solve the problem. As exemple I'm reading a file. You could use this method for another operation, but you need to implements the kill() method so that the main operation will be interrupted.
hope it helps
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Main class
*
* @author el
*
*/
public class Main {
/**
* Thread which perform the task which should be timed out.
*
* @author el
*
*/
public static class MainThread extends Thread {
/**
* For example reading a file. File to read.
*/
final private File fileToRead;
/**
* InputStream from the file.
*/
final private InputStream myInputStream;
/**
* Thread for timeout.
*/
final private TimeOutThread timeOutThread;
/**
* true if the thread has not ended.
*/
boolean isRunning = true;
/**
* true if all tasks where done.
*/
boolean everythingDone = false;
/**
* if every thing could not be done, an {@link Exception} may have
* Happens.
*/
Throwable endedWithException = null;
/**
* Constructor.
*
* @param file
* @throws FileNotFoundException
*/
MainThread(File file) throws FileNotFoundException {
setDaemon(false);
fileToRead = file;
// open the file stream.
myInputStream = new FileInputStream(fileToRead);
// Instantiate the timeout thread.
timeOutThread = new TimeOutThread(10000, this);
}
/**
* Used by the {@link TimeOutThread}.
*/
public void kill() {
if (isRunning) {
isRunning = false;
if (myInputStream != null) {
try {
// close the stream, it may be the problem.
myInputStream.close();
} catch (IOException e) {
// Not interesting
System.out.println(e.toString());
}
}
synchronized (this) {
notify();
}
}
}
/**
* The task which should be timed out.
*/
@Override
public void run() {
timeOutThread.start();
int bytes = 0;
try {
// do something
while (myInputStream.read() >= 0) {
// may block the thread.
myInputStream.read();
bytes++;
// simulate a slow stream.
synchronized (this) {
wait(10);
}
}
everythingDone = true;
} catch (IOException e) {
endedWithException = e;
} catch (InterruptedException e) {
endedWithException = e;
} finally {
timeOutThread.kill();
System.out.println("-->read " + bytes + " bytes.");
isRunning = false;
synchronized (this) {
notifyAll();
}
}
}
}
/**
* Timeout Thread. Kill the main task if necessary.
*
* @author el
*
*/
public static class TimeOutThread extends Thread {
final long timeout;
final MainThread controlledObj;
TimeOutThread(long timeout, MainThread controlledObj) {
setDaemon(true);
this.timeout = timeout;
this.controlledObj = controlledObj;
}
boolean isRunning = true;
/**
* If we done need the {@link TimeOutThread} thread, we may kill it.
*/
public void kill() {
isRunning = false;
synchronized (this) {
notify();
}
}
/**
*
*/
@Override
public void run() {
long deltaT = 0l;
try {
long start = System.currentTimeMillis();
while (isRunning && deltaT < timeout) {
synchronized (this) {
wait(Math.max(100, timeout - deltaT));
}
deltaT = System.currentTimeMillis() - start;
}
} catch (InterruptedException e) {
// If the thread is interrupted,
// you may not want to kill the main thread,
// but probably yes.
} finally {
isRunning = false;
}
controlledObj.kill();
}
}
/**
* Start the main task and wait for the end.
*
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
long start = System.currentTimeMillis();
MainThread main = new MainThread(new File(args[0]));
main.start();
try {
while (main.isRunning) {
synchronized (main) {
main.wait(1000);
}
}
long stop = System.currentTimeMillis();
if (main.everythingDone)
System.out.println("all done in " + (stop - start) + " ms.");
else {
System.out.println("could not do everything in "
+ (stop - start) + " ms.");
if (main.endedWithException != null)
main.endedWithException.printStackTrace();
}
} catch (InterruptedException e) {
System.out.println("You've killed me!");
}
}
}
Regards
Many ways to do this, you can use DATENAME and check for the actual strings 'Saturday' or 'Sunday'
SELECT DATENAME(DW, GETDATE())
Or use the day of the week and check for 1 (Sunday) or 7 (Saturday)
SELECT DATEPART(DW, GETDATE())
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
This jQuery worked for me in IE11, Chrome 53, and Firefox 49:
cloned = $("#fileInput").clone(true);
cloned.val("");
$("#fileInput").replaceWith(cloned);
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
Use microsoft's tool for remote commands executions: PsExec
If there isn't your bat-file on remote host, copy it first. For example:
copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\
And then execute:
psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat
Note: filepath for psexec is path to file on remote server, not your local.
Expand your one liner into multiple lines. Then it becomes easy:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)
I don't think we need to use an external package for just adding multiple classes.
I personally use
<li className={`li active`}>Stacy</li>
or
<li className={`li ${this.state.isActive ? 'active' : ''}`}>Stacy<li>
or
<li className={'li ' + (this.state.isActive ? 'active' : '') }>Stacy<li>
the second and third one in case you need to add or remove classes conditionally.
As others have correctly pointed out, the first part of the ternary needs to return true
or false
and in your question the return value is a jQuery object.
The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.
So with the CSS:
#blackbox {
background:pink;
width:10px;
height:10px;
}
The following jQuery will flip the colour:
var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));
Android programmers could use BasicNameValuePair
Update:
BasicNameValuePair is now deprecated (API 22). Use Pair instead.
Example usage:
Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"
I managed with a simple $(...).click(); with JQuery 1.6.1
Use time
Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"
You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y")
and newdate2 = time.strptime(date2, "%d/%m/%Y")
to convert them to python's date format. Then, the comparison is obvious:
newdate1 > newdate2
will return False
newdate1 < newdate2
will return True
The post Getting parts of a URL (Regex) discusses parsing a URL to identify its various components. If you want to check if a URL is well-formed, it should be sufficient for your needs.
If you need to check if it's actually valid, you'll eventually have to try to access whatever's on the other end.
In general, though, you'd probably be better off using a function that's supplied to you by your framework or another library. Many platforms include functions that parse URLs. For example, there's Python's urlparse module, and in .NET you could use the System.Uri class's constructor as a means of validating the URL.
If you don't want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId
The finalize()
function is the destructor.
However, it should not be normally used because it is invoked after the GC and you can't tell when that will happen (if ever).
Moreover, it takes more than one GC to deallocate objects that have finalize()
.
You should try to clean up in the logical places in your code using the try{...} finally{...}
statements!
If you're using django, you can use urlquote:
>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'
Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:
A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Rows.Count
or
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Cells.Count
or
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Count
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Asymptotic upper bound means that a given algorithm executes during the maximum amount of time, depending on the number of inputs.
Let's take a sorting algorithm as an example. If all the elements of an array are in descending order, then to sort them, it will take a running time of O(n)
, showing upper bound complexity. If the array is already sorted, the value will be O(1)
.
Generally, O-notation
is used for the upper bound complexity.
Asymptotically tight bound (c1g(n) ≤ f(n) ≤ c2g(n)) shows the average bound complexity for a function, having a value between bound limits (upper bound and lower bound), where c1 and c2 are constants.
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work
In the follwing fgets also not work..
char line[256];
char ch;
int i;
printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
Recognizing only numbers is actually answered on the tesseract FAQ page. See that page for more info, but if you have the version 3 package, the config files are already set up. You just specify on the commandline:
tesseract image.tif outputbase nobatch digits
As for the threshold value, I'm not sure which you mean. If your input is an unusual font, perhaps you might retrain with a sample of your input. An alternative is to change tesseract's pruning threshold. Both options are also mentioned in the FAQ.
There are two different ways to implement inserting data from one table to another table.
This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.
----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
You can remove a specific event handler that was attached by on
, using off
$("#ID").on ("eventName", additionalCss, handlerFunction);
// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);
Using this, you will remove only handlerFunction
Another good practice, is to set a nameSpace for multiple attached events
$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);
// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");
You can do this by using asynchronous Javascript SDK provided by facebook
Have a look at the following code
FB Javascript SDK initialization
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this
Add JQuery Library, I would preferred Google Library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
Add share dialog box (You can customize this dialog box by setting up parameters
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>
Now finally add image button
<img src = "share_button.png" id = "share_button">
For more detailed kind of information. please click here
You need to set your window to be topmost.
It varies based on the options that you pass to install
and the contents of the distutils configuration files on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.
Notably, distutils does not have an uninstall command at this time.
It's also noteworthy that deleting a package/egg can cause dependency issues – utilities like easy_install
attempt to alleviate such problems.
// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";
// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
yield mb_substr($str, $i, 1);
}
})($str);
var_dump(
true === $gen instanceof Traversable,
// PHP 7.1
true === is_iterable($gen)
);
foreach ($gen as $char) {
echo $char, PHP_EOL;
}
Make sure your local server (MAMP, XAMPP, WAMP, etc..) is running.
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
I think you can use date()
function to achive this
$date = '19:24:15 06/13/2013';
echo date('h:i:s a m/d/Y', strtotime($date));
This will output
07:24:15 pm 06/13/2013
h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)
Updated
This is with DateTime
$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;
One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.
Type python in the prompt, and press the tab key to see what versions of Python in your environment.
Another option:
=MID(A1,2,LEN(A1)-2)
Or this (for fun):
=RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)
In the closure you pass to sort
, compare the properties you want to sort by. Like this:
movieArr.sorted { $0.name < $1.name }
or the following in the cases that you want to bypass cases:
movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }
Sidenote: Typically only types start with an uppercase letter; I'd recommend using name
and date
, not Name
and Date
.
Example, in a playground:
class Movie {
let name: String
var date: Int?
init(_ name: String) {
self.name = name
}
}
var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")
let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies
sortedMovies
will be in the order [movieA, movieB, movieC]
Swift5 Update
channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
let channelName1 = channel1.name
let channelName2 = channel2.name
return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)
Original from Sept. 13, 2015:
Quick and easy.
$.each(yourArray, function(index, value){
$('.element').html( $('.element').html() + '<span>' + value +'</span>')
});
Update Sept 9, 2019: No jQuery is needed to iterate the array.
yourArray.forEach((value) => {
$(".element").html(`${$(".element").html()}<span>${value}</span>`);
});
/* --- Or without jQuery at all --- */
yourArray.forEach((value) => {
document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)
But there are a few nuances to this which you might not be aware of.
First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.
You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.
And:
By implementing best practices while writing your code you will be much happier with the outcome.
Additional sources:
Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php
Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/
Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028
Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.
>
>
If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:
$(document).ready(function() {
$("[id^=content]").hover(function() {
$(this).addClass('transition');
}, function() {
$(this).removeClass('transition');
});
});
Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.
One other thing that can cause "ambiguous redirect" is \t
\n
\r
in the variable name you are writing too
Maybe not \n\r
? But err on the side of caution
Try this
echo "a" > ${output_name//[$'\t\n\r']}
I got hit with this one while parsing HTML, Tabs \t
at the beginning of the line.
Hi here is how i did it in one Project :
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
I hope it helps Somebody. Thanks
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
cdate(Format([Datum im Format DDMMYYYY],'##/##/####') )
converts string without punctuation characters into date
Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:
.container {_x000D_
border: 1px solid #DDDDDD;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.tag {_x000D_
float: left;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1000;_x000D_
background-color: #92AD40;_x000D_
padding: 5px;_x000D_
color: #FFFFFF;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="tag">Featured</div>_x000D_
<img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
The key is the container has to be positioned relative and the tag positioned absolute.
Some comments on your code
for(i='A';i<='Z';i++)
, if you can check this with a simple if
statement ... you loop over a whole range while you can simply check whether it is contained in that rangeA
you will have your result the first time you enter the first loop) you still loop over all the restSystem.out.println("Lowercase");
statement (and the uppercase statement) are placed in the wrong loopCharacter
class which has for example nice isUpperCase
and isLowerCase
methodsI leave the rest up to you since it is homework
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
I do it this way for Android 2.2 Froyo release: basically use eclipse to create a class like: public class SomePickContactName extends Activity
then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
}//onCreate
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContactInfo(intent);
// Your class variables now have the data, so do something with it.
}
}//onActivityResult
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}//getContactInfo
You need to add the original repository (the one that you forked) as a remote.
git remote add github (clone url for the orignal repository)
Then you need to bring in the changes to your local repository
git fetch github
Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master
. With these branches you can do what you will. Merge them into your branches etc
this error messages means that CABundle is not given by (-CAfile ...) OR the CABundle file is not closed by a self-signed root certificate.
Don't worry. The connection to server will work even you get theis message from openssl s_client ... (assumed you dont take other mistake too)
I stumbled upon this example on https://css-tricks.com/snippets/jquery/smooth-scrolling/ explaining every line of code. I found this to be the best option.
https://css-tricks.com/snippets/jquery/smooth-scrolling/
You can go native:
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
or with jquery:
$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
}
});
Using the utility I describe here, you can have a more control over the string representation you get for your array.
String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString(); // gives "hello, world"
r.mkString(" | "); // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
You can install and use the pip-autoremove utility to remove a package plus unused dependencies.
# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y
If your application third party redirect internally, so it is better to mock HttpContext in below way :
HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
You can write the below code:-
create procedure spCreateTable
as
begin
create table testtb(Name varchar(20))
end
execute it as:-
exec spCreateTable
Try the below:
[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];
To tint the non active buttons, put the below code in your VC's viewDidLoad
:
UITabBarItem *tabBarItem = [yourTabBarController.tabBar.items objectAtIndex:0];
UIImage *unselectedImage = [UIImage imageNamed:@"icon-unselected"];
UIImage *selectedImage = [UIImage imageNamed:@"icon-selected"];
[tabBarItem setImage: [unselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage: selectedImage];
You need to do this for all the tabBarItems, and yes I know it is ugly and hope there will be cleaner way to do this.
Swift:
UITabBar.appearance().tintColor = UIColor.red
tabBarItem.image = UIImage(named: "unselected")?.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = UIImage(named: "selected")?.withRenderingMode(.alwaysOriginal)
You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.
>> signal
signal =
sin: {{1x1x25 cell} {1x1x25 cell}}
cos: {{1x1x25 cell} {1x1x25 cell}}
>> each(fieldnames(signal))
ans =
CellIterator with properties:
NumberOfIterations: 2.0000e+000
Usage:
for bridge = each(fieldnames(signal))
signal.(bridge) = rand(10);
end
I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.
use continue keyword .
EX:
for(int i = 0; i < 10; i++){
if(i == 5){
continue;
}
}