If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
You can use the jquery .length property
var numItems = $('.item').length;
what about this
--// Convert NVARCHAR to DATETIME
DECLARE @date DATETIME = (SELECT convert(DATETIME, '2013-08-29 13:55:48', 120))
--// Convert DATETIME to custom NVARCHAR FORMAT
SELECT
RIGHT('00'+ CAST(DAY(@date) AS NVARCHAR),2) + '-' +
RIGHT('00'+ CAST(MONTH(@date) AS NVARCHAR),2) + '-' +
CAST(YEAR(@date) AS NVARCHAR) + ' ' +
CAST(CONVERT(TIME,@date) AS NVARCHAR)
result: '29-08-2013 13:55:48.0000000'
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
In node.js we can use node-geocoder npm module to get address from lat, lng.,
geo.js
var NodeGeocoder = require('node-geocoder');
var options = {
provider: 'google',
httpAdapter: 'https', // Default
apiKey: ' ', // for Mapquest, OpenCage, Google Premier
formatter: 'json' // 'gpx', 'string', ...
};
var geocoder = NodeGeocoder(options);
geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
console.log(res);
});
output:
node geo.js
[ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
latitude: 28.5967439,
longitude: 77.3285038,
extra:
{ googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
confidence: 1,
premise: 'C-85B',
subpremise: null,
neighborhood: 'C Block',
establishment: null },
administrativeLevels:
{ level2long: 'Gautam Buddh Nagar',
level2short: 'Gautam Buddh Nagar',
level1long: 'Uttar Pradesh',
level1short: 'UP' },
city: 'Noida',
country: 'India',
countryCode: 'IN',
zipcode: '201301',
provider: 'google' } ]
I'd suggest 3 things in the beginning of your script:
First, as already being said use environment:
#!/usr/bin/env python
Second, set your encoding:
# -*- coding: utf-8 -*-
Third, set some doc string:
"""This is a awesome
python script!"""
And for sure I would use " "
(4 spaces) for ident.
Final header will look like:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a awesome
python script!"""
Best wishes and happy coding.
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
You have to add a ToolTip
control to your form first. Then you can set the text it should display for other controls.
Here's a screenshot showing the designer after adding a ToolTip
control which is named toolTip1
:
Simply run:
ifconfig | grep ether | cut -d " " -f10
OR
ip a | grep ether | cut -d " " -f6
These two example commands will grep all lines with "ether" string and cut the mac address (that we need) following the number spaces (specified in the -f option) of the grepped portion.
Tested on different Linux flavors
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
When you override the init you have also to call the init of the parent class
super(Num2, self).__init__(num)
It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
You can use the File class to list the directories.
File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
System.out.println(Arrays.toString(directories));
Update
Comment from the author on this post wanted a faster way, great discussion here: How to retrieve a list of directories QUICKLY in Java?
Basically:
Working for me:
var st = new StackTrace(e, true);
// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();
Here's a function for this use case:
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Usage:
var $form = $("#form_data");
var data = getFormData($form);
When installing on ubuntu via .deb
you can use sudo apt search cudnn | grep installed
A good combination of String extensions:
public static byte[] GetBytes(this string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static Stream ToStream(this string str)
{
Stream StringStream = new MemoryStream();
StringStream.Read(str.GetBytes(), 0, str.Length);
return StringStream;
}
Use this, from here:
function insertAtCaret(areaId, text) {_x000D_
var txtarea = document.getElementById(areaId);_x000D_
if (!txtarea) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var scrollPos = txtarea.scrollTop;_x000D_
var strPos = 0;_x000D_
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
"ff" : (document.selection ? "ie" : false));_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var range = document.selection.createRange();_x000D_
range.moveStart('character', -txtarea.value.length);_x000D_
strPos = range.text.length;_x000D_
} else if (br == "ff") {_x000D_
strPos = txtarea.selectionStart;_x000D_
}_x000D_
_x000D_
var front = (txtarea.value).substring(0, strPos);_x000D_
var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
txtarea.value = front + text + back;_x000D_
strPos = strPos + text.length;_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var ieRange = document.selection.createRange();_x000D_
ieRange.moveStart('character', -txtarea.value.length);_x000D_
ieRange.moveStart('character', strPos);_x000D_
ieRange.moveEnd('character', 0);_x000D_
ieRange.select();_x000D_
} else if (br == "ff") {_x000D_
txtarea.selectionStart = strPos;_x000D_
txtarea.selectionEnd = strPos;_x000D_
txtarea.focus();_x000D_
}_x000D_
_x000D_
txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
If you want to remove a specific Item or variable from the user's local storage, you can use
localStorage.removeItem("name of localStorage variable you want to remove");
Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:
document.querySelector('[data-answer="42"],[type="submit"]')
document.querySelectorAll('[data-answer="42"],[type="submit"]')
[data-answer="42"],[type="submit"]
[data-answer]
or input[type]
Alternate form of the answer by @rumpel
with open(filename, 'w'): pass
Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!
int minutes = 60;
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime - minutes*60*1000);
System.out.println(currentDate);
Chances are that you've not included the header file that declares system()
.
In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include
preprocessor directive. As the code does not #include
the header file in which system()
is declared, the compilation fails.
To fix this issue, find out which header file provides you with the declaration of system()
and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>
Framework 4: no need to use StreamWriter:
System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);
There is a special build-in util for this - 'yes'.
To answer all questions with the same answer, you can run
yes [answer] |./your_script
Or you can put it inside your script have specific answer to each question
The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.
select * from ttt.table_name;
or if table name in all attached databases is unique
select * from my_unique_table_name;
But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential
normally you would use sqlite-command-line in a script
list4 = list1.Concat(list2).Concat(list3).ToList();
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
//
// UIDevice+Hardware.h
// gauravds
//
#import <UIKit/UIKit.h>
@interface UIDevice (Hardware)
- (NSString *)modelIdentifier;
- (NSString *)modelName;
@end
Why not create a category. Don't use malloc method security leak issue. Use safe functions.
NSLog(@"%@ %@", [[UIDevice currentDevice] modelName], [[UIDevice currentDevice] modelIdentifier]);
See the implentations
//
// UIDevice+Hardware.m
// gauravds
//
#import "UIDevice+Hardware.h"
#import <sys/utsname.h>
@implementation UIDevice (Hardware)
- (NSString *)modelIdentifier {
struct utsname systemInfo;
uname(&systemInfo);
return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}
- (NSString *)modelName {
return [self modelNameForModelIdentifier:[self modelIdentifier]];
}
- (NSString *)modelNameForModelIdentifier:(NSString *)modelIdentifier {
// iPhone http://theiphonewiki.com/wiki/IPhone
if ([modelIdentifier isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([modelIdentifier isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([modelIdentifier isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([modelIdentifier isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (GSM)";
if ([modelIdentifier isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (GSM Rev A)";
if ([modelIdentifier isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (CDMA)";
if ([modelIdentifier isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([modelIdentifier isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([modelIdentifier isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (Global)";
if ([modelIdentifier isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([modelIdentifier isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (Global)";
if ([modelIdentifier isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([modelIdentifier isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (Global)";
if ([modelIdentifier isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([modelIdentifier isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([modelIdentifier isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([modelIdentifier isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([modelIdentifier isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([modelIdentifier isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
if ([modelIdentifier isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
if ([modelIdentifier isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
if ([modelIdentifier isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus";
if ([modelIdentifier isEqualToString:@"iPhone10,1"]) return @"iPhone 8"; // US (Verizon), China, Japan
if ([modelIdentifier isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus"; // US (Verizon), China, Japan
if ([modelIdentifier isEqualToString:@"iPhone10,3"]) return @"iPhone X"; // US (Verizon), China, Japan
if ([modelIdentifier isEqualToString:@"iPhone10,4"]) return @"iPhone 8"; // AT&T, Global
if ([modelIdentifier isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus"; // AT&T, Global
if ([modelIdentifier isEqualToString:@"iPhone10,6"]) return @"iPhone X"; // AT&T, Global
// iPad http://theiphonewiki.com/wiki/IPad
if ([modelIdentifier isEqualToString:@"iPad1,1"]) return @"iPad 1G";
if ([modelIdentifier isEqualToString:@"iPad2,1"]) return @"iPad 2 (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([modelIdentifier isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([modelIdentifier isEqualToString:@"iPad2,4"]) return @"iPad 2 (Rev A)";
if ([modelIdentifier isEqualToString:@"iPad3,1"]) return @"iPad 3 (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM)";
if ([modelIdentifier isEqualToString:@"iPad3,3"]) return @"iPad 3 (Global)";
if ([modelIdentifier isEqualToString:@"iPad3,4"]) return @"iPad 4 (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
if ([modelIdentifier isEqualToString:@"iPad3,6"]) return @"iPad 4 (Global)";
if ([modelIdentifier isEqualToString:@"iPad6,11"]) return @"iPad (5th gen) (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad6,12"]) return @"iPad (5th gen) (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad4,1"]) return @"iPad Air (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad5,3"]) return @"iPad Air 2 (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad5,4"]) return @"iPad Air 2 (Cellular)";
// iPad Mini http://theiphonewiki.com/wiki/IPad_mini
if ([modelIdentifier isEqualToString:@"iPad2,5"]) return @"iPad mini 1G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad2,6"]) return @"iPad mini 1G (GSM)";
if ([modelIdentifier isEqualToString:@"iPad2,7"]) return @"iPad mini 1G (Global)";
if ([modelIdentifier isEqualToString:@"iPad4,4"]) return @"iPad mini 2G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad4,5"]) return @"iPad mini 2G (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad4,6"]) return @"iPad mini 2G (Cellular)"; // TD-LTE model see https://support.apple.com/en-us/HT201471#iPad-mini2
if ([modelIdentifier isEqualToString:@"iPad4,7"]) return @"iPad mini 3G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad4,8"]) return @"iPad mini 3G (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad4,9"]) return @"iPad mini 3G (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad5,1"]) return @"iPad mini 4G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad5,2"]) return @"iPad mini 4G (Cellular)";
// iPad Pro https://www.theiphonewiki.com/wiki/IPad_Pro
if ([modelIdentifier isEqualToString:@"iPad6,3"]) return @"iPad Pro (9.7 inch) 1G (Wi-Fi)"; // http://pdadb.net/index.php?m=specs&id=9938&c=apple_ipad_pro_9.7-inch_a1673_wifi_32gb_apple_ipad_6,3
if ([modelIdentifier isEqualToString:@"iPad6,4"]) return @"iPad Pro (9.7 inch) 1G (Cellular)"; // http://pdadb.net/index.php?m=specs&id=9981&c=apple_ipad_pro_9.7-inch_a1675_td-lte_32gb_apple_ipad_6,4
if ([modelIdentifier isEqualToString:@"iPad6,7"]) return @"iPad Pro (12.9 inch) 1G (Wi-Fi)"; // http://pdadb.net/index.php?m=specs&id=8960&c=apple_ipad_pro_wifi_a1584_128gb
if ([modelIdentifier isEqualToString:@"iPad6,8"]) return @"iPad Pro (12.9 inch) 1G (Cellular)"; // http://pdadb.net/index.php?m=specs&id=8965&c=apple_ipad_pro_td-lte_a1652_32gb_apple_ipad_6,8
if ([modelIdentifier isEqualToString:@"iPad 7,1"]) return @"iPad Pro (12.9 inch) 2G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad 7,2"]) return @"iPad Pro (12.9 inch) 2G (Cellular)";
if ([modelIdentifier isEqualToString:@"iPad 7,3"]) return @"iPad Pro (10.5 inch) 1G (Wi-Fi)";
if ([modelIdentifier isEqualToString:@"iPad 7,4"]) return @"iPad Pro (10.5 inch) 1G (Cellular)";
// iPod http://theiphonewiki.com/wiki/IPod
if ([modelIdentifier isEqualToString:@"iPod1,1"]) return @"iPod touch 1G";
if ([modelIdentifier isEqualToString:@"iPod2,1"]) return @"iPod touch 2G";
if ([modelIdentifier isEqualToString:@"iPod3,1"]) return @"iPod touch 3G";
if ([modelIdentifier isEqualToString:@"iPod4,1"]) return @"iPod touch 4G";
if ([modelIdentifier isEqualToString:@"iPod5,1"]) return @"iPod touch 5G";
if ([modelIdentifier isEqualToString:@"iPod7,1"]) return @"iPod touch 6G"; // as 6,1 was never released 7,1 is actually 6th generation
// Apple TV https://www.theiphonewiki.com/wiki/Apple_TV
if ([modelIdentifier isEqualToString:@"AppleTV1,1"]) return @"Apple TV 1G";
if ([modelIdentifier isEqualToString:@"AppleTV2,1"]) return @"Apple TV 2G";
if ([modelIdentifier isEqualToString:@"AppleTV3,1"]) return @"Apple TV 3G";
if ([modelIdentifier isEqualToString:@"AppleTV3,2"]) return @"Apple TV 3G"; // small, incremental update over 3,1
if ([modelIdentifier isEqualToString:@"AppleTV5,3"]) return @"Apple TV 4G"; // as 4,1 was never released, 5,1 is actually 4th generation
// Simulator
if ([modelIdentifier hasSuffix:@"86"] || [modelIdentifier isEqual:@"x86_64"])
{
BOOL smallerScreen = ([[UIScreen mainScreen] bounds].size.width < 768.0);
return (smallerScreen ? @"iPhone Simulator" : @"iPad Simulator");
}
return modelIdentifier;
}
@end
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
Code from the above answer by Dutchie432
.FixedHeightContainer {
float:right;
height: 250px;
width:250px;
padding:3px;
background:#f00;
}
.Content {
height:224px;
overflow:auto;
background:#fff;
}
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
How about an extension method that doesn't use regex.
If you do stick to one of the Regex options at least use RegexOptions.Compiled
in the static variable.
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
This builds on Usman Zafar's answer converted to a method group.
You can't get a path to file from WhatsApp. They don't expose it now. The only thing you can get is InputStream
:
InputStream is = getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/16695"));
Using is
you can show a picture from WhatsApp in your app.
In this Safari HTML5 reference, you can read
To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.
I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.
And what happen if the user catch de JSON and change the bool to True?
I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.
Browsers now warn for the use of synchronous XHR. MDN says this was implemented recently:
Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)
Here's how the change got implemented in Firefox and Chromium:
As for Chrome people report this started happening somewhere around version 39. I'm not sure how to link a revision/changeset to a particular version of Chrome.
Yes, it happens when jQuery appends markup to the page including script tags that load external js files. You can reproduce it with something like this:
$('body').append('<script src="foo.js"></script>');
I guess jQuery will fix this in some future version. Until then we can either ignore it or use A. Wolff's suggestion above.
There is only static fields in interface that dosen't need to initialized during object creation in subclass and the method of interface has to provide actual implementation in subclass .So there is no need of constructor in interface.
Second reason-during the object creation of subclass, the parent constructor is called .But if there will be more than one interface implemented then a conflict will occur during call of interface constructor as to which interface's constructor will call first
$(document).ready(function () {
Addrow();
})
$("#add").click(function () {
Addrow();
})
rowcount = $("#tbuser td").closest.length;
function Addrow() {
rowcount++;
debugger
var markup = "<tr><td></td><td><input type='text' name='stuclass' id='stuclass'/></td><td><select name='Institute' class='Institute_" + rowcount + "'></select></td><td><input type='text' name='obtmark' id='obtmark'/></td><td><input type='text' name='totalmark' id='totalmark'/></td><td><input type='text' name='per' id='per'/></td><td><button type='button' id='delete' onclick='deleterow(this);'>DELETE</button></td></tr>";
$(".tbuser tbody").append(markup);
$.ajax({
type: 'GET',
url: '@Url.Action("bindinst", "Home")',
data: '',
dataType: "json",
success: function (data) {
debugger;
$(".Institute_" + rowcount).empty();
$(".Institute_" + rowcount).append('<option Value="">--Select--</option>');
$.each(data, function (i, result) {
$(".Institute_" + rowcount).append('<option Value="' + result.Value + '">' + result.Text + '</option>');
});
},
});
}
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
On Ubuntu you can try this command.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Specific version : sudo n 8.11.3 instead of sudo n stable
Jeff Atwood has a post on this here: http://www.codinghorror.com/blog/archives/000229.html
He eventually went with Edit Pad Pro, because "Based on my prior usage history, I felt that EditPad Pro was the best fit: it's quite fast on large text files, has best-of-breed regex support, and it doesn't pretend to be an IDE."
Normally, mutt sets the From:
header based on the from
configuration variable you set in ~/.muttrc
:
set from="Fubar <foo@bar>"
If this is not set, mutt
uses the EMAIL
environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):
EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"
However, if you want to be able to edit the From:
header while composing, you need to configure mutt
to allow you to edit headers first. This involves adding the following line in your ~/.muttrc
:
set edit_headers=yes
After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From:
header.
Shell is an interface between a user and OS to access to an operating system's services. It can be either GUI or CLI (Command Line interface).
sh (Bourne shell) is a shell command-line interpreter, for Unix/Unix-like operating systems. It provides some built-in commands. In scripting language we denote interpreter as #!/bin/sh
. It was one most widely supported by other shells like bash (free/open), kash (not free).
Bash (Bourne again shell) is a shell replacement for the Bourne shell. Bash is superset of sh. Bash supports sh. POSIX is a set of standards defining how POSIX-compliant systems should work. Bash is not actually a POSIX compliant shell. In a scripting language we denote the interpreter as #!/bin/bash
.
Analogy:
Subclass the button to store the required value, maybe create a protocol (ControlWithData or something). Set the value when you add the button to the table view cell. In your touch up event, see if the sender obeys the protocol and extract the data. I normally store a reference to the actual object that is rendered on the table view cell.
foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
I've heard vague rumours that this is terifically slow. Anyone know? – Orion Edwards Oct 15 '08 at 1:31 7
I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:
Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums)
{
DoSomething(suitEnum);
}
That's at least a little faster, ja?
For macOS catalina try this : open Xcode. if not existing. download from App store (about 11GB) then open Xcode>open developer tool>more developer tool and used my apple id to download a compatible command line tool. Then, after downloading, I opened Xcode>Preferences>Locations>Command Line Tool and selected the newly downloaded command line tool from downloads.
https://pypi.python.org/pypi/Django/ - works for packages whose maintainers choose to show all packages https://pypi.python.org/simple/pip/ - should do the trick anyhow (lists all links)
Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)
If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!
class Foo{
public static void main(String[] args){
Bar myInstance = new Bar();
myInstance.do(); // works!
Bar.do(); // doesn't work!
Bar.doSomethingStatic(); // works!
}
}
class Bar{
public do() {
// do something
}
public static doSomethingStatic(){
}
}
Also remember, classes in Java should start with an uppercase letter.
I've used ng-change:
Date.prototype.addDays = function(days) {_x000D_
var dat = new Date(this.valueOf());_x000D_
dat.setDate(dat.getDate() + days);_x000D_
return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
function($rootScope, $scope) {_x000D_
function init() {_x000D_
$scope.startDate = new Date();_x000D_
$scope.endDate = $scope.startDate.addDays(14);_x000D_
}_x000D_
_x000D_
_x000D_
function load() {_x000D_
alert($scope.startDate);_x000D_
alert($scope.endDate);_x000D_
}_x000D_
_x000D_
init();_x000D_
// public methods_x000D_
$scope.load = load;_x000D_
$scope.setStart = function(date) {_x000D_
$scope.startDate = date;_x000D_
};_x000D_
$scope.setEnd = function(date) {_x000D_
$scope.endDate = date;_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
<label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
Run_x000D_
</button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )
Here it is: http://jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
html
<input id="myinputfield" value="This is some text" type="button">?
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});?
Here's a simple and dumb solution:
>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)
The best (and easiest) way to copy data from a workbook to another is to use the object model of Excel.
Option Explicit
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set targetworkbook
Set wb2 = ActiveWorkbook
'For instance, copy data from a range in the first workbook to another range in the other workbook
wb2.Worksheets("Sheet2").Range("C3:D4").Value = wb.Worksheets("Sheet1").Range("A1:B2").Value
End Sub
In other words, doesn't DEFAULT render NOT NULL redundant ?
No, it is not redundant. To extended accepted answer. For column col
which is nullable awe can insert NULL even when DEFAULT is defined:
CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);
-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);
+-----+------+
| ID | COL |
+-----+------+
| 1 | null |
+-----+------+
Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL
:
CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL);
INSERT INTO t2(id, col) VALUES(1, NULL);
+-----+-----+
| ID | COL |
+-----+-----+
| 1 | 10 |
+-----+-----+
Here we tried to insert NULL but get default instead.
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
You can use zip
with *
to get transpose of a matrix:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
I just want to add that if you want to write special text if It null than you make it like that
Assert.assertNotNull("The object you enter return null", str1)
First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.
#include <stdio.h>
int main(int argc, char **argv)
{
FILE* sourceFile;
FILE* destFile;
char buf[50];
int numBytes;
if(argc!=3)
{
printf("Usage: fcopy source destination\n");
return 1;
}
sourceFile = fopen(argv[1], "rb");
destFile = fopen(argv[2], "wb");
if(sourceFile==NULL)
{
printf("Could not open source file\n");
return 2;
}
if(destFile==NULL)
{
printf("Could not open destination file\n");
return 3;
}
while(numBytes=fread(buf, 1, 50, sourceFile))
{
fwrite(buf, 1, numBytes, destFile);
}
fclose(sourceFile);
fclose(destFile);
return 0;
}
EDIT: The glibc reference has this to say:
In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).
If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.
You can use both of these methods but there are differences:
SELECT ISNULL(col1, 0 ) FROM table1
SELECT COALESCE(col1, 0 ) FROM table1
Comparing COALESCE() and ISNULL():
The ISNULL function and the COALESCE expression have a similar purpose but can behave differently.
Because ISNULL is a function, it is evaluated only once. As described above, the input values for the COALESCE expression can be evaluated multiple times.
Data type determination of the resulting expression is different. ISNULL uses the data type of the first parameter, COALESCE follows the CASE expression rules and returns the data type of value with the highest precedence.
The NULLability of the result expression is different for ISNULL and COALESCE. The ISNULL return value is always considered NOT NULLable (assuming the return value is a non-nullable one) whereas COALESCE with non-null parameters is considered to be NULL. So the expressions ISNULL(NULL, 1) and COALESCE(NULL, 1) although equivalent have different nullability values. This makes a difference if you are using these expressions in computed columns, creating key constraints or making the return value of a scalar UDF deterministic so that it can be indexed as shown in the following example.
-- This statement fails because the PRIMARY KEY cannot accept NULL values -- and the nullability of the COALESCE expression for col2 -- evaluates to NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0) PRIMARY KEY,
col3 AS ISNULL(col1, 0)
);
-- This statement succeeds because the nullability of the -- ISNULL function evaluates AS NOT NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0),
col3 AS ISNULL(col1, 0) PRIMARY KEY
);
Validations for ISNULL and COALESCE are also different. For example, a NULL value for ISNULL is converted to int whereas for COALESCE, you must provide a data type.
ISNULL takes only 2 parameters whereas COALESCE takes a variable number of parameters.
if you need to know more here is the full document from msdn.
Try the following:
DateTime dtStart;
DateTime dtEnd;
if (DateTime.TryParse( tb1.Text, out dtStart ) && DateTime.TryParse(tb2.Text, out dtEnd ))
{
TimeSpan ts = dtStart - dtEnd;
double difference = ts.TotalMilliseconds;
}
There is a built in function to compare lists:
Following is the syntax for cmp() method -
cmp(list1, list2)
#!/usr/bin/python
list1, list2 = [123, 'xyz'], [123, 'xyz']
print cmp(list1,list2)
When we run above program, it produces following result -
0
If the result is a tie, meaning that 0 is returned
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
Just open your project urls.py, then find this if statement.
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.
if True:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
In django 1.10 you can write so:
urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]
If it's an object method, you need to pass the object to CallObjectMethod
:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
What you were doing was the equivalent of jstr.messageMe()
.
Since your is a void method, you should call:
env->CallVoidMethod(obj, messageMe, jstr);
If you want to return a result, you need to change your JNI signature (the ()V
means a method of void
return type) and also the return type in your Java code.
Use the formula by tigeravatar:
=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50
as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).
To find all of those values, highlight col A. Data > Filter and choose Filter by color.
How about "TIMESTAMPDIFF":
SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff
I had similar requirements but I didn't want to use v-model
to have the state in the parent component. Then I got this to work:
<input
type="checkbox"
:checked="checked"
@input="checked = $event.target.checked"
/>
To pass down the value from the parent, I made a small change on this and it works.
<input
type="checkbox"
:checked="aPropFrom"
@input="$emit('update:aPropFrom', $event.target.checked)"
/>
Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.
Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.
The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.
An important warning: obviously, decrypting your iOS device’s backup
removes its encryption. To protect your privacy and security, you should
only run these scripts on a machine with full-disk encryption. While it
is possible for a security expert to write software that protects keys in
memory, e.g. by using functions like VirtualLock()
and
SecureZeroMemory()
among many other things, these
Python scripts will store your encryption keys and passwords in strings to
be garbage-collected by Python. This means your secret keys and passwords
will live in RAM for a while, from whence they will leak into your swap
file and onto your disk, where an adversary can recover them. This
completely defeats the point of having an encrypted backup.
The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.
Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.
To decrypt:
Decode the keybag stored in the BackupKeyBag
entry of
Manifest.plist
. A high-level overview of this structure is given in
the whitepaper. The iPhone Wiki
describes the binary format: a 4-byte string type field, a 4-byte
big-endian length field, and then the value itself.
The important values are the PBKDF2 ITER
ations and SALT
, the double
protection salt DPSL
and iteration count DPIC
, and then for each
protection CLS
, the WPKY
wrapped key.
Using the backup password derive a 32-byte key using the correct PBKDF2
salt and number of iterations. First use a SHA256 round with DPSL
and
DPIC
, then a SHA1 round with ITER
and SALT
.
Unwrap each wrapped key according to RFC 3394.
Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey
in Manifest.plist
, and unwrapping it. You now have a
SQLite database with all file metadata.
For each file of interest, get the class-encrypted per-file encryption
key and protection class code by looking in the Files.file
database
column for a binary plist containing EncryptionKey
and
ProtectionClass
entries. Strip the initial four-byte length tag from
EncryptionKey
before using.
Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.
First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:
CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \
pip install biplist fastpbkdf2 pycrypto
In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:
#!/usr/bin/env python3.7
# coding: UTF-8
from __future__ import print_function
from __future__ import division
import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify
import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException
def main():
## Parse options
parser = argparse.ArgumentParser()
parser.add_argument('--backup-directory', dest='backup_directory',
default='testdata/encrypted')
parser.add_argument('--password-pipe', dest='password_pipe',
help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
parser.add_argument('--no-anonymize-output', dest='anonymize',
action='store_false')
args = parser.parse_args()
global ANONYMIZE_OUTPUT
ANONYMIZE_OUTPUT = args.anonymize
if ANONYMIZE_OUTPUT:
print('Warning: All output keys are FAKE to protect your privacy')
manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
with open(manifest_file, 'rb') as infile:
manifest_plist = biplist.readPlist(infile)
keybag = Keybag(manifest_plist['BackupKeyBag'])
# the actual keys are unknown, but the wrapped keys are known
keybag.printClassKeys()
if args.password_pipe:
password = readpipe(args.password_pipe)
if password.endswith(b'\n'):
password = password[:-1]
else:
password = getpass.getpass('Backup password: ').encode('utf-8')
## Unlock keybag with password
if not keybag.unlockWithPasscode(password):
raise Exception('Could not unlock keybag; bad password?')
# now the keys are known too
keybag.printClassKeys()
## Decrypt metadata DB
manifest_key = manifest_plist['ManifestKey'][4:]
with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
encrypted_db = db.read()
manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
decrypted_data = AESdecryptCBC(encrypted_db, key)
temp_dir = tempfile.mkdtemp()
try:
# Does anyone know how to get Python’s SQLite module to open some
# bytes in memory as a database?
db_filename = os.path.join(temp_dir, 'db.sqlite3')
with open(db_filename, 'wb') as db_file:
db_file.write(decrypted_data)
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
c = conn.cursor()
# c.execute("select * from Files limit 1");
# r = c.fetchone()
c.execute("""
SELECT fileID, domain, relativePath, file
FROM Files
WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
ORDER BY domain, relativePath""")
results = c.fetchall()
finally:
shutil.rmtree(temp_dir)
for item in results:
fileID, domain, relativePath, file_bplist = item
plist = biplist.readPlistFromString(file_bplist)
file_data = plist['$objects'][plist['$top']['root'].integer]
size = file_data['Size']
protection_class = file_data['ProtectionClass']
encryption_key = plist['$objects'][
file_data['EncryptionKey'].integer]['NS.data'][4:]
backup_filename = os.path.join(args.backup_directory,
fileID[:2], fileID)
with open(backup_filename, 'rb') as infile:
data = infile.read()
key = keybag.unwrapKeyForClass(protection_class, encryption_key)
# truncate to actual length, as encryption may introduce padding
decrypted_data = AESdecryptCBC(data, key)[:size]
print('== decrypted data:')
print(wrap(decrypted_data))
print()
print('== pretty-printed plist')
pprint.pprint(biplist.readPlistFromString(decrypted_data))
##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/
CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"] #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
1:"NSFileProtectionComplete",
2:"NSFileProtectionCompleteUnlessOpen",
3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
4:"NSFileProtectionNone",
5:"NSFileProtectionRecovery?",
6: "kSecAttrAccessibleWhenUnlocked",
7: "kSecAttrAccessibleAfterFirstUnlock",
8: "kSecAttrAccessibleAlways",
9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2
class Keybag(object):
def __init__(self, data):
self.type = None
self.uuid = None
self.wrap = None
self.deviceKey = None
self.attrs = {}
self.classKeys = {}
self.KeyBagKeys = None #DATASIGN blob
self.parseBinaryBlob(data)
def parseBinaryBlob(self, data):
currentClassKey = None
for tag, data in loopTLVBlocks(data):
if len(data) == 4:
data = struct.unpack(">L", data)[0]
if tag == b"TYPE":
self.type = data
if self.type > 3:
print("FAIL: keybag type > 3 : %d" % self.type)
elif tag == b"UUID" and self.uuid is None:
self.uuid = data
elif tag == b"WRAP" and self.wrap is None:
self.wrap = data
elif tag == b"UUID":
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
currentClassKey = {b"UUID": data}
elif tag in CLASSKEY_TAGS:
currentClassKey[tag] = data
else:
self.attrs[tag] = data
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
def unlockWithPasscode(self, passcode):
passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
self.attrs[b"DPSL"],
self.attrs[b"DPIC"], 32)
passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
self.attrs[b"SALT"],
self.attrs[b"ITER"], 32)
print('== Passcode key')
print(anonymize(hexlify(passcode_key)))
for classkey in self.classKeys.values():
if b"WPKY" not in classkey:
continue
k = classkey[b"WPKY"]
if classkey[b"WRAP"] & WRAP_PASSCODE:
k = AESUnwrap(passcode_key, classkey[b"WPKY"])
if not k:
return False
classkey[b"KEY"] = k
return True
def unwrapKeyForClass(self, protection_class, persistent_key):
ck = self.classKeys[protection_class][b"KEY"]
if len(persistent_key) != 0x28:
raise Exception("Invalid key length")
return AESUnwrap(ck, persistent_key)
def printClassKeys(self):
print("== Keybag")
print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
print("Keybag version: %d" % self.attrs[b"VERS"])
print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
print("-"*209)
print("".join(["Class".ljust(53),
"WRAP".ljust(5),
"Type".ljust(11),
"Key".ljust(65),
"WPKY".ljust(65),
"Public key"]))
print("-"*208)
for k, ck in self.classKeys.items():
if k == 6:print("")
print("".join(
[PROTECTION_CLASSES.get(k).ljust(53),
str(ck.get(b"WRAP","")).ljust(5),
KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
]))
print()
def loopTLVBlocks(blob):
i = 0
while i + 8 <= len(blob):
tag = blob[i:i+4]
length = struct.unpack(">L",blob[i+4:i+8])[0]
data = blob[i+8:i+8+length]
yield (tag,data)
i += 8 + length
def unpack64bit(s):
return struct.unpack(">Q",s)[0]
def pack64bit(s):
return struct.pack(">Q",s)
def AESUnwrap(kek, wrapped):
C = []
for i in range(len(wrapped)//8):
C.append(unpack64bit(wrapped[i*8:i*8+8]))
n = len(C) - 1
R = [0] * (n+1)
A = C[0]
for i in range(1,n+1):
R[i] = C[i]
for j in reversed(range(0,6)):
for i in reversed(range(1,n+1)):
todec = pack64bit(A ^ (n*j+i))
todec += pack64bit(R[i])
B = Crypto.Cipher.AES.new(kek).decrypt(todec)
A = unpack64bit(B[:8])
R[i] = unpack64bit(B[8:])
if A != 0xa6a6a6a6a6a6a6a6:
return None
res = b"".join(map(pack64bit, R[1:]))
return res
ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
if len(data) % 16:
print("AESdecryptCBC: data length not /16, truncating")
data = data[0:(len(data)/16) * 16]
data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
if padding:
return removePadding(16, data)
return data
##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange
anon_random = random.Random(0)
memo = {}
def anonymize(s):
if type(s) == str:
s = s.encode('utf-8')
global anon_random, memo
if ANONYMIZE_OUTPUT:
if s in memo:
return memo[s]
possible_alphabets = [
string.digits,
string.digits + 'abcdef',
string.ascii_letters,
"".join(chr(x) for x in range(0, 256)),
]
for a in possible_alphabets:
if all((chr(c) if type(c) == int else c) in a for c in s):
alphabet = a
break
ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
memo[s] = ret
return ret
else:
return s
def wrap(s, width=78):
"Return a width-wrapped repr(s)-like string without breaking on \’s"
s = repr(s)
quote = s[0]
s = s[1:-1]
ret = []
while len(s):
i = s.rfind('\\', 0, width)
if i <= width - 4: # "\x??" is four characters
i = width
ret.append(s[:i])
s = s[i:]
return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)
def readpipe(path):
if stat.S_ISFIFO(os.stat(path).st_mode):
with open(path, 'rb') as pipe:
return pipe.read()
else:
raise Exception("Not a pipe: {!r}".format(path))
if __name__ == '__main__':
main()
Which then prints this output:
Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class WRAP Type Key WPKY Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete 2 AES 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen 2 AES 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2 AES e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone 2 AES 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery? 3 AES a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072
kSecAttrAccessibleWhenUnlocked 2 AES 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock 2 AES 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways 2 AES b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly 3 AES 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 3 AES b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly 3 AES 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2
== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class WRAP Type Key WPKY Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete 2 AES 64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen 2 AES 22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2 AES 1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone 2 AES 2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery? 3 AES 9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072
kSecAttrAccessibleWhenUnlocked 2 AES 606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock 2 AES 6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways 2 AES c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly 3 AES 80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 3 AES a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly 3 AES 1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2
== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'
== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}
The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:
$ python iphone-dataprotection/python_scripts/keychain_tool.py ...
--------------------------------------------------------------------------------------
| Passwords |
--------------------------------------------------------------------------------------
|Service |Account |Data |Access group |Protection class|
--------------------------------------------------------------------------------------
|AirPort |Ed’s Coffee Shop |<3FrenchRoast |apple |AfterFirstUnlock|
...
That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.
To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT
and LISTAGG
:
SELECT * FROM
(
SELECT id, k, v
FROM _kv
)
PIVOT
(
LISTAGG(v ,',')
WITHIN GROUP (ORDER BY k)
FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;
Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.
For a responsive design it is good to use a container having a relative layout and content (placed in container) having fixed layout as.
CSS Styles:
/*Centering element in a base container*/
.contianer-relative{
position: relative;
}
.content-center-text-absolute{
position: absolute;
text-align: center;
width: 100%;
height: 0%;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 51;
}
HTML code:
<!-- Have used ionic classes -->
<div class="row">
<div class="col remove-padding contianer-relative"><!-- container with position relative -->
<div class="item item-image clear-border" ><a href="#"><img ng-src="img/engg-manl.png" alt="ENGINEERING MANUAL" title="ENGINEERING MANUAL" ></a></div> <!-- Image intended to work as a background -->
<h4 class="content-center-text-absolute white-text"><strong>ENGINEERING <br> MANUALS</strong></h4><!-- content div with position fixed -->
</div>
<div class="col remove-padding contianer-relative"><!-- container with position relative -->
<div class="item item-image clear-border"><a href="#"><img ng-src="img/contract-directory.png" alt="CONTRACTOR DIRECTORY" title="CONTRACTOR DIRECTORY"></a></div><!-- Image intended to work as a background -->
<h4 class="content-center-text-absolute white-text"><strong>CONTRACTOR <br> DIRECTORY</strong></h4><!-- content div with position fixed -->
</div>
</div>
For IONIC Grid layout, evenly spaced grid elements and the classes used in above HTML, please refer - Grid: Evenly Spaced Columns. Hope it helps you out... :)
I resolved this issue by setting an email address in Git:
git config --global user.email "[email protected]"
I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?
Forget the mouse. To remove 5 lines, either:
Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?
As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.
I suggest spending some time with the Vim Tutor (run vimtutor
) to get more familiar with Vim in a very didactic way.
try
std::fill
and also
std::size siz = vec.size();
//no memory allocating
vec.resize(0);
vec.resize(siz, 0);
No, [^\x20-\x7E]
is not ASCII.
This is real ASCII:
[^\x00-\x7F]
Otherwise, it will trim out newlines and other special characters that are part of the ASCII table!
Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).
The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.
Please follow the steps as mentioned below.
Visit the standard URL www.visualstudio.com/downloads
Scroll down and click on encircled below as shown in snapshot down
After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Join
You can use the basic way image preloaders work to test if an image exists.
function checkImage(imageSrc, good, bad) {
var img = new Image();
img.onload = good;
img.onerror = bad;
img.src = imageSrc;
}
checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );
As per http://content-security-policy.com/ The best place to start:
default-src 'none';
script-src 'self';
connect-src 'self';
img-src 'self';
style-src 'self';
font-src 'self';
Never inline styles or scripts as it undermines the purpose of CSP. You can use a stylesheet to set a style property and then use a function in a .js
file to change the style property (if need be).
Have a look at Listamatic. Tabs are semantically just a list of items styled in a particular way. You don't even necessarily need javascript to make vertical tabs work as the various examples at Listamatic show.
cmd.exe
, require elevated prompt:Only sessions:
regedit /e "%USERPROFILE%\Desktop\putty-sessions.reg" HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions
All settings:
regedit /e "%USERPROFILE%\Desktop\putty.reg" HKEY_CURRENT_USER\Software\SimonTatham
Only sessions:
reg export HKCU\Software\SimonTatham\PuTTY\Sessions ([Environment]::GetFolderPath("Desktop") + "\putty-sessions.reg")
All settings:
reg export HKCU\Software\SimonTatham ([Environment]::GetFolderPath("Desktop") + "\putty.reg")
Double-click on the *.reg
file and accept the import.
cmd.exe
, require elevated command prompt:regedit /i putty-sessions.reg
regedit /i putty.reg
reg import putty-sessions.reg
reg import putty.reg
Note: do not replace SimonTatham
with your username.
Note: It will create a reg
file on the Desktop of the current user.
Note: It will not export related SSH keys.
I couldn't get it to trigger that on any page. A more robust version of this would do it:
window.console.log = function(){
console.error('The developer console is temp...');
window.console.log = function() {
return false;
}
}
console.log('test');
To style the output: Colors in JavaScript console
Edit Thinking @joeldixon66 has the right idea: Disable JavaScript execution from console « ::: KSpace :::
According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:
dependencies {
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html
It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:
char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);
Without the fflush()
, if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar()
peeks the "a", but the "\n" remains in the buffer, so the next fgets()
will find it and return an empty string without even waiting for user input.
However, note that this use of fflush()
is unportable. I've tested right now on a Linux machine, and it does not work, for example.
The se argument from the example also isn't in the help or online documentation.
When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible
If you are using SQL Server try this:
SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())
Based on your update it would be:
SELECT * FROM FB WHERE Dte < DATEADD(month, -2, GETDATE())
var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);
Faster version as per Tim's suggestion:
var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));
You can use a data trigger (with a view model) on the button to enable a wait cursor.
<Button x:Name="NextButton"
Content="Go"
Command="{Binding GoCommand }">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Cursor" Value="Arrow"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
<Setter Property="Cursor" Value="Wait"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Here is the code from the view-model:
public class MainViewModel : ViewModelBase
{
// most code removed for this example
public MainViewModel()
{
GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
}
// flag used by data binding trigger
private bool _isWorking = false;
public bool IsWorking
{
get { return _isWorking; }
set
{
_isWorking = value;
OnPropertyChanged("IsWorking");
}
}
// button click event gets processed here
public ICommand GoCommand { get; private set; }
private void OnGoCommand(object obj)
{
if ( _selectedCustomer != null )
{
// wait cursor ON
IsWorking = true;
_ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
OnPropertyChanged("GridData");
// wait cursor off
IsWorking = false;
}
}
}
If you want to display links coming from your state or store in Vue 2.0, you can do like this:
<a v-bind:href="''">
{{ url_link }}
</a>
Note that Gene Burinsky's answer (at the time of writing the selected answer) keeps the first of each duplicated column. To keep the last:
df=df.loc[:, ~df.columns[::-1].duplicated()[::-1]]
Use lambda
import tkinter as tk
root = tk.Tk()
def go(text):
print(text)
b = tk.Button(root, text="Click", command=lambda: go("hello"))
b.pack()
root.mainloop()
output:
hello
You can simply use JavaScripts join()
function for that. This would simply look like a.value.join(',')
. The output would be a string though.
Remember that when you write:
MyArray = Range("A1:A5000")
you are really writing
MyArray = Range("A1:A5000").Value
You can also use names:
MyArray = Names("MyWSTable").RefersToRange.Value
But Value is not the only property of Range. I have used:
MyArray = Range("A1:A5000").NumberFormat
I doubt
MyArray = Range("A1:A5000").Font
would work but I would expect
MyArray = Range("A1:A5000").Font.Bold
to work.
I do not know what formats you want to copy so you will have to try.
However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.
Post Edit information
Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.
Of the following statements, the second would fail with a type mismatch:
ValueArray = .Range("A1:T5000").Value
ColourArray = .Range("A1:T5000").Font.Color
ValueArray must be of type variant. I tried both variant and long for ColourArray without success.
I filled ColourArray with values and tried the following statement:
.Range("A1:T5000").Font.Color = ColourArray
The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.
There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.
I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.
With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.
With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.
With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.
Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.
** Code for Version 1**
I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.
Sub SelectionCopyAndPaste()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
NumSelect = NumSelect + 7
Loop
Debug.Print Timer - StartTime
' Average 12.43 secs
Application.Calculation = xlCalculationAutomatic
End Sub
** Code for Versions 2 and 3**
The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.
Type ValueDtl
Value As String
Colour As Long
End Type
Sub SelectionViaArray()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim InxVLCrnt As Integer
Dim InxVLCrntMax As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Dim ValueList() As ValueDtl
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' I have sized the array to more than I expect to require because ReDim
' Preserve is expensive. However, I will resize if I fill the array.
' For my experiment I know exactly how many elements I need but that
' might not be true for you.
ReDim ValueList(1 To 25000)
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
InxVLCrntMax = 0 ' Last used element in ValueList.
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
With Sheets("Time1")
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
InxVLCrntMax = InxVLCrntMax + 1
If InxVLCrntMax > UBound(ValueList) Then
' Resize array if it has been filled
ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
End If
With .Cells(RowSrcCrnt, ColSrcCrnt)
ValueList(InxVLCrntMax).Value = .Value ' Version 2
ValueList(InxVLCrntMax).Value = .Formula ' Version 3
ValueList(InxVLCrntMax).Colour = .Font.Color
End With
NumSelect = NumSelect + 7
Loop
End With
With Sheets("Time2")
For InxVLCrnt = 1 To InxVLCrntMax
With .Cells(RowDestCrnt, ColDestCrnt)
.Value = ValueList(InxVLCrnt).Value ' Version 2
.Formula = ValueList(InxVLCrnt).Value ' Version 3
.Font.Color = ValueList(InxVLCrnt).Colour
End With
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
Next
End With
Debug.Print Timer - StartTime
' Version 2 average 1.47 secs
' Version 3 average 1.83 secs
Application.Calculation = xlCalculationAutomatic
End Sub
You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
Create a URI like this one:
https://maps.google.com/?q=[lat],[long]
For example:
https://maps.google.com/?q=-37.866963,144.980615
or, if you are using the javascript API
map.setCenter(new GLatLng(0,0))
This, and other helpful info comes from here:
https://developers.google.com/maps/documentation/javascript/reference/?csw=1#Map
use a "not exists" left join:
SELECT p.*
FROM primary_table p LEFT JOIN second s ON p.ID = s.ID
WHERE s.ID IS NULL
From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:
select * from table where length(RTRIM(fieldName))=10
UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:
select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890 ' as varchar(30)) ))
as tab(fieldName)
FIELDNAME LEN_ONLY LEN_RTRIM
------------------------------ ----------- -----------
1234567890 12 10
One can test this by using this term:
where length(fieldName)!=length(rtrim(fieldName))
const
is for compile-time constants. You could just make it static readonly
, but that would only apply to the METRICS
variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");
You may want to use a ReadOnlyCollection<T>
to wrap it. For example:
public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
(new List<String> {
SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn,
SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
ReadOnlyCollection<T>
just wraps a potentially-mutable collection, but as nothing else will have access to the List<T>
afterwards, you can regard the overall collection as immutable.
(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)
Whether you declare it as IList<string>
, IEnumerable<string>
, ReadOnlyCollection<string>
or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string>
would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T>
may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T>
could be handy - but inflexible.
Finally, I found the solution to my problem.
I looked into the Magento system log file (var/log/system.log). There I saw the exact error.
The error is as below:-
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227
Actually, I had this error before. But, error display message like Error: 404 Not Found
was new to me.
The reason for this error is that store_id
and website_id
for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
I have written about this problem and solution over here:-
Magento: Solution to "Error: 404 Not Found" in Admin Login Page
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:
'Save module with name: ListOfInteger
Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function
Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub
Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
If list(MyCounter) = value Then
ListContains = True
Exit For
End If
Next
End Function
Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
Debug.Print list(MyCounter)
Next
End Sub
You might use it as follows in your code:
Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer
Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
If IsEmpty(MyCell.value) = False Then
If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
ListAdd rows, MyCell.Row
End If
End If
Next
ListOfInteger.DebugOutputList rows
End Sub
If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)
=Join(Parameters!Product.Label, vbcrfl) for new line
//increase char array size if u want take more no. of characters.
#include <stdio.h>
int main()
{
char s[10],s1[10];
scanf("\n");//imp for below statement to work
scanf("%[^\n]%c",s);//to take input till the you click enter
scanf("%s",s1);//to take input till a space
printf("%s",s);
printf("%s",s1);
return 0;
}
https://kotlinlang.org/docs/reference/collections.html
According to above link List<E> is immutable in Kotlin. However this would work:
var list2 = ArrayList<String>()
list2.removeAt(1)
You can just use val()
method:
$('select').val('the_value');
There is a pretty simple fix for this, the border-spacing
and border-collapse
CSS attributes work on display: table
.
You can use the following to get padding/margins in your cells.
.container {_x000D_
width: 850px;_x000D_
padding: 0;_x000D_
display: table;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
border-collapse: separate;_x000D_
border-spacing: 15px;_x000D_
}_x000D_
_x000D_
.row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.home_1 {_x000D_
width: 64px;_x000D_
height: 64px;_x000D_
padding-right: 20px;_x000D_
margin-right: 10px;_x000D_
display: table-cell;_x000D_
}_x000D_
_x000D_
.home_2 {_x000D_
width: 350px;_x000D_
height: 64px;_x000D_
padding: 0px;_x000D_
vertical-align: middle;_x000D_
font-size: 150%;_x000D_
display: table-cell;_x000D_
}_x000D_
_x000D_
.home_3 {_x000D_
width: 64px;_x000D_
height: 64px;_x000D_
padding-right: 20px;_x000D_
margin-right: 10px;_x000D_
display: table-cell;_x000D_
}_x000D_
_x000D_
.home_4 {_x000D_
width: 350px;_x000D_
height: 64px;_x000D_
padding: 0px;_x000D_
vertical-align: middle;_x000D_
font-size: 150%;_x000D_
display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="home_1">Foo</div>_x000D_
<div class="home_2">Foo</div>_x000D_
<div class="home_3">Foo</div>_x000D_
<div class="home_4">Foo</div>_x000D_
</div>_x000D_
_x000D_
<div class="row">_x000D_
<div class="home_1">Foo</div>_x000D_
<div class="home_2">Foo</div>_x000D_
</div>_x000D_
</div>
_x000D_
Note that you have to have
border-collapse: separate;
Otherwise it will not work.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for Use static imports (only 1.5 or higher).
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.
If you're on Windows, try findstr
. Third-party tools are not needed:
findstr /V /L "searchstring" inputfile.txt > outputfile.txt
It supports regex's too! Just read the tool's help findstr /?
.
P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...
I just ran this on a 1 GB log file, and it literally took 3 seconds.
Use a common table expression to add grand total row, top 100
is required for order by
to work.
With Detail as
(
SELECT top 100 propertyId, SUM(Amount) as TOTAL_COSTS
FROM MyTable
WHERE EndDate IS NULL
GROUP BY propertyId
ORDER BY TOTAL_COSTS desc
)
Select * from Detail
Union all
Select ' Total ', sum(TOTAL_COSTS) from Detail
I would add that since version 3.6, we can use fstrings like the following
foo = "john"
bar = "smith"
print(f"My name is {foo} {bar}")
Which give
My name is john smith
Everything is converted to strings
mylist = ["foo", "bar"]
print(f"mylist = {mylist}")
Result:
mylist = ['foo', 'bar']
you can pass function, like in others formats method
print(f'Hello, here is the date : {time.strftime("%d/%m/%Y")}')
Giving for example
Hello, here is the date : 16/04/2018
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
There are some awesome libraries such as select2, but it doesn't match my need. I've made a sample from scratch in order to use a simple input text.
I only use bootstrap and JQuery, Hope it'll be useful: Example
HTML:
<div class="form-group col-md-12">
<label for="address">Address</label>
<input type="text" class="form-control" id="address">
</div>
<div class="form-group">
<div class="col-md-4">
<label for="number">number</label>
<input type="text" class="form-control" id="number">
</div>
<div class="col-md-8">
<label for="street">street</label>
<input type="text" class="form-control" id="street">
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<label for="zip">zip</label>
<input type="text" class="form-control" id="zip">
</div>
<div class="col-md-8">
<label for="town">town</label>
<input type="text" class="form-control" id="town">
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<label for="department">Department</label>
<input type="text" class="form-control" id="department">
</div>
<div class="col-md-4">
<label for="region">Region</label>
<input type="text" class="form-control" id="region">
</div>
<div class="col-md-4">
<label for="country">Country</label>
<input type="text" class="form-control" id="country">
</div>
</div>
JS:
$("input#address").suggest({
label : "Adresse complete",
street_number_input : {
id : "number",
label : "Numero de la rue"
},
street_name_input : {
id : "street",
label : "Nom de la rue"
},
zip_input : {
id : "zip",
label : "Code postal"
},
town_input : {
id : "town",
label : "Ville"
},
department_input : {
id : "department",
label : "Departement"
},
region_input : {
id : "region",
label : "Region"
},
country_input : {
id : "country",
label : "Pays"
}
});
I was trying to go from godaddy to app engine. What did the trick was using this line:
openssl req -new -newkey rsa:2048 -nodes -keyout name.unencrypted.priv.key -out name.csr
Exactly as is, but replacing name with my domain name (not that it really even mattered)
And I answered all the questions pertaining to common name / organization as www.name.com
Then I opened the csr, copied it, pasted it in go daddy, then downloaded it, unzipped it, navigated to the unzipped folder with the terminal and entered:
cat otherfilegodaddygivesyou.crt gd_bundle-g2-g1.crt > name.crt
Then I used these instructions from Trouble with Google Apps Custom Domain SSL, which were:
openssl rsa -in privateKey.key -text > private.pem
openssl x509 -inform PEM -in www_mydomain_com.crt > public.pem
exactly as is, except instead of privateKey.key I used name.unencrypted.priv.key, and instead of www_mydomain_com.crt, I used name.crt
Then I uploaded the public.pem to the admin console for the "PEM encoded X.509 certificate", and uploaded the private.pem for the "Unencrypted PEM encoded RSA private key"..
.. And that finally worked.
I don't think having a list of chars to remove is safe. I would rather use the following:
For filenames: Use an internal ID or a hash of the filecontent. Save the document name in a database. This way you can keep the original filename and still find the file.
For url parameters: Use urlencode()
to encode any special characters.
The following code will show the current commit
git show HEAD
How about:
hasSiblings
or isFollowedBySiblings (or isFolloedByItems, or isFollowedByOtherItems etc.)
or moreItems
Although I think that even though you shouldn't make a habit of braking 'the rules' sometimes the best way to accomplish something may be to make an exception of the rule (Code Complete guidelines), and in your case, name the variable isNotLast
jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:
$(document).keypress(function(e){
var checkWebkitandIE=(e.which==26 ? 1 : 0);
var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);
if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});
Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064
Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:
$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
$("body").append("<p>ctrl+z detected!</p>");
});
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
I made this short example which also works.
#include <iostream>
#include <type_traits>
class foo;
class bar;
template<class T>
struct is_bar
{
template<class Q = T>
typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
{
return true;
}
template<class Q = T>
typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
{
return false;
}
};
int main()
{
is_bar<foo> foo_is_bar;
is_bar<bar> bar_is_bar;
if (!foo_is_bar.check() && bar_is_bar.check())
std::cout << "It works!" << std::endl;
return 0;
}
Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)
You can see it in action here.
You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.
makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
var json_data = JSON.stringify(data);
return $.ajax({
type: "POST",
url: url,
data: json_data,
dataType: "json",
contentType: "application/json;charset=utf-8"
});
}
// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
.success(function(data){
// treat the READUSERS data returned
})
.fail(function(sender, message, details){
alert("Sorry, something went wrong!");
});
Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:
(X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C)
, where ...
means "0 or more different values(B,) dot (B, C) -> (C,)
(A, B) dot (B,) -> (A,)
(B,) dot (B,) -> ()
Your problem is that you are using np.matrix
, which is totally unnecessary in your code - the main purpose of np.matrix
is to translate a * b
into np.dot(a, b)
. As a general rule, np.matrix
is probably not a good choice.
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.
import { OpaqueToken } from "@angular/core";
export let APP_CONFIG = new OpaqueToken("my.config");
export interface MyAppConfig {
apiEndpoint: string;
}
export const AppConfig: MyAppConfig = {
apiEndpoint: "http://localhost:8080/api/"
};
Inject it in providers in app.module.ts
You will be able to use it across every components.
EDIT for Angular 4 :
For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.
Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject
Example Code
Angular 2 Using Opaque Tokens
const API_URL = new OpaqueToken('apiUrl'); //no Type Check
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
new Inject(API_URL) //notice the new Inject
]
}
]
Angular 4 Using Injection Tokens
const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector
providers: [
{
provide: DataService,
useFactory: (http, apiUrl) => {
// create data service
},
deps: [
Http,
API_URL // no `new Inject()` needed!
]
}
]
Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.
go to http://nodejs.org/
and hit the button that says "Download For ..."
This'll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.
Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.
Have tried this on a Windows machine and it works
If you wanna install opencv for python version 3.7, heres how you do it!
py -3.7 -m pip install opencv-python
ZonedDateTime.now( // Capture current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Montreal" ) // Specify desired/expected time zone. Or pass `ZoneId.systemDefault` for the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMinute() // Extract the minute of the hour of the time-of-day from the `ZonedDateTime` object.
42
ZonedDateTime
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime
.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Call any of the many getters to pull out pieces of the date-time.
int year = zdt.getYear() ;
int monthNumber = zdt.getMonthValue() ;
String monthName = zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.JAPAN ) ; // Locale determines human language and cultural norms used in localizing. Note that `Locale` has *nothing* to do with time zone.
int dayOfMonth = zdt.getDayOfMonth() ;
String dayOfWeek = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
int hour = zdt.getHour() ; // Extract the hour from the time-of-day.
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;
The java.time classes resolve to nanoseconds. Your Question asked for the fraction of a second in milliseconds. Obviously, you can divide by a million to truncate nanoseconds to milliseconds, at the cost of possible data loss. Or use the TimeUnit
enum for such conversion.
long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;
DateTimeFormatter
To produce a String
to combine pieces of text, use DateTimeFormatter
class. Search Stack Overflow for more info on this.
Instant
Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant
.
Instant instant = zdt.toInstant() ;
And go back again.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDateTime
A couple of other Answers use the LocalDateTime
class. That class in not appropriate to the purpose of tracking actual moments, specific moments on the timeline, as it intentionally lacks any concept of time zone or offset-from-UTC.
So what is LocalDateTime
good for? Use LocalDateTime
when you intend to apply a date & time to any locality or all localities, rather than one specific locality.
For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" )
. That value has no meaning until you apply a time zone (a ZoneId
) to get a ZonedDateTime
. Christmas happens first in Kiribati, then later in New Zealand and far east Asia. Hours later Christmas starts in India. More hour later in Africa & Europe. And still not Xmas in the Americas until several hours later. Christmas starting in any one place should be represented with ZonedDateTime
. Christmas everywhere is represented with a LocalDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
Since I had a similar situation, I thought I'd share my situation and how these answers helped me (thanks everyone).
So I decided to work locally by amending my last commit every time I wanted to save my progress on the main branch (I know, I should've branched out, committed on that, kept pushing and later merge back to master).
One late night, in paranoid fear of loosing my progress to hardware failure or something out of the ether, I decided to push master to origin. Later I kept amending my local master branch and when I decided it's time to push again, I was faced with different master branches and found out I can't amend origin/upstream (duh!) like I can local development branches.
So I didn't checkout master locally because I already was after a commit. Master was unchanged. I didn't even need to reset --hard, my current commit was OK.
I just forced push to origin, without even specifying what commit I wanted to force on master since in this case it's whatever HEAD is at. Checked git diff master..origin/master
so there weren't any differences and that's it. All fixed. Thanks! (I know, I'm a git newbie, please forgive!).
So if you're already OK with your master branch locally, just:
git push --force origin master
git diff master..origin/master
I know this has been answered but wanted to provide alternate solution for anyone in the future:
You can use .loc
to subset the dataframe by only values that are notnull()
, and then subset out the 'x'
column only. Take that same vector, and apply(int)
to it.
If column x is float:
df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)
Try this values_list('column_name', flat=True)
.
answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()]).values_list('column_name', flat=True)
It will return you a list with specified column values
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
I finally got this working.
I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...
In code you can put the following:
HttpComponentsClientHttpRequestFactory rf =
(HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);
The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory
class used by the RestTemplate
. Therefore, all subsequent calls made by RestTemplate
will use the timeout settings defined above.
Or the better option is to do this:
<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="readTimeout" value="${application.urlReadTimeout}" />
<property name="connectTimeout" value="${application.urlConnectionTimeout}" />
</bean>
</constructor-arg>
</bean>
Where I use the RestOperations
interface in my code and get the timeout values from a properties file.
The best way is deltaE. DeltaE is a number that shows the difference of the colors. If deltae < 1 then the difference can't recognize by human eyes. I wrote a code in canvas and js for converting rgb to lab and then calculating delta e. On this example the code is recognising pixels which have different color with a base color that I saved as LAB1. and then if it is different makes those pixels red. You can increase or reduce the sensitivity of the color difference with increae or decrease the acceptable range of delta e. In this example I assigned 10 for deltaE in the line that I wrote (deltae <= 10):
<script>
var constants = {
canvasWidth: 700, // In pixels.
canvasHeight: 600, // In pixels.
colorMap: new Array()
};
// -----------------------------------------------------------------------------------------------------
function fillcolormap(imageObj1) {
function rgbtoxyz(red1,green1,blue1){ // a converter for converting rgb model to xyz model
var red2 = red1/255;
var green2 = green1/255;
var blue2 = blue1/255;
if(red2>0.04045){
red2 = (red2+0.055)/1.055;
red2 = Math.pow(red2,2.4);
}
else{
red2 = red2/12.92;
}
if(green2>0.04045){
green2 = (green2+0.055)/1.055;
green2 = Math.pow(green2,2.4);
}
else{
green2 = green2/12.92;
}
if(blue2>0.04045){
blue2 = (blue2+0.055)/1.055;
blue2 = Math.pow(blue2,2.4);
}
else{
blue2 = blue2/12.92;
}
red2 = (red2*100);
green2 = (green2*100);
blue2 = (blue2*100);
var x = (red2 * 0.4124) + (green2 * 0.3576) + (blue2 * 0.1805);
var y = (red2 * 0.2126) + (green2 * 0.7152) + (blue2 * 0.0722);
var z = (red2 * 0.0193) + (green2 * 0.1192) + (blue2 * 0.9505);
var xyzresult = new Array();
xyzresult[0] = x;
xyzresult[1] = y;
xyzresult[2] = z;
return(xyzresult);
} //end of rgb_to_xyz function
function xyztolab(xyz){ //a convertor from xyz to lab model
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var x2 = x/95.047;
var y2 = y/100;
var z2 = z/108.883;
if(x2>0.008856){
x2 = Math.pow(x2,1/3);
}
else{
x2 = (7.787*x2) + (16/116);
}
if(y2>0.008856){
y2 = Math.pow(y2,1/3);
}
else{
y2 = (7.787*y2) + (16/116);
}
if(z2>0.008856){
z2 = Math.pow(z2,1/3);
}
else{
z2 = (7.787*z2) + (16/116);
}
var l= 116*y2 - 16;
var a= 500*(x2-y2);
var b= 200*(y2-z2);
var labresult = new Array();
labresult[0] = l;
labresult[1] = a;
labresult[2] = b;
return(labresult);
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageX = 0;
var imageY = 0;
context.drawImage(imageObj1, imageX, imageY, 240, 140);
var imageData = context.getImageData(0, 0, 240, 140);
var data = imageData.data;
var n = data.length;
// iterate over all pixels
var m = 0;
for (var i = 0; i < n; i += 4) {
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
var xyzcolor = new Array();
xyzcolor = rgbtoxyz(red,green,blue);
var lab = new Array();
lab = xyztolab(xyzcolor);
constants.colorMap.push(lab); //fill up the colormap array with lab colors.
}
}
// -----------------------------------------------------------------------------------------------------
function colorize(pixqty) {
function deltae94(lab1,lab2){ //calculating Delta E 1994
var c1 = Math.sqrt((lab1[1]*lab1[1])+(lab1[2]*lab1[2]));
var c2 = Math.sqrt((lab2[1]*lab2[1])+(lab2[2]*lab2[2]));
var dc = c1-c2;
var dl = lab1[0]-lab2[0];
var da = lab1[1]-lab2[1];
var db = lab1[2]-lab2[2];
var dh = Math.sqrt((da*da)+(db*db)-(dc*dc));
var first = dl;
var second = dc/(1+(0.045*c1));
var third = dh/(1+(0.015*c1));
var deresult = Math.sqrt((first*first)+(second*second)+(third*third));
return(deresult);
} // end of deltae94 function
var lab11 = new Array("80","-4","21");
var lab12 = new Array();
var k2=0;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageData = context.getImageData(0, 0, 240, 140);
var data = imageData.data;
for (var i=0; i<pixqty; i++) {
lab12 = constants.colorMap[i];
var deltae = deltae94(lab11,lab12);
if (deltae <= 10) {
data[i*4] = 255;
data[(i*4)+1] = 0;
data[(i*4)+2] = 0;
k2++;
} // end of if
} //end of for loop
context.clearRect(0,0,240,140);
alert(k2);
context.putImageData(imageData,0,0);
}
// -----------------------------------------------------------------------------------------------------
$(window).load(function () {
var imageObj = new Image();
imageObj.onload = function() {
fillcolormap(imageObj);
}
imageObj.src = './mixcolor.png';
});
// ---------------------------------------------------------------------------------------------------
var pixno2 = 240*140;
</script>
Generally, you need to get a handle to the control via its clientId. This example uses a JSF2 Facelets view with a request-scope binding to get a handle to the other control:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head><title>Show/Hide</title></h:head>
<h:body>
<h:form>
<h:button value="toggle"
onclick="toggle('#{requestScope.foo.clientId}'); return false;" />
<h:inputText binding="#{requestScope.foo}" id="x" style="display: block" />
</h:form>
<script type="text/javascript">
function toggle(id) {
var element = document.getElementById(id);
if(element.style.display == 'block') {
element.style.display = 'none';
} else {
element.style.display = 'block'
}
}
</script>
</h:body>
</html>
Exactly how you do this will depend on the version of JSF you're working on. See this blog post for older JSF versions: JSF: working with component identifiers.
Instead of
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
you should try
port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port
so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.
One example could be that it only listens to 127.0.0.1
, which makes connecting from a different host impossible.
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
For my case, it was with Toolbar i resolved it like this:
ic_toolbar_drawble.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/ic_toolbar"
android:right="-16dp"
android:left="-16dp"/>
</layer-list>
In my Fragment, i check the api :
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
toolbar.setLogo(R.drawable.ic_toolbar);
else
toolbar.setLogo(R.drawable.ic_toolbar_draweble);
Good luck!
This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.
Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.
Look here: http://en.cppreference.com/w/cpp/algorithm/sort.
It says:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
bool cmp(const Type1 &a, const Type2 &b);
Also, here's an example of how you can use std::sort
using a custom C++14 polymorphic lambda:
std::sort(std::begin(container), std::end(container),
[] (const auto& lhs, const auto& rhs) {
return lhs.first < rhs.first;
});
I tried the following code that seemed to work:
if(open(my $FILE, "<File.txt")) {
while(<$FILE>){
print "$_";}
} else {
print "File could not be opened or did not exists\n";
}
From the header of '/etc/mysql/my.cnf':
MariaDB programs look for option files in a set of
locations which depend on the deployment platform.
[...] For information about these locations, do:
'my_print_defaults --help' and see what is printed under
"Default options are read from the following files in the given order:"
More information at: http://dev.mysql.com/doc/mysql/en/option-files.html
getElementById returns either a reference to an element with an id matching the argument, or null if no such element exists in the document.
getElementsByName() (note the plural Elements) returns a (possibly empty) HTMLCollection of the elements with a name matching the argument. Note that IE treats the name and id attributes and properties as the same thing, so getElementsByName will return elements with matching id also.
getElementsByTagName is similar but returns a NodeList. It's all there in the relevant specifications.
This is a fiddle I always use with my Web applications:
$('body').on('dragstart drop', function(e){
e.preventDefault();
return false;
});
It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.
<form action="portfolio.html">
<button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>
I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)
Double.parseDouble(p.replace(',','.'))
...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.
Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.
You want to use the null-coalescing operator, which is designed for exactly this purpose.
Using it you end up with this code.
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor
at the end of your MySQLdb.connect
.
I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:
conn = MySQLdb.connect(host="oldhost",
user="olduser",
passwd="oldpass",
db="olddb",
cursorclass=MySQLdb.cursors.DictCursor)
Which was replaced by:
conn = MySQLdb.connect(host="newhost",
user="newuser",
passwd="newpass",
db="newdb")
The parameter cursorclass=MySQLdb.cursors.DictCursor
at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.
So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.
I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.
Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -
SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;
Query performance is also high.
For me this was the solution.
The problem was that the SVN server was behind a reverse-proxy (pound). And the reverse proxy had to be told to allow OPTIONS
.
You may probably do this way
var currentMonth = new Date().getMonth();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here
}
The quick answer is to use a for()
loop in place of your foreach()
loops. Something like:
@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
@Html.LabelFor(model => model.Theme[themeIndex])
@for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
{
@Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
@for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
{
@Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
@Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
@Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
}
}
}
But this glosses over why this fixes the problem.
There are three things that you have at least a cursory understanding before you can resolve this issue. I have to admit that I cargo-culted this for a long time when I started working with the framework. And it took me quite a while to really get what was going on.
Those three things are:
LabelFor
and other ...For
helpers work in MVC?All three of these concepts link together to get an answer.
LabelFor
and other ...For
helpers work in MVC?So, you've used the HtmlHelper<T>
extensions for LabelFor
and TextBoxFor
and others, and
you probably noticed that when you invoke them, you pass them a lambda and it magically generates
some html. But how?
So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for
TextBoxFor
public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
First, this is an extension method for a strongly typed HtmlHelper
, of type <TModel>
. So, to simply
state what happens behind the scenes, when razor renders this view it generates a class.
Inside of this class is an instance of HtmlHelper<TModel>
(as the property Html
, which is why you can use @Html...
),
where TModel
is the type defined in your @model
statement. So in your case, when you are looking at this view TModel
will always be of the type ViewModels.MyViewModels.Theme
.
Now, the next argument is a bit tricky. So lets look at an invocation
@Html.TextBoxFor(model=>model.SomeProperty);
It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for
this argument would simply be a Func<TModel, TProperty>
, where TModel
is the type of the view model and TProperty
is inferred as the type of the property.
But thats not quite right, if you look at the actual type of the argument its Expression<Func<TModel, TProperty>>
.
So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just code references.)
However, when the compiler sees that the type is an Expression<>
, it doesn't immediately compile the lambda down to MSIL, instead it generates an
Expression Tree!
So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:
| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.
Simply put, an expression tree is a representation of a function as a collection of "actions".
In the case of model=>model.SomeProperty
, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"
This expression tree can be compiled into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.
So Func<>
or Action<>
, once you have them, they are pretty much atomic. All you can really do is Invoke()
them, aka tell them to
do the work they are supposed to do.
Expression<Func<>>
on the other hand, represents a collection of actions, which can be appended, manipulated, visited, or compiled and invoked.
So with that understanding of what an Expression<>
is, we can go back to Html.TextBoxFor
. When it renders a textbox, it needs
to generate a few things about the property that you are giving it. Things like attributes
on the property for validation, and specifically
in this case it needs to figure out what to name the <input>
tag.
It does this by "walking" the expression tree and building a name. So for an expression like model=>model.SomeProperty
, it walks the expression
gathering the properties that you are asking for and builds <input name='SomeProperty'>
.
For a more complicated example, like model=>model.Foo.Bar.Baz.FooBar
, it might generate <input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" />
Make sense? It is not just the work that the Func<>
does, but how it does its work is important here.
(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)
So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat
Dictionary<string, string>
, we have lost the hierarchical structure our nested view model may have had. It's the
model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do
this? You guessed it, by using the "key" or name of the input that got posted.
So if the form post looks like
Foo.Bar.Baz.FooBar = Hello
And you are posting to a model called SomeViewModel
, then it does the reverse of what the helper did in the first place. It looks for
a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...
Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar".
PHEW!!!
And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.
So your solution doesn't work because the Html.[Type]For()
helpers need an expression. And you are just giving them a value. It has no idea
what the context is for that value, and it doesn't know what to do with it.
Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of TModel
, because you are in a different view context. This means that you can describe
your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It
will only generate based on the expression it's given (not the entire context).
So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:
@Html.TextBoxFor(model=>model.FooBar)
Rather than
@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)
That means that it will generate an input tag like this:
<input name="FooBar" />
Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property
called FooBar
off of TModel
. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a Baz
, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.
Now once you get all of this, you can start to do really interesting things with Expression<>
, by programatically extending them and doing
other neat things with them. I won't get into any of that. But, hopefully, this will
give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.
This is a known issue in BS 3 - https://github.com/twbs/bootstrap/issues/9862?source=cc
I have tested on Bootply using the latest build, so keep watching GitHub for the latest updates/fix.
In Bootstrap 3, .row
is must be used inside a .container
or .container-fluid
to counteract the negative margins on the row. This will eliminate the horizontal scrollbar.
From the docs...
"Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding."
Bootstrap 4
The container
>row
>col
relationship work the same way as 3.x...
"Containers are the most basic layout element in Bootstrap and are required when using our default grid system"
If you need this solution for only few types of modals just use
style="width:90%"
attribute.
example:
div class="modal-dialog modal-lg" style="width:90%"
note: this will change only this particular modal
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
Below code worked perfectly with me:
dependencies {
api 'com.android.support:design:28.0.0-alpha3'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha2'
}
First Question: Difference between parseInt and valueOf in java?
Second Question:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
Third Question:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:
http://rip747.github.com/popupwindow/
Alternately, you can always use JavaScript's window.open function.
Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.
As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:
To call router:
this.router.navigate(['/myUrlPath', "someId", "another ID"]);
In routes.ts:
{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},
A .zip
file is required in order to include npm modules in Lambda. And you really shouldn't be using the Lambda web editor for much of anything- as with any production code, you should be developing locally, committing to git, etc.
1) My Lambda functions are usually helper utilities for a larger project, so I create a /aws/lambdas directory within that to house them.
2) Each individual lambda directory contains an index.js file containing the function code, a package.json file defining dependencies, and a /node_modules subdirectory. (The package.json file is not used by Lambda, it's just so we can locally run the npm install
command.)
package.json:
{
"name": "my_lambda",
"dependencies": {
"svg2png": "^4.1.1"
}
}
3) I .gitignore all node_modules directories and .zip files so that the files generated from npm installs and zipping won't clutter our repo.
.gitignore:
# Ignore node_modules
**/node_modules
# Ignore any zip files
*.zip
4) I run npm install
from within the directory to install modules, and develop/test the function locally.
5) I .zip the lambda directory and upload it via the console.
(IMPORTANT: Do not use Mac's 'compress' utility from Finder to zip the file! You must run zip from the CLI from within the root of the directory- see here)
zip -r ../yourfilename.zip *
NOTE:
You might run into problems if you install the node modules locally on your Mac, as some platform-specific modules may fail when deployed to Lambda's Linux-based environment. (See https://stackoverflow.com/a/29994851/165673)
The solution is to compile the modules on an EC2 instance launched from the AMI that corresponds with the Lambda Node.js runtime you're using (See this list of Lambda runtimes and their respective AMIs).
See also AWS Lambda Deployment Package in Node.js - AWS Lambda
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.
If you have Git Bash you can open your emulator with a double-click, with some initial setup (tested in Windows 10 only):
cd ~/AppData/Local/Android/sdk/emulator
./emulator -list-avds
and keep note of the emulator's name. MY_EMULATOR
for example.Open Notepad and add these two lines (insert your emulator's name instead of MY_EMULATOR
):
cd ~/AppData/Local/Android/sdk/emulator; ./emulator -avd MY_EMULATOR
Save the file somewhere convinient as myfile.sh. You can change "myfile" as suits you best, but the extension .sh is needed.
chmod +x myfile.sh
. Remember to put your file's name instead of myfile.And that's it! From now on, everytime you need to start that emulator, just locate your myfile.sh and double click on it and wait for your Android emulator to launch!
In the simplest form, the following code works in Angular 6/7
this.http.post("http://destinationurl.com/endpoint", fileFormData)
.subscribe(response => {
//handle response
}, err => {
//handle error
});
Here is the complete implementation
The below should work
describe "#foo"
it "should call 'bar' with appropriate arguments" do
subject.stub(:bar)
subject.foo
expect(subject).to have_received(:bar).with("Invalid number of arguments")
end
end
Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments
You can use this functions to check valid phone numbers and normalize them:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
For system applications only!
Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();
Note: System applications don't need to run "su" to execute this command.
I don't have enough reputation to add a comment to the top answer, but with the power of aliases you can get away with just typing the following:
powershell "start cmd -v runAs"
This is just a shorter version of user3018703 excellent solution:
powershell -Command "Start-Process cmd -Verb RunAs"
This works fine for me,
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];
NSError* theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
attributes:nil error:&theError])
{
NSLog(@"not created");
}
If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.
$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!
if (file_exists($vid)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $vid); // check mime type
finfo_close($finfo);
if (preg_match('/video\/*/', $mime_type)) {
$video_attributes = _get_video_attributes($vid, $ffmpeg_path);
print_r('Codec: ' . $video_attributes['codec'] . '<br/>');
print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');
print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
. $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');
print_r('Size: ' . _human_filesize(filesize($vid)));
} else {
print_r('File is not a video.');
}
} else {
print_r('File does not exist.');
}
function _get_video_attributes($video, $ffmpeg) {
$command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
$output = shell_exec($command);
$regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
if (preg_match($regex_sizes, $output, $regs)) {
$codec = $regs [1] ? $regs [1] : null;
$width = $regs [3] ? $regs [3] : null;
$height = $regs [4] ? $regs [4] : null;
}
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$ms = $regs [4] ? $regs [4] : null;
}
return array('codec' => $codec,
'width' => $width,
'height' => $height,
'hours' => $hours,
'mins' => $mins,
'secs' => $secs,
'ms' => $ms
);
}
function _human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
Using @Jarda's guide you can define this if you need to set the variable the same value for all tests:
@Before
public void setClientMapper() throws NoSuchFieldException, SecurityException{
FieldSetter.setField(client, client.getClass().getDeclaredField("mapper"), new Mapper());
}
But beware that setting private values to be different should be handled with care. If they are private are for some reason.
Example, I use it, for example, to change the wait time of a sleep in the unit tests. In real examples I want to sleep for 10 seconds but in unit-test I'm satisfied if it's immediate. In integration tests you should test the real value.
After cleaning the string, you can match non-whitespace characters or word-boundaries.
Here are two simple regular expressions to capture words in a string:
/\S+/g
/\b[a-z\d]+\b/g
The example below shows how to retrieve the word count from a string, by using these capturing patterns.
/*Redirect console output to HTML.*/document.body.innerHTML='';console.log=function(s){document.body.innerHTML+=s+'\n';};_x000D_
/*String format.*/String.format||(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return"undefined"!=typeof a[n]?a[n]:m})}([].slice.call(arguments,1))});_x000D_
_x000D_
// ^ IGNORE CODE ABOVE ^_x000D_
// =================_x000D_
_x000D_
// Clean and match sub-strings in a string._x000D_
function extractSubstr(str, regexp) {_x000D_
return str.replace(/[^\w\s]|_/g, '')_x000D_
.replace(/\s+/g, ' ')_x000D_
.toLowerCase().match(regexp) || [];_x000D_
}_x000D_
_x000D_
// Find words by searching for sequences of non-whitespace characters._x000D_
function getWordsByNonWhiteSpace(str) {_x000D_
return extractSubstr(str, /\S+/g);_x000D_
}_x000D_
_x000D_
// Find words by searching for valid characters between word-boundaries._x000D_
function getWordsByWordBoundaries(str) {_x000D_
return extractSubstr(str, /\b[a-z\d]+\b/g);_x000D_
}_x000D_
_x000D_
// Example of usage._x000D_
var edisonQuote = "I have not failed. I've just found 10,000 ways that won't work.";_x000D_
var words1 = getWordsByNonWhiteSpace(edisonQuote);_x000D_
var words2 = getWordsByWordBoundaries(edisonQuote);_x000D_
_x000D_
console.log(String.format('"{0}" - Thomas Edison\n\nWord count via:\n', edisonQuote));_x000D_
console.log(String.format(' - non-white-space: ({0}) [{1}]', words1.length, words1.join(', ')));_x000D_
console.log(String.format(' - word-boundaries: ({0}) [{1}]', words2.length, words2.join(', ')));
_x000D_
body { font-family: monospace; white-space: pre; font-size: 11px; }
_x000D_
You could also create a mapping of words to get unique counts.
function cleanString(str) {_x000D_
return str.replace(/[^\w\s]|_/g, '')_x000D_
.replace(/\s+/g, ' ')_x000D_
.toLowerCase();_x000D_
}_x000D_
_x000D_
function extractSubstr(str, regexp) {_x000D_
return cleanString(str).match(regexp) || [];_x000D_
}_x000D_
_x000D_
function getWordsByNonWhiteSpace(str) {_x000D_
return extractSubstr(str, /\S+/g);_x000D_
}_x000D_
_x000D_
function getWordsByWordBoundaries(str) {_x000D_
return extractSubstr(str, /\b[a-z\d]+\b/g);_x000D_
}_x000D_
_x000D_
function wordMap(str) {_x000D_
return getWordsByWordBoundaries(str).reduce(function(map, word) {_x000D_
map[word] = (map[word] || 0) + 1;_x000D_
return map;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
function mapToTuples(map) {_x000D_
return Object.keys(map).map(function(key) {_x000D_
return [ key, map[key] ];_x000D_
});_x000D_
}_x000D_
_x000D_
function mapToSortedTuples(map, sortFn, sortOrder) {_x000D_
return mapToTuples(map).sort(function(a, b) {_x000D_
return sortFn.call(undefined, a, b, sortOrder);_x000D_
});_x000D_
}_x000D_
_x000D_
function countWords(str) {_x000D_
return getWordsByWordBoundaries(str).length;_x000D_
}_x000D_
_x000D_
function wordFrequency(str) {_x000D_
return mapToSortedTuples(wordMap(str), function(a, b, order) {_x000D_
if (b[1] > a[1]) {_x000D_
return order[1] * -1;_x000D_
} else if (a[1] > b[1]) {_x000D_
return order[1] * 1;_x000D_
} else {_x000D_
return order[0] * (a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0));_x000D_
}_x000D_
}, [1, -1]);_x000D_
}_x000D_
_x000D_
function printTuples(tuples) {_x000D_
return tuples.map(function(tuple) {_x000D_
return padStr(tuple[0], ' ', 12, 1) + ' -> ' + tuple[1];_x000D_
}).join('\n');_x000D_
}_x000D_
_x000D_
function padStr(str, ch, width, dir) { _x000D_
return (width <= str.length ? str : padStr(dir < 0 ? ch + str : str + ch, ch, width, dir)).substr(0, width);_x000D_
}_x000D_
_x000D_
function toTable(data, headers) {_x000D_
return $('<table>').append($('<thead>').append($('<tr>').append(headers.map(function(header) {_x000D_
return $('<th>').html(header);_x000D_
})))).append($('<tbody>').append(data.map(function(row) {_x000D_
return $('<tr>').append(row.map(function(cell) {_x000D_
return $('<td>').html(cell);_x000D_
}));_x000D_
})));_x000D_
}_x000D_
_x000D_
function addRowsBefore(table, data) {_x000D_
table.find('tbody').prepend(data.map(function(row) {_x000D_
return $('<tr>').append(row.map(function(cell) {_x000D_
return $('<td>').html(cell);_x000D_
}));_x000D_
}));_x000D_
return table;_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
$('#countWordsBtn').on('click', function(e) {_x000D_
var str = $('#wordsTxtAra').val();_x000D_
var wordFreq = wordFrequency(str);_x000D_
var wordCount = countWords(str);_x000D_
var uniqueWords = wordFreq.length;_x000D_
var summaryData = [_x000D_
[ 'TOTAL', wordCount ],_x000D_
[ 'UNIQUE', uniqueWords ]_x000D_
];_x000D_
var table = toTable(wordFreq, ['Word', 'Frequency']);_x000D_
addRowsBefore(table, summaryData);_x000D_
$('#wordFreq').html(table);_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
table-layout: fixed;_x000D_
width: 200px;_x000D_
font-family: monospace;_x000D_
}_x000D_
thead {_x000D_
border-bottom: #000 3px double;;_x000D_
}_x000D_
table, td, th {_x000D_
border: #000 1px solid;_x000D_
}_x000D_
td, th {_x000D_
padding: 2px;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
textarea, input[type="button"], table {_x000D_
margin: 4px;_x000D_
padding: 2px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<h1>Word Frequency</h1>_x000D_
<textarea id="wordsTxtAra" cols="60" rows="8">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal._x000D_
_x000D_
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this._x000D_
_x000D_
But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.</textarea><br />_x000D_
<input type="button" id="countWordsBtn" value="Count Words" />_x000D_
<div id="wordFreq"></div>
_x000D_
You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.
The equivalent of .live() in 1.7 looks like this:
$(document).on('click', '#child', function() ...);
Basically, watch the document for click events and filter them for #child.
if it was an IPv6 address, have a look at this: https://code.google.com/p/android/issues/detail?id=33046
Looks like there was a bug in Android that was fixed in 4.3(?).
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Your root logger definition is a bit confused. See the log4j documentation.
This is a standard Java properties file, which means that lines are treated as key=value pairs. Your second log4j.rootLogger
line is overwriting the first, which explains why you aren't seeing anything on the console
appender.
You need to merge your two rootLogger
definitions into one. It looks like you're trying to have DEBUG
messages go to the console and INFO
messages to the file. The root logger can only have one level, so you need to change your configuration so that the appenders have appropriate levels.
While I haven't verified that this is correct, I'd guess it'll look something like this:
log4j.rootLogger=DEBUG,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
Note that you also have an error in casing - you have console lowercase in one place and in CAPS in another.
declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
@locationID =
CASE @locationType
WHEN 'location' THEN account_location
WHEN 'area' THEN xxx_location_area
WHEN 'division' THEN xxx_location_division
END
Allow an analysis.
#include <iostream> // not #include "iostream"
using namespace std; // in this case okay, but never do that in header files
class A
{
public:
void f() { cout<<"f()\n"; }
};
int main()
{
/*
// A a; //this works
A *a = new A(); //this doesn't
a.f(); // "f has not been declared"
*/ // below
// system("pause"); <-- Don't do this. It is non-portable code. I guess your
// teacher told you this?
// Better: In your IDE there is prolly an option somewhere
// to not close the terminal/console-window.
// If you compile on a CLI, it is not needed at all.
}
As a general advice:
0) Prefer automatic variables
int a;
MyClass myInstance;
std::vector<int> myIntVector;
1) If you need data sharing on big objects down
the call hierarchy, prefer references:
void foo (std::vector<int> const &input) {...}
void bar () {
std::vector<int> something;
...
foo (something);
}
2) If you need data sharing up the call hierarchy, prefer smart-pointers
that automatically manage deletion and reference counting.
3) If you need an array, use std::vector<> instead in most cases.
std::vector<> is ought to be the one default container.
4) I've yet to find a good reason for blank pointers.
-> Hard to get right exception safe
class Foo {
Foo () : a(new int[512]), b(new int[512]) {}
~Foo() {
delete [] b;
delete [] a;
}
};
-> if the second new[] fails, Foo leaks memory, because the
destructor is never called. Avoid this easily by using
one of the standard containers, like std::vector, or
smart-pointers.
As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.
You can use IOUtils.write(byte[] data, OutputStream output) from Apache Commons IO.
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);
I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.
I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:
def myfunc(a,b):
if (a>b): return a
else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)
Output:
[[7 4 5]
[7 6 9]]
Try the cex
argument:
?par
cex
For anyone out there using VS2015, I was getting this error too, and it turns out I hadn't added the library to the project...
Install-Package Xamarin.Android.Support.v7.AppCompat
Use the minDate option to set the minimum possible date. http://jqueryui.com/demos/datepicker/#option-minDate
Proximity Sensor Dial
*#*#7378423#*#*
1) Service Tests - (If present)
2) Proximity Switch
3) Test on sensor (Next to logo(top) of mobile)
4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery
OR
4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.
Technically, Its not any software solution, but hardware solution will work.
var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
d
stands for Declaration Files:
When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
The concept of declaration files is analogous to the concept of header file found in C/C++.
declare module arithmetics {
add(left: number, right: number): number;
subtract(left: number, right: number): number;
multiply(left: number, right: number): number;
divide(left: number, right: number): number;
}
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.
You can save the struct into a map by matching the struct Key
and Value
components to their fictive key and value parts on the map:
mapConfig := map[string]string{}
for _, v := range myconfig {
mapConfig[v.Key] = v.Value
}
Then using the golang comma ok idiom you can test for the key presence:
if v, ok := mapConfig["key1"]; ok {
fmt.Printf("%s exists", v)
}
create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.
You can call controller and get the page content and you can show that in your modal.
below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...
index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function loadme(){
//alert("loadig");
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
}
</script>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="contentBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
registration.html
--------------------
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {
border: 3px solid #f1f1f1;
font-family: Arial;
}
.container {
padding: 20px;
background-color: #f1f1f1;
width: 560px;
}
input[type=text], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type=checkbox] {
margin-top: 16px;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
<body>
<h2>CSS Newsletter</h2>
<form action="/action_page.php">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
</html>
I always use QString::setNum()
.
int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);
setNum()
is overloaded in many ways. See QString
class reference.
Based on Kenton's answer, a simpler yet working solution looks like:
message Foo {
oneof optional_baz { // "optional_" prefix here just serves as an indicator, not keyword in proto2
int32 baz = 1;
}
}
I have met the similiar issue. I would link to run Ant task fron Maven build and I got the issue. I have fixed it as bellow steps:
And it worked for me.