I've had success using TriadMixing and CIE94 to avoid similar colors. The following image uses input colors red, yellow, and white. See here.
The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the ALTER
query again.
Solution to iOS7 prior and iOS7 above
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import <UIKit/UIKit.h>
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define iOS7_0 @"7.0"
@interface UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel;
@end
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import "UILabel+DynamicHeight.h"
@implementation UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel{
NSAssert(self, @"UILabel was nil");
//Label text
NSString *aLabelTextString = [self text];
//Label font
UIFont *aLabelFont = [self font];
//Width of the Label
CGFloat aLabelSizeWidth = self.frame.size.width;
if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
//version < 7.0
return [aLabelTextString sizeWithFont:aLabelFont
constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
}
else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
//version >= 7.0
//Return the calculated size of the Label
return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : aLabelFont
}
context:nil].size;
}
return [self bounds].size;
}
@end
You can apply a centering to any View, including a Layout, by using the XML attribute android:layout_gravity". You probably want to give it the value "center".
You can find a reference of possible values for this option here: http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#attr_android:layout_gravity
Your curtime
variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t
values just fine.
You can also bind
to contextmenu
and return false
:
$('selector').bind('contextmenu', function(e){
e.preventDefault();
//code
return false;
});
Demo: http://jsfiddle.net/maniator/WS9S2/
Or you can make a quick plugin that does the same:
(function( $ ) {
$.fn.rightClick = function(method) {
$(this).bind('contextmenu rightclick', function(e){
e.preventDefault();
method();
return false;
});
};
})( jQuery );
Demo: http://jsfiddle.net/maniator/WS9S2/2/
Using .on(...)
jQuery >= 1.7:
$(document).on("contextmenu", "selector", function(e){
e.preventDefault();
//code
return false;
}); //does not have to use `document`, it could be any container element.
BTW, this also happens if you change the team of your target in Xcode and rebuild. Was quite puzzled to see that problem with an app that I had run on the device before. Took me a while to figure out… Might only happen the first time building to a device with a team, though.
This should work in most cases:
import os,sys
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))
I am doing this programmatically, and I simply moved my addSubview(tableView) to the bottom after adding all of my other subviews, and it solved my problem!
Not sure why this only appears on device and not my simulator, but either way at least there is a simple solution!
Component 1(child):
@Component(
selector:'com1'
)
export class Component1{
function1(){...}
}
Component 2(parent):
@Component(
selector:'com2',
template: `<com1 #component1></com1>`
)
export class Component2{
@ViewChild("component1") component1: Component1;
function2(){
this.component1.function1();
}
}
I hope my script help you.
<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>
My script
<script>
$(".mostrar-producto").mouseover(function(){
$(".producto").fadeIn();
});
$(".mostrar-producto").mouseleave(function(){
$(".producto").fadeOut();
});
</script>
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx
Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx
The variable is captured by the inline functions defined in the method. this
in the function will refer to another object. This way, you can make the function hold a reference to the this
in the outer scope.
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
Your document should not contain two divs with the same id. This is invalid HTML, and as a result, the underlying DOM API does not support it.
From the HTML standard:
id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.
You can either assign different ids to each div and select them both using $('#id1, #id2)
. Or assign the same class to both elements (.cls
for example), and use $('.cls')
to select them both.
How about something like:
<a href="\\DangerServer\Downloads\MyVirusArchive.exe"
type="application/octet-stream">Don't download this file!</a>
Here are some examples:
> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
weighted mean
> z$y <- rev(z$y)
> z
w x y mean
1 5 1 NA 1
2 6 2 3 2
3 7 3 2 3
4 8 4 1 4
>
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
w x y mean wmean
1 5 1 NA 1 1.000000
2 6 2 3 2 2.666667
3 7 3 2 3 2.333333
4 8 4 1 4 2.000000
I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.
After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:
CREATE TABLE "my_schema"."my_table" (...);
COPY "my_schema"."my_table" (...) FROM stdin;
This way using psql -f xxxxx
works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).
You need the Apache Commons Codec library 1.4 or above in your classpath. This library contains Base64 implementation.
Below code will be work for you :
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
application.applicationIconBadgeNumber = 0;
//self.textView.text = [userInfo description];
// We can determine whether an application is launched as a result of the user tapping the action
// button or whether the notification was delivered to the already-running application by examining
// the application state.
if (application.applicationState == UIApplicationStateActive) {
// Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}
Another simplest way to connect is through an OdbcConnection using App.config file like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
</appSettings>
MyDB.mdb is my database file and it is present in current primary application folder with main exe file.
if your mdf file has password then use like this
<appSettings>
<add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
</appSettings>
As of python 3.5.2, you can use:
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.
For how class_weight
works: It penalizes mistakes in samples of class[i]
with class_weight[i]
instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight
of class 1 relative to class 0, say {0:.1, 1:.9}.
If the class_weight
doesn't sum to 1, it will basically change the regularization parameter.
For how class_weight="auto"
works, you can have a look at this discussion.
In the dev version you can use class_weight="balanced"
, which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.
In my case where I wanted to have something like this:
I had to follow the same thing as suggested by @Mdlc but probably slightly simpler (targeting only >= 21):
//kotlin
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:"+realSize, Toast.LENGTH_LONG).show()
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
It works on landscape too:
Edit The above solution does not work correctly in multi-window mode where the usable rectangle is not smaller just due to the navigation bar but also because of custom window size. One thing that I noticed is that in multi-window the navigation bar is not hovering over the app so even with no changes to DecorView padding we have the correct behaviour:
Note the difference between how navigation bar is hovering over the bottom of the app in these to scenarios. Fortunately, this is easy to fix. We can check if app is multi window. The code below also includes the part to calculate and adjust the position of toolbar (full solution: https://stackoverflow.com/a/14213035/477790)
// kotlin
// Let the window flow into where window decorations are
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
// calculate where the bottom of the page should end up, considering the navigation bar (back buttons, ...)
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val realSize = Point()
windowManager.defaultDisplay.getRealSize(realSize);
val usableRect = Rect()
windowManager.defaultDisplay.getRectSize(usableRect)
Toast.makeText(this, "Usable Screen: " + usableRect + " real:" + realSize, Toast.LENGTH_LONG).show()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !isInMultiWindowMode) {
window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
// move toolbar/appbar further down to where it should be and not to overlap with status bar
val layoutParams = ConstraintLayout.LayoutParams(appBarLayout.layoutParams as ConstraintLayout.LayoutParams)
layoutParams.topMargin = getSystemSize(Constants.statusBarHeightKey)
appBarLayout.layoutParams = layoutParams
}
Result on Samsung popup mode:
This is a solution along the lines of CMS's, but solves a few key issues for me:
var delay = (function() {
var timer = {}
, values = {}
return function(el) {
var id = el.form.id + '.' + el.name
return {
enqueue: function(ms, cb) {
if (values[id] == el.value) return
if (!el.value) return
var original = values[id] = el.value
clearTimeout(timer[id])
timer[id] = setTimeout(function() {
if (original != el.value) return // solves race condition
cb.apply(el)
}, ms)
}
}
}
}())
Usage:
signup.key.addEventListener('keyup', function() {
delay(this).enqueue(300, function() {
console.log(this.value)
})
})
The code is written in a style I enjoy, you may need to add a bunch of semicolons.
Things to keep in mind:
this
works as expected (like in the example).setTimeout
.The solution I use adds another level of complexity, allowing you to cancel execution, for example, but this is a good base to build on.
Here's @SLaks answer, but in pure ES6 JavaScript.
var start = new Date,_x000D_
$timer = document.querySelector('.Timer');_x000D_
_x000D_
setInterval(function(timestamp) {_x000D_
$timer.innerText = `${timestamp - start) / 1000} Seconds`;_x000D_
}, 1000);
_x000D_
Based on Chris's comment
CSS
.amazon-rating {
width: 55px;
height: 12px;
overflow: hidden;
}
.rating-stars {
left: -18px;
top: -102px;
position: relative;
}
HAML
.amazon-rating
%iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
Normally i use a class for this:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray
if you really need an array:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Note that i've presumed that the first column is a string
and the second an integer
. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY
methods.
Some options without REGEXMATCH
, since you might want to be case insensitive and not want say blast
or ablative
to trigger a YES
. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:
First very similar to @user1598086's answer:
=FIND("bla",A1)
Is case sensitive but returns #VALUE! rather than NO
and a number rather than YES
(both of which can however be changed to NO/YES respectively).
=SEARCH("bla",A1)
Case insensitive, so treats Black
and black
equally. Returns as above.
The former (for the latter equivalent) to indicate whether bla
present after the first three characters in A1:
=FIND("bla",A1,4)
Returns a number for blazer, black
but #VALUE!
for blazer, blue
.
To find Bla
only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):
=SEARCH(" Bla ",A1)
Since the return in all cases above is either a number ("found", so YES
preferred) or #VALUE!
we can use ISERROR to test for #VALUE!
within an IF formula, for instance taking the first example above:
=if(iserror(FIND("bla",A1)),"NO","YES")
Longer than the regexmatch
but the components are easily adjustable.
There are three ways.
The first is to put the script tag on the bottom of the page:
<body>
<!--Body content-->
<script type="text/javascript">
alert('<%: TempData["Resultat"]%>');
</script>
</body>
The second way is to create an onload event:
<head>
<script type="text/javascript">
window.onload = function(){//window.addEventListener('load',function(){...}); (for Netscape) and window.attachEvent('onload',function(){...}); (for IE and Opera) also work
alert('<%: TempData["Resultat"]%>');
}
</script>
</head>
It will execute a function when the window loads.
Finally, the third way is to create a readystatechange
event and check the current document.readystate:
<head>
<script type="text/javascript">
document.onreadystatechange = function(){//window.addEventListener('readystatechange',function(){...}); (for Netscape) and window.attachEvent('onreadystatechange',function(){...}); (for IE and Opera) also work
if(document.readyState=='loaded' || document.readyState=='complete')
alert('<%: TempData["Resultat"]%>');
}
</script>
</head>
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
The value of the length property must be greater than or equal to name atribute length, else throwing an error.
Works
@Column(name = "typ e", length = 4, unique = true)
private String type;
Not works, type.length: 4 != length property: 3
@Column(name = "type", length = 3, unique = true)
private String type;
If you don't feel like iterating, try FBFriendModel.find({ id:333 }).remove( callback );
or FBFriendModel.find({ id:333 }).remove().exec();
mongoose.model.find
returns a Query, which has a remove
function.
Update for Mongoose v5.5.3 - remove()
is now deprecated. Use deleteOne()
, deleteMany()
or findOneAndDelete() instead.
Something like this:
ARGV.each do|a|
puts "Argument: #{a}"
end
then
$ ./test.rb "test1 test2"
or
v1 = ARGV[0]
v2 = ARGV[1]
puts v1 #prints test1
puts v2 #prints test2
Like this ?
<script>
var meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'X-UA-Compatible');
meta.setAttribute('content', 'IE=Edge');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>
You can have an onclick event in the svg itself, I do this all the time in my work. make a rect over the space of your svg, (so define it last, remember svg uses the painters model)
rect.btn {
stroke:#fff;
fill:#fff;
fill-opacity:0;
stroke-opacity:0;
}
then as an attribute to the rect add the onclick (this can be done with js or jquery as well).
<div>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<circle ... //your img svg
<rect class="btn" x="0" y="0" width="10" height="10" onclick="alert('click!')" />
</g>
</svg>
</div>
this will work in most modern browsers, http://caniuse.com/svg ...though if you need cross compatability, you can implement Google Chrome Frame. http://www.google.com/chromeframe
>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>>
Subtle point here...
There is an implicit typecast for i+j
when j
is a double and i
is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j
where i
is an integer and j
is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j
to (int)
in this case for clarity.
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
You can merge, or you can apply individual commits across branches by using git cherry-pick.
Run this:
curl http://169.254.169.254/latest/meta-data/
You will be able to see different types of attributes which are provided by aws.
You could leverage the html-to-react
npm module.
Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.
You can do this using the head and tail commands:
head -n <num> | tail -n <lines to print>
where num is 1e6 + the number of lines you want to print.
Put the font-family
declaration into a body
selector:
body {
font-family: Algerian;
}
All the elements on your page will inherit this font-family then (unless, of course you override it later).
A solution that works for me (July 2017), is to utilize ESLint. As everybody knows, you can use the linter in multiple ways, globally or locally. I use it locally and with the google style guide. They way I set it up is as follow...
cd to your working directory
npm init
npm install --save-dev eslint
node_modules/.bin/eslint --init
I use google style and json config file
Now you will have a .eslintrc.json
file the root of your working directory. You can open that file and modify as you please utilizing the eslint rules. Next cmd+,
to open vscode
system preferences. In the search bar type eslint
and look for "eslint.autoFixOnSave": false
. Copy the setting and pasted in the user settings file and change false
to true
. Hope this can help someone utilizing vscode.
What fixed it for me that I haven't seen mentioned so far - if you have multiple 'flavors', make sure the currently selected 'build variant' matches the flavor for the layout file you're trying to view.
Check Collections#sort
method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList
method.
private List<String> teamsName = new ArrayList<String>();
List<String> subList = teamsName.subList(1, teamsName.size());
Collections.sort(subList);
There is a discussion on GitHub because of a question similar to this one: https://gist.github.com/1398757
You can use other projects for guidance, search in GitHub for:
And finally, in a book (http://shop.oreilly.com/product/0636920025344.do) suggests this structure:
+-- index.html
+-- js/
¦ +-- main.js
¦ +-- models/
¦ +-- views/
¦ +-- collections/
¦ +-- templates/
¦ +-- libs/
¦ +-- backbone/
¦ +-- underscore/
¦ +-- ...
+-- css/
+-- ...
You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);
Why not create an extension method? That's more readable.
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();
foreach(string ext in extensions)
{
files = files.Concat(dir.GetFiles(ext));
}
return files;
}
EDIT: a more efficient version:
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Usage:
DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir");
dInfo.GetFilesByExtensions(".jpg",".exe",".gif");
Configuration Options:
$(document).ready(function () {
$("#companiesTable").dataTable({
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"bAutoWidth": false, // Disable the auto width calculation
"aoColumns": [
{ "sWidth": "30%" }, // 1st column width
{ "sWidth": "30%" }, // 2nd column width
{ "sWidth": "40%" } // 3rd column width and so on
]
});
});
Specify the css for the table:
table.display {
margin: 0 auto;
width: 100%;
clear: both;
border-collapse: collapse;
table-layout: fixed; // add this
word-wrap:break-word; // add this
}
HTML:
<table id="companiesTable" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<% for(Company c: DataRepository.GetCompanies()){ %>
<tr>
<td><%=c.getName()%></td>
<td><%=c.getAddress()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>
</tbody>
</table>
It works for me!
As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.
using System.Management;
...
string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
You need to use the target
selector.
Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/
For curl
, how about using the -d
switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"
?
repeated = str + str + str;
Sometimes simple is best. Everyone reading the code can see what's happening.
And the compiler will do the fancy stuff with StringBuilder
behind the scenes for you.
This question already has an answer, but I just want to add that in Windows there is Windows Subsystem for Linux WSL.
So for example if you want to check if you have service named Elasicsearch that is in status running you can do something like the snippet below in powershell
net start | grep Elasticsearch
For C++ it depends on what you are doing. OK, it is stupid code but imagine
class myTimeEatingClass { public: //constructor myTimeEatingClass() { sleep(2000); ms_usedTime+=2; } ~myTimeEatingClass() { sleep(3000); ms_usedTime+=3; } const unsigned int getTime() const { return ms_usedTime; } static unsigned int ms_usedTime; };
myTimeEatingClass::ms_CreationTime=0;
myFunc()
{
for (int counter = 0; counter <= 10; counter++) {
myTimeEatingClass timeEater();
//do something
}
cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;
}
myOtherFunc()
{
myTimeEatingClass timeEater();
for (int counter = 0; counter <= 10; counter++) {
//do something
}
cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;
}
You will wait 55 seconds until you get the output of myFunc. Just because each loop contructor and destructor together need 5 seconds to finish.
You will need 5 seconds until you get the output of myOtherFunc.
Of course, this is a crazy example.
But it illustrates that it might become a performance issue when each loop the same construction is done when the constructor and / or destructor needs some time.
I had the same problem to show an user detail from my application.
You can do this:
<Link to={'/ideas/'+this.props.testvalue }>Create Idea</Link>
or
<Link to="ideas/hello">Create Idea</Link>
and
<Route name="ideas/:value" handler={CreateIdeaView} />
to get this via this.props.match.params.value
at your CreateIdeaView class.
You can see this video that helped me a lot: https://www.youtube.com/watch?v=ZBxMljq9GSE
Its very simple..Just type below line
npm view < package-name > version
** Example **
npm view redux version
I have version 7.2.0 of redux
I discovered that if I set up the two-step authentication in github, Eclipse isn't able to connect to Github - which makes sense because the two-step authentication in github requires you to input a number from an SMS (and Eclipse wouldn't have this information).
If this is your scenario, you might consider de-activating your two-step authentication in github, and see if that helps.
If you're getting something like getElementById call returns null
, it's probably because the function is running, but the ID hasn't had time to load in the DOM.
Try using Will's answer (towards the top) with a delay. Example:
angular.module('MyApp', [])
.controller('MyCtrl', [function() {
$scope.sleep = (time) => {
return new Promise((resolve) => setTimeout(resolve, time));
};
angular.element(document).ready(function () {
$scope.sleep(500).then(() => {
//code to run here after the delay
});
});
}]);
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
%PROGRAMFILES%\Git\etc
profile
HOME="c:\location_were_you_want_gitconfig"
Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.
The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.
#box {
background-color: #000;
position: relative;
padding: 10px;
width: 220px;
height:30px;
}
Bourne shell (sh) uses PATH to locate in source <file>
. If the file you are trying to source is not in your path, you get the error 'file not found'.
Try:
source ./<filename>
You can use the following to get the previous URL.
var oldURL = document.referrer;
alert(oldURL);
Is there a js listener for when a user scrolls in a certain textbox that can be used?
DOM L3 UI Events spec gave the initial definition but is considered obsolete.
To add a single handler you can do:
let isTicking;
const debounce = (callback, evt) => {
if (isTicking) return;
requestAnimationFrame(() => {
callback(evt);
isTicking = false;
});
isTicking = true;
};
const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => debounce(handleScroll, evt);
For multiple handlers or, if preferable for style reasons, you may use addEventListener
as opposed to assigning your handler to onscroll
as shown above.
If using something like _.debounce
from lodash you could probably get away with:
const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));
Review browser compatibility and be sure to test on some actual devices before calling it done.
Edited: optimized code.
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
To get Bitmap from resources:
Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
Copy-pasted from a recipe written by "Adrián Santalla" on androidcookbook.com: https://www.androidcookbook.com/Recipe.seam?recipeId=3307
1. Create an XML file that represents the button states
Create an xml into drawable called 'button.xml' to name the button states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/button_disabled" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/button_pressed" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/button_focused" />
<item
android:state_enabled="true"
android:drawable="@drawable/button_enabled" />
</selector>
2. Create an XML file that represents each button state
Create one xml file for each of the four button states. All of them should be under drawables folder. Let's follow the names set in the button.xml file.
button_enabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#00CCFF"
android:centerColor="#0000CC"
android:endColor="#00CCFF"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_focused.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F7D358"
android:centerColor="#DF7401"
android:endColor="#F7D358"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_pressed.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#0000CC"
android:centerColor="#00CCFF"
android:endColor="#0000CC"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_disabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F2F2F2"
android:centerColor="#A4A4A4"
android:endColor="#F2F2F2"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
3. Create an XML file that represents the button style
Once you have created the files mentioned above, it's time to create your application button style. Now, you need to create a new XML file, called styles.xml (if you don't have it yet) where you can include more custom styles, into de values directory.
This file will contain the new button style of your application. You need to set your new button style features in it. Note that one of those features, the background of your new style, should be set with a reference to the button (button.xml) drawable that was created in the first step. To refer to the new button style we use the name attribute.
The example below show the content of the styles.xml file:
<resources>
<style name="button" parent="@android:style/Widget.Button">
<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">#FFFFFFFF</item>
<item name="android:shadowColor">#FF000000</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">-1</item>
<item name="android:shadowRadius">0.2</item>
<item name="android:textSize">16dip</item>
<item name="android:textStyle">bold</item>
<item name="android:background">@drawable/button</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>
</resources>
4. Create an XML with your own custom application theme
Finally, you need to override the default Android button style. For that, you need to create a new XML file, called themes.xml (if you don't have it yet), into the values directory and override the default Android button style.
The example below show the content of the themes.xml:
<resources>
<style name="YourApplicationTheme" parent="android:style/Theme.NoTitleBar">
<item name="android:buttonStyle">@style/button</item>
</style>
</resources>
Hope you guys can have the same luck as I had with this, when I was looking for custom buttons. Enjoy.
The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.
Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.
So this is not possible. If you want to respond to https links, then you need an ssl certificate.
In Java 6, there is a method doing exactly what you want:
private static final byte[] CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")
Alternatively you could use Google Guava:
import com.google.common.io.BaseEncoding;
private static final byte[] CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());
The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.
Right CLick on res folder -> New Android Resource Directory - select resource type raw -> ok and move your file to this folder
Even if its showing unresolved reference: raw in the Android Studio, it does still run. when I did the rebuild it didn't show any error during the build. just put the right path like R.raw.myrawfile and run it, the app will run.
if u want the red mark on the code to go away you probably have to restart (do invalidate cache and restart)
I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S
:
# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80 is a NameVirtualHost
default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
[...]
11.22.33.44:443 is a NameVirtualHost
default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80 hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001 hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000 hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443 hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001 hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000 hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK
Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).
Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default
on line 33 and /etc/apache2/sites-enabled/default-ssl
on line 163. Likewise *:30000
is listed in 2 places. The solution (in my case) was simply to delete one of the entries.
PHP device detection from 51Degrees.com does exactly what you want - detects mobile devices and various properties associated with detected devices. It is simple to use and requires no maintenance. Set up is done in 4 easy steps:
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
if ($_51d['IsMobile'])
{
//Start coding for a mobile device here.
}
51Degrees device detector does not use regular expressions for detections. Only important parts of HTTP headers are used to match devices. Which makes this solution the fastest (5 000 000 detections per second on mediocre hardware) and most accurate (99.97% accuracy) as hundreds of new devices are added to the database weekly (Supported device types include consoles, smart TVs, e-readers, tablets and more).
Software is open source distributed under Mozilla Public License 2 and compatible with commercial and open source projects. As a bonus 51Degrees solution also contains a complementary PHP image optimiser that can automatically resize images for mobile devices.
By default 51Degrees PHP device detector uses Lite data file which is free and contains over 30000 devices and 50 properties for each device. Lite file is updated once every 3 month. If you want to have a higher level of details about requesting mobile devices, then Premium and Enterprise data files are available. Premium contains well over 70000 devices and 100 properties for each device with weekly updates. Enterprise is updated daily and contains over 150000 devices with 150 properties for each.
Use checked
to get the value. During onChange
, checked
will be true
and it will be a type of boolean
.
Hope this helps!
class A extends React.Component {_x000D_
constructor() {_x000D_
super()_x000D_
this.handleCheckBox = this.handleCheckBox.bind(this)_x000D_
this.state = {_x000D_
checked: false_x000D_
}_x000D_
}_x000D_
_x000D_
handleCheckBox(e) {_x000D_
this.setState({_x000D_
checked: e.target.checked_x000D_
})_x000D_
}_x000D_
_x000D_
render(){_x000D_
return <input type="checkbox" onChange={this.handleCheckBox} checked={this.state.checked} />_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<A/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
I found it easier in following links:
In
http://www.remondo.net/visitor-pattern-example-csharp/ I found an example that shows an mock example that shows what is benefit of visitor pattern. Here you have different container classes for Pill
:
namespace DesignPatterns
{
public class BlisterPack
{
// Pairs so x2
public int TabletPairs { get; set; }
}
public class Bottle
{
// Unsigned
public uint Items { get; set; }
}
public class Jar
{
// Signed
public int Pieces { get; set; }
}
}
As you see in above, You BilsterPack
contain pairs of Pills' so you need to multiply number of pair's by 2. Also you may notice that Bottle
use unit
which is different datatype and need to be cast.
So in main method you may calculate pill count using following code:
foreach (var item in packageList)
{
if (item.GetType() == typeof (BlisterPack))
{
pillCount += ((BlisterPack) item).TabletPairs * 2;
}
else if (item.GetType() == typeof (Bottle))
{
pillCount += (int) ((Bottle) item).Items;
}
else if (item.GetType() == typeof (Jar))
{
pillCount += ((Jar) item).Pieces;
}
}
Notice that above code violate Single Responsibility Principle
. That means you must change main method code if you add new type of container. Also making switch longer is bad practice.
So by introducing following code:
public class PillCountVisitor : IVisitor
{
public int Count { get; private set; }
#region IVisitor Members
public void Visit(BlisterPack blisterPack)
{
Count += blisterPack.TabletPairs * 2;
}
public void Visit(Bottle bottle)
{
Count += (int)bottle.Items;
}
public void Visit(Jar jar)
{
Count += jar.Pieces;
}
#endregion
}
You moved responsibility of counting number of Pill
s to class called PillCountVisitor
(And we removed switch case statement). That mean's whenever you need to add new type of pill container you should change only PillCountVisitor
class. Also notice IVisitor
interface is general for using in another scenarios.
By adding Accept method to pill container class:
public class BlisterPack : IAcceptor
{
public int TabletPairs { get; set; }
#region IAcceptor Members
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
#endregion
}
we allow visitor to visit pill container classes.
At the end we calculate pill count using following code:
var visitor = new PillCountVisitor();
foreach (IAcceptor item in packageList)
{
item.Accept(visitor);
}
That mean's: Every pill container allow the PillCountVisitor
visitor to see their pills count. He know how to count your pill's.
At the visitor.Count
has the value of pills.
In http://butunclebob.com/ArticleS.UncleBob.IuseVisitor you see real scenario in which you can not use polymorphism (the answer) to follow Single Responsibility Principle. In fact in:
public class HourlyEmployee extends Employee {
public String reportQtdHoursAndPay() {
//generate the line for this hourly employee
}
}
the reportQtdHoursAndPay
method is for reporting and representation and this violate the Single Responsibility Principle. So it is better to use visitor pattern to overcome the problem.
https://github.com/HardySimpson/docker-cleanup
A tiny all-in-one shell, which removes:
Intend to run as a crontab job
<none>:<none>
images2>/dev/null
or notWhat is Predicate Delegate?
1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework.
2) It is being used with lambda expression (=>). It takes generic type as an argument.
3) It allows a predicate function to be defined and passed as a parameter to another function.
4) It is a special case of a Func
, in that it takes only a single parameter and always returns a bool.
In C# namespace:
namespace System
{
public delegate bool Predicate<in T>(T obj);
}
It is defined in the System namespace.
Where should we use Predicate Delegate?
We should use Predicate Delegate in the following cases:
1) For searching items in a generic collection. e.g.
var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
2) Basic example that shortens the code and returns true or false:
Predicate<int> isValueOne = x => x == 1;
now, Call above predicate:
Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
3) An anonymous method can also be assigned to a Predicate delegate type as below:
Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
bool result = isUpper("Hello Chap!!");
Any best practices about predicates?
Use Func, Lambda Expressions and Delegates instead of Predicates.
$(':text').attr("disabled", "disabled");
sets all textbox to disabled mode.
You can do in another way like giving each textbox id. By doing this code weight will be more and performance issue will be there.
So better have $(':text').attr("disabled", "disabled");
approach.
Read your reference more carefully:
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
. . .
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
You can add it like this
header('Location: http://linkhere.com/'.$url_endpoint);
There's an open issue for this in Google's IssueTracker.
The potential solutions given in the issue (as of the date of this post) are:
As described here, you can also attempt the command
npm cache clean
That fixed it for me, after the other steps had not fully yielded results (other than updating everything).
This works pretty well with using optional matches (prints after href=
) and gets the link only. Tested on http://pythex.org/
(?:href=['"])([:/.A-z?<_&\s=>0-9;-]+)
Oputput:
Match 1. /wiki/Main_Page
Match 2. /wiki/Portal:Contents
Match 3. /wiki/Portal:Featured_content
Match 4. /wiki/Portal:Current_events
Match 5. /wiki/Special:Random
Match 6. //donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=en
The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined
and not an empty string unlike some of the other answers here.
function getCookie(name) {
return (document.cookie.match('(^|;) *'+name+'=([^;]*)')||[])[2];
}
The above worked fine for me on all browsers I checked, but as mentioned by @vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.
function getCookie(name) {
return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
}
See http://www.eyecon.ro/bootstrap-datepicker/
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
try this
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
var this_input=$(this);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.attr('checked1','11')_x000D_
} else {_x000D_
this_input.attr('checked1','22')_x000D_
}_x000D_
$('.radio-button').prop('checked', false);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.prop('checked', false);_x000D_
this_input.attr('checked1','22')_x000D_
} else {_x000D_
this_input.prop('checked', true);_x000D_
this_input.attr('checked1','11')_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
I was facing this issue in ionic and tried many solutions but solved this by running this.
For MAC: node --max-old-space-size=4096 /usr/local/bin/ionic cordova build android --prod
For Windows: node --max-old-space-size=4096 /Users/{your user}/AppData/Roaming/npm/node_modules/ionic/bin/ionic cordova build windows --prod
If you can use jQuery, you can try BgSwitcher plugin to switch the background-image with effects, it's very easy to use.
For example :
$('.bgSwitch').bgswitcher({
images: ["style/img/bg0.jpg","style/img/bg1.jpg","style/img/bg2.jpg"],
effect: "fade",
interval: 10000
});
And add your own effect, see adding an effect types
Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet()
Dim ws As Worksheet
Dim pw As String
pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then
Exit Sub
ElseIf pw = NullString Then
Exit Sub
ElseIf pw = 123456 Then
For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next
End If
End Sub
In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:
Use same (any) eventing you like.
window.on('resize', resize);
Then assuming you have svg & force variables:
var svg = /* D3 Code */;
var force = /* D3 Code */;
function resize(e){
// get width/height with container selector (body also works)
// or use other method of calculating desired values
var width = $('#myselector').width();
var height = $('#myselector').height();
// set attrs and 'resume' force
svg.attr('width', width);
svg.attr('height', height);
force.size([width, height]).resume();
}
In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?
Cheers, g
The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.
I can finally copy paste between MacVim on my terminal and the rest of my applications.
Following the useful comments, I've completely rebuilt the date formatter. Usage is supposed to:
If you consider this code useful, I may publish the source and a JAR in github.
// The problem - not UTC
Date.toString()
"Tue Jul 03 14:54:24 IDT 2012"
// ISO format, now
PrettyDate.now()
"2012-07-03T11:54:24.256 UTC"
// ISO format, specific date
PrettyDate.toString(new Date())
"2012-07-03T11:54:24.256 UTC"
// Legacy format, specific date
PrettyDate.toLegacyString(new Date())
"Tue Jul 03 11:54:24 UTC 2012"
// ISO, specific date and time zone
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST")
"1969-07-20 03:17:40 CDT"
// Specific format and date
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
"1969-07-20"
// ISO, specific date
PrettyDate.toString(moonLandingDate)
"1969-07-20T20:17:40.234 UTC"
// Legacy, specific date
PrettyDate.toLegacyString(moonLandingDate)
"Wed Jul 20 08:17:40 UTC 1969"
(This code is also the subject of a question on Code Review stackexchange)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Formats dates to sortable UTC strings in compliance with ISO-8601.
*
* @author Adam Matan <[email protected]>
* @see http://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string/11294308
*/
public class PrettyDate {
public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy";
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT);
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
static {
legacyFormatter.setTimeZone(utc);
isoFormatter.setTimeZone(utc);
}
/**
* Formats the current time in a sortable ISO-8601 UTC format.
*
* @return Current time in ISO-8601 format, e.g. :
* "2012-07-03T07:59:09.206 UTC"
*/
public static String now() {
return PrettyDate.toString(new Date());
}
/**
* Formats a given date in a sortable ISO-8601 UTC format.
*
* <pre>
* <code>
* final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
* moonLandingCalendar.set(1969, 7, 20, 20, 18, 0);
* final Date moonLandingDate = moonLandingCalendar.getTime();
* System.out.println("UTCDate.toString moon: " + PrettyDate.toString(moonLandingDate));
* >>> UTCDate.toString moon: 1969-08-20T20:18:00.209 UTC
* </code>
* </pre>
*
* @param date
* Valid Date object.
* @return The given date in ISO-8601 format.
*
*/
public static String toString(final Date date) {
return isoFormatter.format(date);
}
/**
* Formats a given date in the standard Java Date.toString(), using UTC
* instead of locale time zone.
*
* <pre>
* <code>
* System.out.println(UTCDate.toLegacyString(new Date()));
* >>> "Tue Jul 03 07:33:57 UTC 2012"
* </code>
* </pre>
*
* @param date
* Valid Date object.
* @return The given date in Legacy Date.toString() format, e.g.
* "Tue Jul 03 09:34:17 IDT 2012"
*/
public static String toLegacyString(final Date date) {
return legacyFormatter.format(date);
}
/**
* Formats a date in any given format at UTC.
*
* <pre>
* <code>
* final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
* moonLandingCalendar.set(1969, 7, 20, 20, 17, 40);
* final Date moonLandingDate = moonLandingCalendar.getTime();
* PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
* >>> "1969-08-20"
* </code>
* </pre>
*
*
* @param date
* Valid Date object.
* @param format
* String representation of the format, e.g. "yyyy-MM-dd"
* @return The given date formatted in the given format.
*/
public static String toString(final Date date, final String format) {
return toString(date, format, "UTC");
}
/**
* Formats a date at any given format String, at any given Timezone String.
*
*
* @param date
* Valid Date object
* @param format
* String representation of the format, e.g. "yyyy-MM-dd HH:mm"
* @param timezone
* String representation of the time zone, e.g. "CST"
* @return The formatted date in the given time zone.
*/
public static String toString(final Date date, final String format, final String timezone) {
final TimeZone tz = TimeZone.getTimeZone(timezone);
final SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.setTimeZone(tz);
return formatter.format(date);
}
}
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
Html:
<div id="example">
<button v-on:click="multiple">Multiple</button>
</div>
JS:
var vm = new Vue({
el: '#example',
data: {
name: 'Vue.js'
},
// define methods under the `methods` object
methods: {
multiple: function (event) {
this.first()
this.second()
}
first: function (event) {
//yourstuff
}
second: function (event) {
//yourstuff
}
}
})
vm.multiple()
Initialize it first
MainActivity mActivity= new MainActivity();
Then you can continue
mActivity.startChronometer();
There's a way to do it without branching, but it's not very pretty.
sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
http://graphics.stanford.edu/~seander/bithacks.html
Lots of other interesting, overly-clever stuff on that page, too...
There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.
Important:
Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).
Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.
Ergo:
on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.
on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.
Examples:
Note:
The following examples convert to and from UTF-8 encoded strings:
To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode
for [Text.Encoding]::UTF8
Convert TO Base64:
PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==
Convert FROM Base64:
PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead
You should probably clone your repository first.
Remove your file from all branches history:
git filter-branch --tree-filter 'rm -f filename.orig' -- --all
Remove your file just from the current branch:
git filter-branch --tree-filter 'rm -f filename.orig' -- --HEAD
Lastly you should run to remove empty commits:
git filter-branch -f --prune-empty -- --all
Following the exceedingly simple method from Andralor here fixed the issue for me: https://github.com/fancyapps/fancyBox/issues/766
Essentially, call the iframe again onUpdate:
$('a.js-fancybox-iframe').fancybox({
type: 'iframe',
scrolling : 'visible',
autoHeight: true,
onUpdate: function(){
$("iframe.fancybox-iframe");
}
});
If you have a toggle switch that toggles between list to grid, don't forget to call recyclerView.removeItemDecoration()
before setting any new Item decoration. If not then the new calculations for the spacing would be incorrect.
Something like this.
recyclerView.removeItemDecoration(gridItemDecorator)
recyclerView.removeItemDecoration(listItemDecorator)
if (showAsList){
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.addItemDecoration(listItemDecorator)
}
else{
recyclerView.layoutManager = GridLayoutManager(this, spanCount)
recyclerView.addItemDecoration(gridItemDecorator)
}
On thing to remember here is that the default param must be the last param in the function definition.
Following code will not compile:
void fun(int first, int second = 10, int third);
Following code will compile:
void fun(int first, int second, int third = 10);
You can resolve the issue by forcing the collation used in a query to be a particular collation, e.g. SQL_Latin1_General_CP1_CI_AS
or DATABASE_DEFAULT
. For example:
SELECT MyColumn
FROM FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE SQL_Latin1_General_CP1_CI_AS =
b.YourID COLLATE SQL_Latin1_General_CP1_CI_AS
In the above query, a.MyID and b.YourID would be columns with a text-based data type. Using COLLATE
will force the query to ignore the default collation on the database and instead use the provided collation, in this case SQL_Latin1_General_CP1_CI_AS
.
Basically what's going on here is that each database has its own collation which "provides sorting rules, case, and accent sensitivity properties for your data" (from http://technet.microsoft.com/en-us/library/ms143726.aspx) and applies to columns with textual data types, e.g. VARCHAR
, CHAR
, NVARCHAR
, etc. When two databases have differing collations, you cannot compare text columns with an operator like equals (=) without addressing the conflict between the two disparate collations.
I was able to implement Luca's solution, but I had to make a few changes for it to work. My goal was to use D3.js with a Web Browser control for a Windows Forms Application (targeting .NET 2.0). It is working for me now. I hope this can help someone else.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
namespace ClientUI
{
static class Program
{
static Mutex mutex = new System.Threading.Mutex(false, "jMutex");
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
{
// Another application instance is running
return;
}
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
int ie_emulation = 11999;
try
{
string tmp = Properties.Settings.Default.ie_emulation;
ie_emulation = int.Parse(tmp);
}
catch { }
SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);
Application.Run(new MainForm());
}
finally
{
mutex.ReleaseMutex();
}
}
private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
{
RegistryKey Regkey = null;
try
{
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
// If the path is not correct or
// if user doesn't have privileges to access the registry
if (Regkey == null)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
// Check if key is already present
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
Regkey.Close();
return;
}
// If key is not present or different from desired, add/modify the key , key value
Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);
// Check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName));
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
}
else
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is " + ieval);
}
}
catch (Exception ex)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
}
finally
{
//Close the Registry
if (Regkey != null) Regkey.Close();
}
}
}
}
Also, I added a string (ie_emulation) to the project's settings with the value of 11999. This value seems to be working for IE11(11.0.15).
Next, I had to change the permission for my application to allow access to the registry. This can be done by adding a new item to your project (using VS2012). Under the General Items, select Application Manifest File. Change the level from asInvoker to requireAdministrator (as shown below).
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
If someone reading this is trying to use D3.js with a webbrowser control, you may have to modify the JSON data to be stored within a variable inside your HTML page because D3.json uses XmlHttpRequest (easier to use with a webserver). After those changes and the above, my windows forms are able to load local HTML files that call D3.
Pretty much what others said, but using "~/.bash_profile" and step by step (for beginners):
cd ~ && mkdir installed-packages
sudo yum install -y wget
cd ~/installed-packages
wget http://www-eu.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
tar -xvf apache-maven-3.5.0-bin.tar.gz
ln -s ~/installed-packages/apache-maven-3.5.0 /usr/local/apache-maven
~/.bash_profile
(This is where environment variables are commonly stored):
vi ~/.bash_profile
MVN_HOME=/usr/local/apache-maven
(do this before PATH variable is defined)
vi
tool: Press i
key to enable insert mode):$MVN_HOME:$MVN_HOME/bin
vi
tool: Press esc
key to exit insert mode and :wq!
to save and quit file)source ~/.bash_profile
mvn --help
for strings in panda take pd.isnull:
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
the function as feature extraction for NLTK
def act_features(atext):
features = {}
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
if word not in default_stopwords:
features['cont({})'.format(word.lower())]=True
return features
You will need to put the try/except inside the most innerloop where the error may occur, i.e.
for i in something:
for j in somethingelse:
for k in whatever:
try:
something_complex(i, j, k)
except Exception, e:
print e
try:
something_less_complex(i, j)
except Exception, e:
print e
... and so on
In other words, you will need to wrap statements that may fail in try/except as specific as possible, in the most inner-loop as possible.
You need to set index=False
in to_excel
in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
Updated answer, nearly 5 years later:
The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e. content://
rather than file://
. A better solution is to simply use context.getContentResolver().openInputStream(intent.getData())
, as that will return an InputStream that you can handle as you choose.
For example, BitmapFactory.decodeStream()
works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.
However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.
Original answer:
The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}
After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.
To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the columnIndex
code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.
You can use console consumer to view messages produced on some topic:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
It's possible to use a function, which evaluates the OR logic and returns a single value.
@echo off
set var1=3
set var2=5
call :logic_or orResult "'%var1%'=='4'" "'%var2%'=='5'"
if %orResult%==1 (
echo At least one expression is true
) ELSE echo All expressions are false
exit /b
:logic_or <resultVar> expression1 [[expr2] ... expr-n]
SETLOCAL
set "logic_or.result=0"
set "logic_or.resultVar=%~1"
:logic_or_loop
if "%~2"=="" goto :logic_or_end
if %~2 set "logic_or.result=1"
SHIFT
goto :logic_or_loop
:logic_or_end
(
ENDLOCAL
set "%logic_or.resultVar%=%logic_or.result%"
exit /b
)
I had this problem for a different reason. I went to the maven repository https://mvnrepository.com looking for the latest version of spring core, which at the time was 5.0.0.M3/ The repository showed me this entry for my pom.xml:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.0.M3</version>
</dependency>
Naive fool that I am, I assumed that the comment was telling me that the jar is located in the default repository.
However, after a lot of head-banging, I saw a note just below the xml saying "Note: this artifact it located at Alfresco Public repository (https://artifacts.alfresco.com/nexus/content/repositories/public/)"
So the comment in the XML is completely misleading. The jar is located in another archive, which was why Maven couldn't find it!
Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...
So the solution was quite simple - I've just done this grant:
grant userB to userA;
That's all folks ;-)
Another requirement is that the object has to be owned by user userA before altering it...
Put it inside an UIImageView
let logo = UIImage(named: "logo.png")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
(1..4).each { |i|
a = 9 if i==3
puts a
}
#nil
#nil
#9
#nil
for i in 1..4
a = 9 if i==3
puts a
end
#nil
#nil
#9
#9
In 'for' loop, local variable is still lives after each loop. In 'each' loop, local variable refreshes after each loop.
Just change "rc01" in first and last line inside dependencies to "alpha1" This is working for me
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
...
<body>
<div id="content">
<b>This is the main container.</b>
</div>
</body>
</html>
You can then center the #content
div using:
#content {
width: 400px;
margin: 0 auto;
background-color: #66ffff;
}
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:
[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }
It will hide the time button from the date picker too.
Sorry if this answer is a little late ;)
As string[]
implements IEnumerable
IEnumerable<string> m_oEnum = new string[] {"1","2","3"}
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy... Please Note: This works in Higher version of CSS (>3.0).
If this is for debugging purposes, I would advise you use a JavaScript debugger such as Firebug. It will let you view the entire contents of arrays and much more, including modifying array entries and stepping through code.
I am using mysql 5.5.24 and the following code works:
select * from (
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
) as a
WHERE guaranteed_postcode NOT IN --this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
You can use the native JS slice method:
<div v-for="item in shoppingItems.slice(0,10)">
The slice() method returns the selected elements in an array, as a new array object.
Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter
Using the GCC compiler(which I did locally) and an online compiler(link), a code similar to the one in the question runs provided a variable name.
#include<iostream>
int main(){
int r= 2, c=3;
int arr[r][c];
arr[0][1]= 3;
std::cout<<arr[0][1];
}
Output: 3
Though I quote cplusplus.com,
NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression since arrays are blocks of static memory whose size must be determined at compile-time before the program runs.
It seems like the present compilers have been changed in this regard. This is a C99 standard which the maintainers of the standard compilers added to their compilers.
We need not have a const declaration. During compilation, the compiler automatically substitutes the value.
This question goes around the topic.
NOTE: This is not the standard coding practice, so some compilers might still throw an error.
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
Reinitialise the view controller
YourViewController *vc = [[YourViewController alloc] initWithNibName:@"YourViewControllerIpad" bundle:nil];
[self.navigationController vc animated:NO];
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
m = [1:numel(list)]';
elm = list.*m;
vectorized algorithms in matlab are in general much faster.
How can I get the value from the map, which is passed as a reference to a function?
Well, you can pass it as a reference. The standard reference wrapper that is.
typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;
// use it
void function(map_ref_t map_r)
{
// get to the map from inside the
// std::reference_wrapper
// see the alternatives behind that link
MAP & the_map = map_r;
// take the value from the map
// by reference
auto & value_r = the_map["key"];
// change it, "in place"
value_r = "new!";
}
And the test.
void test_ref_to_map() {
MAP valueMap;
valueMap["key"] = "value";
// pass it by reference
function(valueMap);
// check that the value has changed
assert( "new!" == valueMap["key"] );
}
I think this is nice and simple. Enjoy ...
You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array
bool isEqual = Enumerable.SequenceEqual(target1, target2);
Mathematically, to get percentage from two numbers:
percentage = (yourNumber / totalNumber) * 100;
And also, to calculate from a percentage :
number = (percentage / 100) * totalNumber;
For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.
text-shadow : 0 0 0 #your-font-color;
This works:
myElement.className = 'foo bar baz';
You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.
To confirm you video is in the correct format (resolution, bitrate, codec, etc.) check with the official documentation - extract below:
Standard definition (Low quality)
Video codec - H.264
Video resolution - 176 x 144 px
Video frame rate - 12 fps
Video bitrate - 56 Kbps
Audio codec - AAC-LC
Audio channels - (mono)
Audio bitrate - 24 Kbps
Standard definition (High quality)
Video codec - H.264
Video resolution - 480 x 360 px
Video frame rate - 30 fps
Video bitrate - 500 Kbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 128 Kbps
High definition 720p (N/A on all devices)
Video codec - H.264
Video resolution - 1280 x 720 px
Video frame rate - 30 fps
Video bitrate - 2 Mbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 192 Kbps
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:
COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;
Note: The folder must be writable.
By executing your .bat you are setting config for only that session not globally. When you open and another cmd prompt and run npm install
that config will not set for this session so modify your .bat file as
@echo off
npm config set registry https://registry.npmjs.org/
@cmd.exe /K
I was able to make this work by creating a named range in the current sheet that referred to the table I wanted to reference in the other sheet.
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
There is something similar in the Python Decorator Library.
Please bear in mind that it does not test for exceptions, but the return value. It retries until the decorated function returns True.
A slightly modified version should do the trick.
While u have tried tons of configuring and clicking and still facing the pop-up error, maybe my answer here will guide u to kill the error.
Updated version for SQL Server 2017 using STRING_AGG function to construct the pivot column list:
create table temp
(
date datetime,
category varchar(3),
amount money
);
insert into temp values ('20120101', 'ABC', 1000.00);
insert into temp values ('20120201', 'DEF', 500.00);
insert into temp values ('20120201', 'GHI', 800.00);
insert into temp values ('20120210', 'DEF', 700.00);
insert into temp values ('20120301', 'ABC', 1100.00);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = (SELECT STRING_AGG(category,',') FROM (SELECT DISTINCT category FROM temp WHERE category IS NOT NULL)t);
set @query = 'SELECT date, ' + @cols + ' from
(
select date
, amount
, category
from temp
) x
pivot
(
max(amount)
for category in (' + @cols + ')
) p ';
execute(@query);
drop table temp;
cmp
Compare
'a' cmp 'b' # -1
'b' cmp 'a' # 1
'a' cmp 'a' # 0
eq
Equal to
'a' eq 'b' # 0
'b' eq 'a' # 0
'a' eq 'a' # 1
ne
Not-Equal to
'a' ne 'b' # 1
'b' ne 'a' # 1
'a' ne 'a' # 0
lt
Less than
'a' lt 'b' # 1
'b' lt 'a' # 0
'a' lt 'a' # 0
le
Less than or equal to
'a' le 'b' # 1
'b' le 'a' # 0
'a' le 'a' # 1
gt
Greater than
'a' gt 'b' # 0
'b' gt 'a' # 1
'a' gt 'a' # 0
ge
Greater than or equal to
'a' ge 'b' # 0
'b' ge 'a' # 1
'a' ge 'a' # 1
See perldoc perlop
for more information.
( I'm simplifying this a little bit as all but cmp
return a value that is both an empty string, and a numerically zero value instead of 0
, and a value that is both the string '1'
and the numeric value 1
. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )
This is an extension function I wrote in Kotlin to use with the RecyclerView
(based on @Paul Woitaschek answer):
fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
val smoothScroller = object : LinearSmoothScroller(this.context) {
override fun getVerticalSnapPreference(): Int = snapMode
override fun getHorizontalSnapPreference(): Int = snapMode
}
smoothScroller.targetPosition = position
layoutManager?.startSmoothScroll(smoothScroller)
}
Use it like this:
myRecyclerView.smoothSnapToPosition(itemPosition)
I got here looking for the same thing and I found another solution. If you guys are interested I share this class:
using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
/// <summary>
/// Generates a 16 byte Unique Identification code of a computer
/// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
/// </summary>
public class FingerPrint
{
private static string fingerPrint = string.Empty;
public static string Value()
{
if (string.IsNullOrEmpty(fingerPrint))
{
fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " +
biosId() + "\nBASE >> " + baseId() +
//"\nDISK >> "+ diskId() + "\nVIDEO >> " +
videoId() +"\nMAC >> "+ macId()
);
}
return fingerPrint;
}
private static string GetHash(string s)
{
MD5 sec = new MD5CryptoServiceProvider();
ASCIIEncoding enc = new ASCIIEncoding();
byte[] bt = enc.GetBytes(s);
return GetHexString(sec.ComputeHash(bt));
}
private static string GetHexString(byte[] bt)
{
string s = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
return s;
}
#region Original Device ID Getting Code
//Return a hardware identifier
private static string identifier
(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
if (mo[wmiMustBeTrue].ToString() == "True")
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
}
return result;
}
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
private static string cpuId()
{
//Uses first CPU identifier available in order of preference
//Don't get all identifiers, as it is very time consuming
string retVal = identifier("Win32_Processor", "UniqueId");
if (retVal == "") //If no UniqueID, use ProcessorID
{
retVal = identifier("Win32_Processor", "ProcessorId");
if (retVal == "") //If no ProcessorId, use Name
{
retVal = identifier("Win32_Processor", "Name");
if (retVal == "") //If no Name, use Manufacturer
{
retVal = identifier("Win32_Processor", "Manufacturer");
}
//Add clock speed for extra security
retVal += identifier("Win32_Processor", "MaxClockSpeed");
}
}
return retVal;
}
//BIOS Identifier
private static string biosId()
{
return identifier("Win32_BIOS", "Manufacturer")
+ identifier("Win32_BIOS", "SMBIOSBIOSVersion")
+ identifier("Win32_BIOS", "IdentificationCode")
+ identifier("Win32_BIOS", "SerialNumber")
+ identifier("Win32_BIOS", "ReleaseDate")
+ identifier("Win32_BIOS", "Version");
}
//Main physical hard drive ID
private static string diskId()
{
return identifier("Win32_DiskDrive", "Model")
+ identifier("Win32_DiskDrive", "Manufacturer")
+ identifier("Win32_DiskDrive", "Signature")
+ identifier("Win32_DiskDrive", "TotalHeads");
}
//Motherboard ID
private static string baseId()
{
return identifier("Win32_BaseBoard", "Model")
+ identifier("Win32_BaseBoard", "Manufacturer")
+ identifier("Win32_BaseBoard", "Name")
+ identifier("Win32_BaseBoard", "SerialNumber");
}
//Primary video controller ID
private static string videoId()
{
return identifier("Win32_VideoController", "DriverVersion")
+ identifier("Win32_VideoController", "Name");
}
//First enabled network card ID
private static string macId()
{
return identifier("Win32_NetworkAdapterConfiguration",
"MACAddress", "IPEnabled");
}
#endregion
}
}
I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.
Note: Add reference to System.Management
.
Here is sample code for display Image from URL.
public static Void downloadfile(String fileurl, ImageView img) {
Bitmap bmImg = null;
URL myfileurl = null;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if (length > 0) {
int[] bitmapData = new int[length];
byte[] bitmapData2 = new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
img.setImageBitmap(bmImg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try this:
var momentObj = $("#start_ts").datepicker("getDate");
var yourDate = momentObj.format('L');
From your command line you can run..
php -i
I know it's not the browser window, but you can't see the phpinfo();
contents without making the function call. Obviously, the best approach would be to have a phpinfo script in the root of your web server directory, that way you have access to it at all times via http://localhost/info.php
or something similar (NOTE: don't do this in a production environment or somewhere that is publicly accessible)
EDIT: As mentioned by binaryLV, its quite common to have two versions of a php.ini per installation. One for the command line interface (CLI) and the other for the web server interface. If you want to see phpinfo output for your web server make sure you specify the ini file path, for example...
php -c /etc/php/apache2/php.ini -i
There are 3 location providers in Android.
They are:
gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).
The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris
Code Reference : https://stackoverflow.com/a/3145655/28557
-----------------------Update-----------------------
Now Android have Fused location provider
The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage
Fused location provider provide three ways to fetch location
References :
Official site : http://developer.android.com/google/play-services/location.html
Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example
http://blog.lemberg.co.uk/fused-location-provider
--------------------------------------------------------
The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".
<meta http-equiv="refresh" content="15" >
This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.
Let us know if it worked/solved your problem!?
-Brad
Posting this to help someone.
Symptom:
channel 2: open failed: connect failed: Connection refused
debug1: channel 2: free: direct-tcpip:
listening port 8890 for 169.254.76.1 port 8890,
connect from ::1 port 52337 to ::1 port 8890, nchannels 8
My scenario; i had to use the remote server as a bastion host to connect elsewhere. Final Destination/Target: 169.254.76.1, port 8890. Through intermediary server with public ip: ec2-54-162-180-7.compute-1.amazonaws.com
SSH local port forwarding command:
ssh -i ~/keys/dev.tst -vnNT -L :8890:169.254.76.1:8890
[email protected]
What the problem was: There was no service bound on port 8890 in the target host. i had forgotten to start the service.
How did i trouble shoot:
SSH into bastion host and then do curl.
Hope this helps.
Please follow @Sourav's advice.
If after restarting the server you get errors, you may need to set your directory options as well. This is done in the <Directory>
tag in httpd.conf. Make sure the final config looks like this:
DocumentRoot "C:\alan"
<Directory "C:\alan">
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
A keystore needs a keystore file. The KeyStore
class needs a FileInputStream
. But if you supply null (instead of FileInputStream
instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool
.
Following code creates an empty keystore with empty password
KeyStore ks2 = KeyStore.getInstance("jks"); ks2.load(null,"".toCharArray()); FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore"); ks2.store(out, "".toCharArray());
Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.
This problem also occurs if a 'view' (imaginary table) exists in database as same name as our new table name.
In Python 3 you can use a variation on:
def Deb(msg = None):
print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")
In code, you can then use:
Deb("Some useful information")
Deb()
To produce:
123: Some useful information
124:
Where the 123 and 124 are the lines that the calls are made from.
The solution for me was to check the case sensitivity of the username. A lot of people are mentioning that the URL is case sensitive, but it seems the username is as well!
According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."
So add indexes for your other fields and it will work. I had a similar problem and this solved it.
You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/
Check your CPU's virtualization in BIOS setup is enabled.
Application binary interface (ABI)
Functionality:
Existing entities:
consumer:
These are needed by whoever has to ensure that build tool-chains work as a whole. If you write one module in assembly language, another in Python, and instead of your own boot-loader want to use an operating system, then your "application" modules are working across "binary" boundaries and require agreement of such "interface".
C++ name mangling because object files from different high-level languages might be required to be linked in your application. Consider using GCC standard library making system calls to Windows built with Visual C++.
ELF is one possible expectation of the linker from an object file for interpretation, though JVM might have some other idea.
For a Windows RT Store app, try searching for ARM ABI if you really wish to make some build tool-chain work together.
you also coud try this:
<select ng-model="selectedItem" ng-change="update()">
<option ng-repeat="item in items"
ng-selected="selectedItem == item.Id" value="{{item.Id}}">
{{item.Name}}
</option>
</select>
Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.
So what you do is register the driver so that the JDBC system can know what to do with the URL:
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Then you form the URL:
String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"
And finally, use it to get a connection:
Connection c = DriverManager.getConnection(url);
In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.
In terms of what properties MySQL supports, see here.
EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.
I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.
First I stringify the data as
var myData = [];
allData.forEach((x, index) => {
// console.log(index);
myData.push(JSON.stringify({
"product_id" : x.product_id,
"product" : x.product,
"url" : x.url,
"image_url" : x.image_url,
"price" : x.price,
"source": x.source
}))
})
Then I sent it like
$.ajax({
url: '{% url "url_name" %}',
method: "POST",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'queryset[]': myData
},
success: (res) => {
// success post work here.
}
})
And received as :
list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]
This work's very well.. hope it help's someone !
-(IBAction)flashlight:(id)sender {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
if (device.torchMode == AVCaptureTorchModeOff) {
[sender setTitle:@"Torch Off" forState:UIControlStateNormal];
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *cam = [[AVCaptureSession alloc] init];
[cam beginConfiguration];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[cam addInput:flashInput];
[cam addOutput:output];
[device unlockForConfiguration];
[cam commitConfiguration];
[cam startRunning];
[self setTorchSession:cam];
}
else {
[sender setTitle:@"Torch On" forState:UIControlStateNormal];
[_torchSession stopRunning];
}
}
}
I've my project in github and heroku, for upload an heroku use :
heroku git:remote -a <project>
The doc it is:
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.
So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...
Maybe the code might be cleaner, but it works for me pretty well.
<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>
<script>
var map;
function initialize() {
// Get all map canvas with ".maps" and store them to a variable.
var maps = document.getElementsByClassName("maps");
var ids, gps, mapId = '';
// Loop: Explore all elements with ".maps" and create a new Google Map object for them
for(var i=0; i<maps.length; i++) {
// Get ID of single div
mapId = document.getElementById(maps[i].id);
// Get LatLng stored in data attribute.
// !!! Make sure there is no space in data-attribute !!!
// !!! and the values are separated with comma !!!
gps = mapId.getAttribute('data-gps');
// Convert LatLng to an array
gps = gps.split(",");
// Create new Google Map object for single canvas
map = new google.maps.Map(mapId, {
zoom: 15,
// Use our LatLng array bellow
center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
mapTypeId: 'roadmap',
mapTypeControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
}
});
// Create new Google Marker object for new map
var marker = new google.maps.Marker({
// Use our LatLng array bellow
position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
map: map
});
}
}
</script>
If you have Exchange 2010:
(In my case, the error message didn't contain " for [email protected]")
This shows how to add a receive connector: http://exchangeserverpro.com/how-to-configure-a-relay-connector-for-exchange-server-2010/
But I also needed to perform a step found here: http://recover-email.blogspot.com.au/2013/12/how-to-solve-exchange-smtp-server-error.html
- Go to Exchange Management Shell and run the command
- Get-ReceiveConnector "JiraTest" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"
While working on this, I ran the following on the affected server's PowerShell console until the error went away:
Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Test Email" -Body "This is a test"
Code I have used for IE 11 without jquery and just for a single textarea:
Javascript:
// Impede que o comentário tenha mais de num_max caracteres
var internalChange= 0; // important, prevent reenter
function limit_char(max)
{
if (internalChange == 1)
{
internalChange= 0;
return;
}
internalChange= 1;
// <form> and <textarea> are the ID's of your form and textarea objects
<form>.<textarea>.value= <form>.<textarea>.value.substring(0,max);
}
and html:
<TEXTAREA onpropertychange='limit_char(5)' ...
I think that they are often not "versus", but you can combine them. I also think that oftentimes, the words you mention are just buzzwords. There are few people who actually know what "object-oriented" means, even if they are the fiercest evangelists of it.
Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
Here's an example:
<script>
var globalVariable = 7; //==window.globalVariable
function aGlobal( param ) { //==window.aGlobal();
//param is only accessible in this function
var scopedToFunction = {
//can't be accessed outside of this function
nested : 3 //accessible by: scopedToFunction.nested
};
anotherGlobal = {
//global because there's no `var`
};
}
</script>
You'll want to investigate closures, and how to use them to make private members.
Garbage collector is a component of jvm.
It is used to collect garbage when ever cpu gets free.
Here garbage means unused objects it runs in Background of main program
to monitor the status of the main program.
JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern
// filename: MyComponent.js
function MyComponent() {
return <div />;
}
as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here
You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.
No need to use string functions. You can use something that's actually designed for what you want: pathinfo()
:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
I know this is an old one but even I found myself wandering past it again, so I thought I'd submit my own option here.
Best bet is to check out my blog post on this: Timing things in Objective-C: A stopwatch
Basically, I wrote a class that does stop watching in a very basic way but is encapsulated so that you only need to do the following:
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
And you end up with:
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
in the log...
Again, check out my post for a little more or download it here: MMStopwatch.zip
pip
is installed automatically with python2 using brew:
brew install python3
pip3 --version
Column values from the SELECT statement are assigned into @low
and @day
local variables; the @adjustedLow
value is not assigned into any variable and it causes the problem:
The problem is here:
select
top 1 @low = low
, @day = day
, @adjustedLow -- causes error!
--select high
from
securityquote sq
...
Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
'abcdefg' =~ /\Aabc/
How about using assign?
functionReturningTwoValues <- function(a, b) {
assign(a, 1, pos=1)
assign(b, 2, pos=1)
}
You can pass the names of the variable you want to be passed by reference.
> functionReturningTwoValues('a', 'b')
> a
[1] 1
> b
[1] 2
If you need to access the existing values, the converse of assign
is get
.
bundle exec
is a Bundler command to execute a script in the context of the current bundle (the one from your directory's Gemfile). rake db:migrate
is the script where db is the namespace and migrate is the task name defined.
So bundle exec rake db:migrate
executes the rake script with the command db:migrate
in the context of the current bundle.
As to the "why?" I'll quote from the bundler page:
In some cases, running executables without
bundle exec
may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.
and
has lower precedence than &&
.
But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator:
def happy?() true; end
def know_it?() true; end
todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"
todo
# => "Clap your hands"
todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"
todo
# => true
You can try this:
function search(data,search) {
var obj = [], index=0;
for(var i=0; i<data.length; i++) {
for(key in data[i]){
if(data[i][key].toString().toLowerCase().indexOf(search.toLowerCase())!=-1) {
obj[index] = data[i];
index++;
break;
}
}
return obj;
}
console.log(search(obj.list,'my Name'));
@ Merk
For ur solution insted of lambda expression you can use following code:
//var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
TranslateTransform tt = null;
TransformGroup transformGroup = (TransformGroup)grid.RenderTransform;
for (int i = 0; i < transformGroup.Children.Count; i++)
{
if (transformGroup.Children[i] is TranslateTransform)
tt = (TranslateTransform)transformGroup.Children[i];
}
this code can be use as is for .Net Frame work 3.0 or 2.0
Hope It helps you :-)
You can use the CSS property "content":
div {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
div:after {
content: "X";
font-size: 2em;
color: #FFF;
}
Like this: http://jsfiddle.net/HKtFV/
You can use the concept of multiple queries in the FROM keyword. Let me show you one example:
SELECT DISTINCT e.id,e.name,d.name,lap.lappy LAPTOP_MAKE,c_loc.cnty COUNTY
FROM (
SELECT c.id cnty,l.name
FROM county c, location l
WHERE c.id=l.county_id AND l.end_Date IS NOT NULL
) c_loc, emp e
INNER JOIN dept d ON e.deptno =d.id
LEFT JOIN
(
SELECT l.id lappy, c.name cmpy
FROM laptop l, company c
WHERE l.make = c.name
) lap ON e.cmpy_id=lap.cmpy
You can use as many tables as you want to. Use outer joins and union where ever it's necessary, even inside table subqueries.
That's a very easy method to involve as many as tables and fields.
For a String constant you have no choice other than escaping via backslash.
Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.
Shorter version:
$('#multiselect1').multiselect({
...
onChange: function() {
console.log($('#multiselect1').val());
}
});
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
Just replace it:
<li><a href="" data-toggle="modal" data-target="#modalRegister">Register</a></li>
Instead of:
<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>
Variables are not defined, but declared.
This is possible duplicate of declare variables in a pl/sql block
But you can look here :
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/fundamentals.htm#i27306
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/overview.htm
UPDATE:
Refer here : How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?