//best and simple way to show keys and values
//initialize map
Map<Integer, String> map = new HashMap<Integer, String>();
//Add some values
map.put(1, "Hi");
map.put(2, "Hello");
// iterate map using entryset in for loop
for(Entry<Integer, String> entry : map.entrySet())
{ //print keys and values
System.out.println(entry.getKey() + " : " +entry.getValue());
}
//Result :
1 : Hi
2 : Hello
You also need to handle exceptions from threads:
static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}
private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
Console.WriteLine(e.Exception.StackTrace);
}
Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.
A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.
Configuration is as follows: React + Redux, Webpack 3.5.6
The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.
The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.
So here it is:
fetch('../../package.json')
.then(resp => resp.json())
.then((packageJson) => {
console.log(packageJson.version);
});
Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.
If you have no time, submit the malware to cwsandbox:
http://jon.oberheide.org/blog/2008/01/15/detecting-and-evading-cwsandbox/
HTH
let mainString = "Hello World"
let stringToColor = "World"
SWIFT 5
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
SWIFT 4.2
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
You can find the target element in event.target
:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
I know if that can help you a bit.
Here is something I tried to simulate for you.
Checkout the jsFiddle ;)
http://jsfiddle.net/migontech/gbW8Z/5/
Created a filter that you also can use in 'ng-repeat'
app.filter('getById', function() {
return function(input, id) {
var i=0, len=input.length;
for (; i<len; i++) {
if (+input[i].id == +id) {
return input[i];
}
}
return null;
}
});
Usage in controller:
app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
$scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'}, {category:'freshwater', id:'2', name:'bass', more:'false'}]
$scope.showdetails = function(fish_id){
var found = $filter('getById')($scope.fish, fish_id);
console.log(found);
$scope.selected = JSON.stringify(found);
}
}]);
If there are any questions just let me know.
This is vary useful please try it and change as required.
#!/bin/bash
for load in $(seq 1 100); do
echo -ne "$load % downloded ...\r"
sleep 1
done
echo "100"
echo "Loaded ..."
int [] SouceArray1 = new int[] {2,1,3};
int [] SourceArray2 = new int[] {4,5,6};
int [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];
SouceArray1.CopyTo(targetArray,0);
SourceArray2.CopyTo(targetArray,SouceArray1.Length) ;
foreach (int i in targetArray) Console.WriteLine(i + " ");
Using the above code two Arrays can be easily merged.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
The below programme will help you drop duplicates on whole , or if you want to drop duplicates based on certain columns , you can even do that:
import org.apache.spark.sql.SparkSession
object DropDuplicates {
def main(args: Array[String]) {
val spark =
SparkSession.builder()
.appName("DataFrame-DropDuplicates")
.master("local[4]")
.getOrCreate()
import spark.implicits._
// create an RDD of tuples with some data
val custs = Seq(
(1, "Widget Co", 120000.00, 0.00, "AZ"),
(2, "Acme Widgets", 410500.00, 500.00, "CA"),
(3, "Widgetry", 410500.00, 200.00, "CA"),
(4, "Widgets R Us", 410500.00, 0.0, "CA"),
(3, "Widgetry", 410500.00, 200.00, "CA"),
(5, "Ye Olde Widgete", 500.00, 0.0, "MA"),
(6, "Widget Co", 12000.00, 10.00, "AZ")
)
val customerRows = spark.sparkContext.parallelize(custs, 4)
// convert RDD of tuples to DataFrame by supplying column names
val customerDF = customerRows.toDF("id", "name", "sales", "discount", "state")
println("*** Here's the whole DataFrame with duplicates")
customerDF.printSchema()
customerDF.show()
// drop fully identical rows
val withoutDuplicates = customerDF.dropDuplicates()
println("*** Now without duplicates")
withoutDuplicates.show()
// drop fully identical rows
val withoutPartials = customerDF.dropDuplicates(Seq("name", "state"))
println("*** Now without partial duplicates too")
withoutPartials.show()
}
}
Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.
I typically abbreviate so that I can use several places in my code. Near the top, do something like this:
string nl = System.Environment.NewLine;
Then I can just use "nl" instead of the full qualification everywhere when constructing strings.
For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task
class and TaskStatus
enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.
In the context of methods marked as async
, the resulting Task
is not a Task
representing the execution of the method, but a Task
for the continuation of the method.
This is only able to make use of a few possible states:
I understand that Running
could appear to have been a better default than WaitingForActivation
, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await
-ing something else). The other option may have been to add a new value to TaskStatus
, however this could have been a breaking change for existing applications and libraries.
All of this is very different to when making use of Task.Run
which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus
enumeration.
If you wish to keep track of the status of an async method, take a look at the IProgress(T)
interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T)
interface.
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
why not try opening your file as text?
with open(fname, 'rt') as f:
lines = [x.strip() for x in f.readlines()]
Additionally here is a link for python 3.x on the official page: https://docs.python.org/3/library/io.html And this is the open function: https://docs.python.org/3/library/functions.html#open
If you are really trying to handle it as a binary then consider encoding your string.
Age (full years) of the Person:
SELECT
TRUNC(months_between(sysdate, per.DATE_OF_BIRTH) / 12) AS "Age"
FROM PD_PERSONS per
Hope below code will help you.
DateFormat formatDate = new SimpleDateFormat(ISO_DATE_TIME_PATTERN);
formatDate.setTimeZone(TimeZone.getTimeZone("UTC"));
formatDate.parse(dateString);
First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list
Extract the file it create dex2jar
folder
Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex
file
Now pick classes.dex file and put it into dex2jar
folder
Now open cmd window and type the path of dex2jar
folder
Now type the command dex2jar.bat classes.dex
and press Enter
Now Open the dex2jar
folder you found classes_dex2jar.jar
file
Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui
Last Step Open the file classes_dex2jar.jar
in java decompiler tool now you can see apk code
Here are a couple good sites to check out for that,
http://www.tripwiremagazine.com/2011/10/css-menu-and-navigation.html (Lots of examples)
http://webdesignerwall.com/tutorials/css3-dropdown-menu (1 example more tutorial like)
Hope this is helpful information!
Actually there are three ways to enable full screnn, visit : https://developer.android.com/training/system-ui/immersive
but if you wanna get full screen when the activity is opened, just put this code in your_activity.java
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
hideSystemUI();
}
}
private void hideSystemUI() {
// Enables regular immersive mode.
// For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
// Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN);
}
// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
They are bit shift operator which exists in many mainstream programming languages, <<
is the left shift and >>
is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
In short "redirect://yahoo.com"
will lend you to yahoo.com
.
where as "redirect:yahoo.com"
will lend you your-context/yahoo.com
ie for ex- localhost:8080/yahoo.com
$.ajax({_x000D_
url: URL,_x000D_
type: 'GET',_x000D_
dataType: 'json',_x000D_
headers: {_x000D_
'header1': 'value1',_x000D_
'header2': 'value2'_x000D_
},_x000D_
contentType: 'application/json; charset=utf-8',_x000D_
success: function (result) {_x000D_
// CallBack(result);_x000D_
},_x000D_
error: function (error) {_x000D_
_x000D_
}_x000D_
});
_x000D_
You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):
Function GetFillColor(Rng As Range) As Long
GetFillColor = Rng.Interior.ColorIndex
End Function
Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel
In your worksheet, you can use the following: =GetFillColor(B5)
All these loops do the exact same, I just want to show these before throwing in my two cents.
First, the classic way of looping through List:
for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }
Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).
for (String s : strings) { /* do something using s */ }
Third, the micro-optimized for loop:
int size = strings.size();
for (int i = -1; ++i < size;) { /* do something using strings.get(i) */ }
Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.
While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java for-each loop (some refer to it as Iterator loop and others as for-in loop) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.
If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.
Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:
num // 10 ** (int(math.log(num, 10)) - 1)
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456
You will need to add some checks if it's possible that your input number has less digits than you want.
Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:
int x = *(int*)"abcd";
Or a bit more specific:
int x = *(int32_t*)"abcd";
One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):
int x = ((union {char s[5]; int number;}){"abcd"}).number;
/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");
Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).
For starters, you can "disable" the option from being selected accidentally by users:
<option value="" disabled="disabled">Choose an option</option>
Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:
select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
// value is set to a valid option, so submit form
return true;
}
return false;
Or something to that effect.
If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...
Should do the job for MySQL, for SqlServer I'm sure there is an analog function.
If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE
for MySQL.
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:
/*jshint -W106 */
save_state(id);
/*jshint +W106 */
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set
. You should realize that it has absolutely no meaning for most implementations of Set
. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
You can get around this limit with the deprecated syntax: ORDER BY 1 DESC
This syntax is not deprecated at all, it's E121-03 from SQL99.
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
I guess ssh
is the best secured way for this, for example :
ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"
where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.
Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain
if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config
. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.
Some extra docs over the source project main pages :
ssh and ssh-agent
man ssh
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/
It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).
If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.
public class YourLoggingWrapper {
private static boolean loggingIsInitialized = false;
public YourLoggingWrapper() {
// ...blah
}
public static void debug(String debugMsg) {
log(LogLevel.Debug, debugMsg);
}
// Same for all other log levels your want to handle.
// You mentioned TRACE and ERROR.
private static void log(LogLevel level, String logMsg) {
if(!loggingIsInitialized)
initLogging();
org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");
switch(level) {
case: Debug:
logger.debug(logMsg);
break;
default:
// whatever
}
}
// log4j logging is lazily constructed; it gets initialized
// the first time the invoking app calls a log method
private static void initLogging() {
loggingIsInitialized = true;
org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");
// Now all the same configuration code that @oers suggested applies...
// configure the logger, configure and add its appenders, etc.
debugLogger.addAppender(someConfiguredFileAppender);
}
With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
The List
interface supports random access via the get
method - to get line 0, use list.get(0)
. You'll need to use array access on that, ie, lines.get(0)[0]
is the first element of the first line.
See the javadoc here.
There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...
EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())
... to format your number in a standard format.
PhoneNumberUtils.compare(String a, String b);
... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.
p.s. setting the the EditText to phone
is already a good choice; eventually it might be helpful to add digits
e.g. in your layout it looks as ...
<EditText
android:id="@+id/editTextId"
android:inputType="phone"
android:digits="0123456789+"
/>
I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them
What is ARIA?
If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.
ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.
And see this you tube video for ARIA live.
To me, the problem looks like you're sending "datetime('now')"
as a string, rather than a value.
My thought is to find a way to grab the current date/time and send it to your database as a date/time value, or find a way to use SQLite's built-in (DATETIME('NOW'))
parameter
Check out the anwsers at this SO.com question - they might lead you in the right direction.
Hopefully this helps!
You can try "ours" option in git merge,
git merge branch -X ours
This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
Try working with this C# snippet I just crafted:
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string directory = @"C:\downloads";
DirectoryInfo di = new DirectoryInfo(directory);
DirectorySecurity ds = di.GetAccessControl();
foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine("Identity = {0}; Access = {1}",
rule.IdentityReference.Value, rule.AccessControlType);
}
}
}
}
And here's a reference you could also look at. My code might give you an idea as to how you could check for permissions before attempting to write to a directory.
This is not exactly what you are looking for, but might work in your case
grep '[[:blank:]]'
Equivalent to
grep -P '[ \t]'
So it will find Space and Tab.
Note, it is not advertised in my man grep
, but still works
$ man grep | grep blank | wc 0 0 0
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
Use "
That should work.
I think you want (this won't fit in a int
though, you'll need to store it as a long
):
long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;
Alternatively, storing the ticks is a better idea.
If for any reason you cannot change the original filter mapping ("/*" in my case) and you are dispatching to an unchangeable third-party filter, you can find useful the following:
The following works in Weblogic 12.1.3:
import org.apache.commons.lang3.reflect.FieldUtils; import javax.servlet.Filter; [...] @Override public void doFilter(ServletRequest request, ServletRespons response, FilterChain chain) throws IOException, ServletException { String path = ((HttpServletRequest) request).getRequestURI(); if(!bypassSWA(path)){ swpFilterHandler.doFilter(request, response, chain); } else { try { ((Filter) (FieldUtils.readField( (FieldUtils.readField( (FieldUtils.readField(chain, "filters", true)), "last", true)), "item", true))) .doFilter(request, response, chain); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
http://docs.python.org/2/tutorial/classes.html#method-objects
Usually, a method is called right after it is bound:
x.f()
In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:
xf = x.f while True: print xf()
will continue to print hello world until the end of time.
What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used...
Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
Since none of the answers here seem to solve it properly, here's my semi-obfuscated version using underscorejs:
function foo(l, target) {
var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0);
return _.chain(l).
sortBy(function(x) { return Math.round(x) - x }).
map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }).
value();
}
foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9]
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16]
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33]
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0]
The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:
>>> 0.1 0.10000000000000001
you may be tempted to use the
round()
function to chop it back to the single digit you expect. But that makes no difference:>>> round(0.1, 1) 0.10000000000000001
The problem is that the binary floating-point value stored for
“0.1”
was already the best possible binary approximation to1/10
, so trying to round it again can’t make it better: it was already as good as it gets.Another consequence is that since
0.1
is not exactly1/10
, summing ten values of0.1
may not yield exactly1.0
, either:>>> sum = 0.0 >>> for i in range(10): ... sum += 0.1 ... >>> sum 0.99999999999999989
One alternative and solution to your problems would be using the decimal
module.
I've just fixed this for my machine. Maybe it will work for some. Maybe not for others, but here is what worked for me.
In IIS, I had to add bindings for https to the default website (or, I suppose, the website you are running the app under).
Now my localhost works when debugging from Visual Studio.
This worked for me. Lists the files created on May 30 in the current directory.
ls -lt | grep 'May 30'
No.
The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain name only.
Accessing all cookies for current domain is done via document.cookie
.
While you will not get as detailed information about the model as in Keras' model.summary, simply printing the model will give you some idea about the different layers involved and their specifications.
For instance:
from torchvision import models
model = models.vgg16()
print(model)
The output in this case would be something as follows:
VGG (
(features): Sequential (
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU (inplace)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU (inplace)
(4): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU (inplace)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU (inplace)
(9): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU (inplace)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU (inplace)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU (inplace)
(16): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU (inplace)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU (inplace)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU (inplace)
(23): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU (inplace)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU (inplace)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU (inplace)
(30): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
)
(classifier): Sequential (
(0): Dropout (p = 0.5)
(1): Linear (25088 -> 4096)
(2): ReLU (inplace)
(3): Dropout (p = 0.5)
(4): Linear (4096 -> 4096)
(5): ReLU (inplace)
(6): Linear (4096 -> 1000)
)
)
Now you could, as mentioned by Kashyap, use the state_dict
method to get the weights of the different layers. But using this listing of the layers would perhaps provide more direction is creating a helper function to get that Keras like model summary! Hope this helps!
Due to windows encoding issue for me
I experienced this "Could not open input file" error. Then I obtained the file using wget
from another linux system, and the error did not occur.
The error ws only occurring for me when the file transited through windows.
As this is the top search on Google for converting a list of lists into a Numpy array, I'll offer the following despite the question being 4 years old:
>>> x = [[1, 2], [1, 2, 3], [1]]
>>> y = numpy.hstack(x)
>>> print(y)
[1 2 1 2 3 1]
When I first thought of doing it this way, I was quite pleased with myself because it's soooo simple. However, after timing it with a larger list of lists, it is actually faster to do this:
>>> y = numpy.concatenate([numpy.array(i) for i in x])
>>> print(y)
[1 2 1 2 3 1]
Note that @Bastiaan's answer #1 doesn't make a single continuous list, hence I added the concatenate
.
Anyway...I prefer the hstack
approach for it's elegant use of Numpy.
In recent versions of major browsers you can use backdrop-filter property.
HTML
<div>backdrop blur</div>
CSS
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}
or if you need different background color for browsers without support:
div {
background-color: rgba(255, 255, 255, 0.9);
}
@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
}
}
Demo: JSFiddle
Docs: Mozilla Developer: backdrop-filter
Is it for me?: CanIUse
In addition to the Python 2 approach here are the equivalents for Python 3:
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
Ranges are lists in Python 2 and iterators in Python 3.
Try this, replacing .myClassName
with the actual name of the class (but keep the period at the beginning).
$('.myClassName').each(function() {
alert( this.id );
});
So if the class is "test", you'd do $('.test').each(func...
.
This is the specific form of .each()
that iterates over a jQuery object.
The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t
.
Using that form of $.each()
, you would need to do it like this:
$.each($('.myClassName'), function() {
alert( this.id );
});
...which will have the same result as the example above.
The benefits of super()
in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without super()
. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child
and a mixin, their code would not work properly.
Use the Make shell
builtin like in MY_VAR=$(shell echo whatever)
me@Zack:~$make
MY_VAR IS whatever
me@Zack:~$ cat Makefile
MY_VAR := $(shell echo whatever)
all:
@echo MY_VAR IS $(MY_VAR)
re.split(pattern, string[, maxsplit=0])
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.)
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
Here is the another solution as well, the bind method.
$(document).bind('click', ".intro", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
Cheers :)
DECLARE @INSERTEDCOUNT INT,
@DELETEDCOUNT INT
SELECT @INSERTEDCOUNT = COUNT([YourColumnName]) FROM inserted
SELECT @DELETEDCOUNT = COUNT([YourColumnName]) FROM deleted
IF its updation
@INSERTEDCOUNT = 1
@DELETEDCOUNT = 1
if its insertion
@INSERTEDCOUNT = 1
@DELETEDCOUNT = 0
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/ It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
Here's all the options you have:
for...of
(ES2015)var dictionary = {_x000D_
"data": [_x000D_
{"id":"0","name":"ABC"},_x000D_
{"id":"1","name":"DEF"}_x000D_
],_x000D_
"images": [_x000D_
{"id":"0","name":"PQR"},_x000D_
{"id":"1","name":"xyz"}_x000D_
]_x000D_
};_x000D_
_x000D_
for (const entry of dictionary.data) {_x000D_
console.log(JSON.stringify(entry))_x000D_
}
_x000D_
Array.prototype.forEach
(ES5)var dictionary = {_x000D_
"data": [_x000D_
{"id":"0","name":"ABC"},_x000D_
{"id":"1","name":"DEF"}_x000D_
],_x000D_
"images": [_x000D_
{"id":"0","name":"PQR"},_x000D_
{"id":"1","name":"xyz"}_x000D_
]_x000D_
};_x000D_
_x000D_
dictionary.data.forEach(function(entry) {_x000D_
console.log(JSON.stringify(entry))_x000D_
})
_x000D_
for()
(ES1)var dictionary = {_x000D_
"data": [_x000D_
{"id":"0","name":"ABC"},_x000D_
{"id":"1","name":"DEF"}_x000D_
],_x000D_
"images": [_x000D_
{"id":"0","name":"PQR"},_x000D_
{"id":"1","name":"xyz"}_x000D_
]_x000D_
};_x000D_
_x000D_
for (let i = 0; i < dictionary.data.length; i++) {_x000D_
console.log(JSON.stringify(dictionary.data[i]))_x000D_
}
_x000D_
You can retrieve information about the version of your JBoss EAP installation by running the same script used to start the server with the -V switch. For Linux and Unix installations this script is run.sh and on Microsoft Windows installations it is run.bat. Regardless of platform the script is located in $JBOSS_HOME/bin. Using these scripts to actually start your server is dealt with in Chapter 4, Launching the JBoss EAP Server.
in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
SELECT EXTRACT( YEAR_MONTH FROM `date` )
FROM `Table` WHERE Condition = 'Condition';
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
select b.* from
(select
`lms_attendance`.`user` AS `user`,
max(`lms_attendance`.`time`) AS `time`
from `lms_attendance`
group by
`lms_attendance`.`user`) a
join
(select *
from `lms_attendance` ) b
on a.user = b.user
and a.time = b.time
$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')
$response = $request.GetResponse()
$response.StatusCode
$response.Close()
If you are using the glyphicon as the first character of the string, you can use the html char (see https://glyphicons.bootstrapcheatsheets.com/) and then apply the font to the first character of the element:
option::first-letter{
font-family: Glyphicons Halflings;
}
You can use the following to get the previous URL.
var oldURL = document.referrer;
alert(oldURL);
If the list is in random order, you can just take the first 50.
Otherwise, use
import random
random.sample(the_list, 50)
random.sample
help text:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)
Assuming you're building a Web Application, which it appears you are given the MVC2 point, you shouldn't use the App_Code folder. It was not designed to be integrated with Web Application projects.
When you Compile in Visual Studio, all the code in your application (including in App_Code) gets compiled into an assembly. When you run your application, asp.net knows about a "special" folder called App_Code and compiles the content of it into an assembly with a unique name. Thus, anytime you run the project you'll run into this problem.
The solution:
Rename your App_Code folder to something like "Code" or "Global" (and update your now broken references) & voila, problem solved.
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
I implemented a Hive Data platform recently in my firm and can speak to it in first person since I was a one man team.
I benchmarked the following options:
HBase is like a Map. If you know the key, you can instantly get the value. But if you want to know how many integer keys in Hbase are between 1000000 and 2000000 that is not suitable for Hbase alone.
If you have data that needs to be aggregated, rolled up, analyzed across rows then consider Hive.
Hopefully this helps.
Hive actually rocks ...I know, I have lived it for 12 months now... So does HBase...
Yes. You need to prefix the table name with "#" (hash) to create temporary tables.
If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.
"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.
Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005
If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.
They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.
DECLARE @ItemBack1 TABLE
(
column1 int,
column2 int,
someInt int,
someVarChar nvarchar(50)
);
INSERT INTO @ItemBack1
SELECT column1,
column2,
someInt,
someVarChar
FROM table2
WHERE table2.ID = 7;
More Info on Table Variables: http://odetocode.com/articles/365.aspx
Based on the main answer, this is an example, useful to display an information tooltip when clicking on a ?
near a link:
document.onclick = function() { document.getElementById("tooltip").style.display = 'none'; };_x000D_
_x000D_
document.getElementById("tooltip").onclick = function(e) { e.stopPropagation(); }_x000D_
_x000D_
document.getElementById("help").onclick = function(e) { document.getElementById("tooltip").style.display = 'block';_x000D_
e.stopPropagation(); };
_x000D_
#help { opacity: 0; margin-left: 0.1em; padding: 0.4em; }_x000D_
_x000D_
a:hover + #help, #help:hover { opacity: 0.5; cursor: pointer; }_x000D_
_x000D_
#tooltip { border: 1px solid black; display: none; padding: 0.75em; width: 50%; text-align: center; font-family: sans-serif; font-size:0.8em; }
_x000D_
<a href="">Delete all obsolete informations</a><span id="help">?</span>_x000D_
<div id="tooltip">All data older than 2 weeks will be deleted.</div>
_x000D_
This is a quick and simple add of a named tab to the current worksheet:
Sheets.Add.Name = "Tempo"
EDIT: As of 2019, e.metaKey
is supported on all major browsers as per the MDN.
Note that on Windows, although the ? Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.
This is only for the command key on MacOS/keyboards.
Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown
/keyup
and record when a key is pressed and then depressed based on event.keyCode
.
Unfortunately, these key codes are browser-dependent:
224
17
91
(Left Command) or 93
(Right Command)You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
A simpler way of doing it is:
var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
HTML
<div id="wrapper">
<div id="nav"></div>
<div id="content"></div>
<div class="clearFloat"></div>
</div>
CSS
.clearFloat {
font-size: 0px;
line-height: 0px;
margin: 0px;
padding: 0px;
clear: both;
height: 0px;
}
Well I was searching view json file in WebBrowser in my Desktop app, when I try in IE still same problem IE was also prompt to download the file. Luckily after too much search I find the solution for it.
You need to : Open Notepad and paste the following:
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json] "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}" "Encoding"=hex:08,00,00,00Save document as Json.reg and then right click on file and run as administrator.
After this You can view json file in IE and you Desktop WebBrowser enjoy :)
1) How do I make it so that the whole column is "checked" by default?
var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;
dataGridView1.Columns.Insert(0, doWork);
2) How can I make sure I'm only getting values from the "checked" rows?
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;//If editing is enabled, skip the new row
//The Cell's Value gets it wrong with the true default, it will return
//false until the cell changes so use FormattedValue instead.
if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
{
//Do stuff with row
}
}
npm install jspdf --save
//code on react
import jsPDF from 'jspdf';
var doc = new jsPDF()
doc.fromHTML("<div>JOmin</div>", 1, 1)
onclick //
doc.save("name.pdf")
Yes it is valid according to xhtml1-strict.dtd
. The following XHTML passes the validation:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<ul>
<li><div>test</div></li>
</ul>
</body>
</html>
import sys
from Tkinter import *
def quit():
sys.exit()
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
Should do what you are asking.
For symfony 4 users:
$query = $request->query->get('query');
The SSL errors are often thrown by network management software such as Cyberroam.
To answer your question,
you will have to enter badidea into Chrome every time you visit a website.
You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors
Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.
public String decorateTheString(String orgStr){
StringBuilder builder = new StringBuilder();
builder.append(orgStr);
builder.deleteCharAt(orgStr.length()-1);
builder.insert(0,builder.hashCode());
return builder.toString();
}
It can be use as a helper/builder to build the String, not the String itself.
This is command for connect
smtp.gmail.com
587
echo -n '{{user_name}}' | base64
echo -n '{{user_password}}' | base64
openssl s_client -connect {{server_name}}:{{server_port}} -crlf -quiet -starttls smtp
and steps to accept message to send
auth login
{{user_name__hash}}
{{user_password__hash}}
helo {{server_name}}
mail from: <{{message_from}}>
rcpt to: <{{message_to}}>
DATA
from: <{{message_from}}>
to: <{{message_to}}>
subject:{{message_subject}}
Content-Type: text/html; charset='UTF-8'; Content-Transfer-Encoding: base64;
MIME-Version: 1.0
{{message_content}}
.
quit
Your else statement should look like this (note the ^
):
{{^avatar}}
...
{{/avatar}}
In mustache this is called 'Inverted sections'.
It isn't possible to do it the way you've defined ldap_get
. However, if you define ldap_get
like this:
def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )
Now you can:
ldap_get( base_dn, filter, X )
But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).
The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
Do you need to fake an anchor click? From the thickbox site:
ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).
If that is acceptable it should be as easy as putting the thickbox class on the input itself:
<input id="thickboxButton" type="button" class="thickbox" value="Click me">
If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.
Edit:
Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:
<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>
The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.
Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
This version trims internal whitespace and non-alphanumerics:
static inline std::string &trimAll(std::string &s)
{
if(s.size() == 0)
{
return s;
}
int val = 0;
for (int cur = 0; cur < s.size(); cur++)
{
if(s[cur] != ' ' && std::isalnum(s[cur]))
{
s[val] = s[cur];
val++;
}
}
s.resize(val);
return s;
}
You need to have an implementation of IValueConverter interface that converts the uri into an image. Your Convert implementation of IValueConverter will look something like this:
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value as string);
image.EndInit();
return image;
Then you will need to use the converter in your binding:
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath, Converter=...}" />
</Image.Source>
</Image>
you just need to use:
Map<>.toString().replace("]","\n");
and replaces the ending square bracket of each key=value set with a new line.
simple you want to inialize a 2d array and assign a size of array then a example is
public static void main(String args[])
{
char arr[][]; //arr is 2d array name
arr = new char[3][3];
}
//this is a way to inialize a 2d array in java....
Simply use the macros from <float.h>
and the variable-width conversion specifier (".*"
):
float f = 3.14159265358979323846;
printf("%.*f\n", FLT_DIG, f);
I had the same problem, needed a modification of [Required] attribute - make field required in dependence of http request.The solution was similar to Dan Hunex answer, but his solution didn't work correctly (see comments). I don't use unobtrusive validation, just MicrosoftMvcValidation.js out of the box. Here it is. Implement your custom attribute:
public class RequiredIfAttribute : RequiredAttribute
{
public RequiredIfAttribute(/*You can put here pararmeters if You need, as seen in other answers of this topic*/)
{
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
//You can put your logic here
return ValidationResult.Success;//I don't need its server-side so it always valid on server but you can do what you need
}
}
Then you need to implement your custom provider to use it as an adapter in your global.asax
public class RequreIfValidator : DataAnnotationsModelValidator <RequiredIfAttribute>
{
ControllerContext ccontext;
public RequreIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
: base(metadata, context, attribute)
{
ccontext = context;// I need only http request
}
//override it for custom client-side validation
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
//here you can customize it as you want
ModelClientValidationRule rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
//and here is what i need on client side - if you want to make field required on client side just make ValidationType "required"
ValidationType =(ccontext.HttpContext.Request["extOperation"] == "2") ? "required" : "none";
};
return new ModelClientValidationRule[] { rule };
}
}
And modify your global.asax with a line
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequreIfValidator));
and here it is
[RequiredIf]
public string NomenclatureId { get; set; }
The main advantage for me is that I don't have to code custom client validator as in case of unobtrusive validation. it works just as [Required], but only in cases that you want.
The solution I chose is similar to Daniel's, but rather than use an object factory and override the toString, I explicitly add the hash to the object when it is first requested through a getHashCode function. A little messy, but better for my needs :)
Function.prototype.getHashCode = (function(id) {
return function() {
if (!this.hashCode) {
this.hashCode = '<hash|#' + (id++) + '>';
}
return this.hashCode;
}
}(0));
I second Wireshark. It is very powerful and versatile. And since this tool will work not only on Windows but also on Linux or Mac OSX, investing your time to learn it (quite easy actually) makes sense. Whatever the platform or the language you use, it makes sense.
Regards,
Richard Just Programmer http://sili.co.nz/blog
The mktemp(1)
man page explains it fairly well:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
In a script, I invoke mktemp something like
mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktemp
is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others
By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…
1st download jquery.form.js file from below url
http://plugins.jquery.com/form/
Write below code in cshtml
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
<div id="uploadTemplate">
<input type="text" value="Asif" id="txtname" name="txtName" />
<div id="dvAddTemplate">
Add Template
<br />
<input type="file" name="file" id="file" tabindex="2" />
<br />
<input type="submit" value="Submit" />
<input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
</div>
<div id="TemplateTree" style="overflow-x: auto;"></div>
</div>
<div id="progressBarDiv" style="display: none;">
<img id="loading-image" src="~/Images/progress-loader.gif" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
debugger;
alert('sample');
var status = $('#status');
$('#frmTemplateUpload').ajaxForm({
beforeSend: function () {
if ($("#file").val() != "") {
//$("#uploadTemplate").hide();
$("#btnAction").hide();
$("#progressBarDiv").show();
//progress_run_id = setInterval(progress, 300);
}
status.empty();
},
success: function () {
showTemplateManager();
},
complete: function (xhr) {
if ($("#file").val() != "") {
var millisecondsToWait = 500;
setTimeout(function () {
//clearInterval(progress_run_id);
$("#uploadTemplate").show();
$("#btnAction").show();
$("#progressBarDiv").hide();
}, millisecondsToWait);
}
status.html(xhr.responseText);
}
});
});
</script>
Action method :-
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public void Upload(HttpPostedFileBase file, string txtname )
{
try
{
string attachmentFilePath = file.FileName;
string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);
}
catch (Exception ex)
{
}
}
Presumably you could kick off a setTimeout
call in mousedown
, and then cancel it in mouseup
(if mouseup
happens before your timeout completes).
However, looks like there is a plugin: longclick.
.spec.ts
file is used for unit testing
of your application.
If you don't to get it generated just use --spec=false
while creating new Component
. Like this
ng generate component --spec=false mycomponentName
In my case the error message was:
ASPNETCOMPILER : error CS1617: Invalid option '7.3' for /langversion; must be ISO-1, ISO-2, Default or an integer in range 1 to 6.
As stated in this GitHub issue, and this VS Developer Community post it seems to be a bug in an older Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package.
After upgrading this NuGet package to 3.6.0 the error still persisted in my web application.
I found out that I had to delete an old "bin\Roslyn" folder in my Web Application to make this work.
It seems that the newer Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package (3.6.0 in my case) does not bring a its own "Rosyln" folder anymore, and if present, that old "Roslyn" folder took precedence during compilation.
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Here the best way
First : make new xml
file in res
/drawable
name it rounded_edit_text
then paste this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#F9966B" />
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
Second: in res/layout copy and past following code (code of EditText
)
<EditText
android:id="@+id/txtdoctor"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/rounded_edit_text"
android:ems="10" >
<requestFocus />
</EditText>
\040
matches exactly the space character.
New Link
Escape sequences for Regex PHP
I used fake UserAgent.
How to use:
from fake_useragent import UserAgent
import requests
ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)
Output:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>
You need to set the "default value" for the date field to getdate()
. Any records inserted into the table will automatically have the insertion date as their value for this field.
The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.
Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.
As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):
These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.
// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
Should use ToUniversalTime() for the DateTime object.
If, like me, you don't have access to the puppet master and need to print debug logs to inspect variables on your puppet client machine, you can try writing to a file from your puppet code itself:
file { '/tmp/puppet_debug.log':
content => inline_template('<%= @variable_x.to_s %>'),
}
Just you need to desc with asc. Write the query like below. It will return the values in ascending order.
SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;
Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.
#!/usr/bin/env sh
KEYSTORE_FILE=/path/to/keystore.jks
KEYSTORE_PASS=changeit
import_cert() {
local HOST=$1
local PORT=$2
# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert
# delete the old alias and then import the new one
keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null
# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
-alias ${HOST} -file ${HOST}.cert \
-keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}
rm ${HOST}.cert
}
import_cert stackoverflow.com 443
import_cert www.google.com 443
import_cert 172.217.194.104 443 # google
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
For Python 3.7 or later,(2018-10-10), I have to combine both @Alejandro BR and SMNALLY's answer, coz @Alejandro forget to define wincl.
import os, os.path
import win32com.client
if os.path.exists('C:/Users/jz/Desktop/test.xlsm'):
excel_macro = win32com.client.DispatchEx("Excel.Application") # DispatchEx is required in the newest versions of Python.
excel_path = os.path.expanduser('C:/Users/jz/Desktop/test.xlsm')
workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
excel_macro.Application.Run("test.xlsm!Module1.Macro1") # update Module1 with your module, Macro1 with your macro
workbook.Save()
excel_macro.Application.Quit()
del excel_macro
I wouldn't recommend the HAVING
keyword for newbies, it is essentially for legacy purposes.
I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:
I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.
So I've taken a literal interpretation.
The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES
but it could be a VIEW
:
WITH PAYMENT_TALLIES (user_id, zip, tally)
AS
(
SELECT user_id, zip, COUNT(*) AS tally
FROM PAYMENT
GROUP
BY user_id, zip
)
SELECT DISTINCT *
FROM PAYMENT AS P
WHERE EXISTS (
SELECT *
FROM PAYMENT_TALLIES AS PT
WHERE P.user_id = PT.user_id
AND PT.tally > 1
);
If column is not NOT NULL
(nullable).
You just put NULL
instead of value in INSERT
statement.
In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".
Set MaintainScrollPositionOnPostBack="true"
in the page declaration:
<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
a wrapper is class which is used to communicate between two different application between different platform
As of Java-8, there are four variants of the setAll method which sets all elements of the specified array, using a provided generator function to compute each element.
Of those four overloads only three of them accept an array of primitives declared as such:
Examples of how to use the aforementioned methods:
// given an index, set the element at the specified index with the provided value
double [] doubles = new double[50];
Arrays.setAll(doubles, index -> 30D);
// given an index, set the element at the specified index with the provided value
int [] ints = new int[50];
Arrays.setAll(ints, index -> 60);
// given an index, set the element at the specified index with the provided value
long [] longs = new long[50];
Arrays.setAll(longs, index -> 90L);
The function provided to the setAll
method receives the element index and returns a value for that index.
you may be wondering how about characters array?
This is where the fourth overload of the setAll
method comes into play. As there is no overload that consumes an array of character primitives, the only option we have is to change the declaration of our character array to a type Character[]
.
If changing the type of the array to Character
is not appropriate then you can fall back to the Arrays.fill method.
Example of using the setAll
method with Character[]
:
// given an index, set the element at the specified index with the provided value
Character[] character = new Character[50];
Arrays.setAll(characters, index -> '+');
Although, it's simpler to use the Arrays.fill
method rather than the setAll
method to set a specific value.
The setAll
method has the advantage that you can either set all the elements of the array to have the same value or generate an array of even numbers, odd numbers or any other formula:
e.g.
int[] evenNumbers = new int[10];
Arrays.setAll(evenNumbers, i -> i * 2);
There's also several overloads of the parallelSetAll method which is executed in parallel, although it's important to note that the function passed to the parallelSetAll method must be side-effect free.
Conclusion
If your goal is simply to set a specific value for each element of the array then using the Arrays.fill
overloads would be the most appropriate option. However, if you want to be more flexible or generate elements on demand then using the Arrays.setAll
or Arrays.parallelSetAll
(when appropriate) would be the option to go for.
tracert
/traceroute
to find number of hopsStaticResource will be resolved on object construction.
DynamicResource will be evaluated and resolved every time control needs the resource.
You have a couple of choices. For one, you can use the os.path.getmtime
and os.path.getctime
functions:
import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))
Your other option is to use os.stat
:
import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))
Note: ctime()
does not refer to creation time on *nix systems, but rather the last time the inode data changed. (thanks to kojiro for making that fact more clear in the comments by providing a link to an interesting blog post)
At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload
maybe. Something like this:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function(){
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
There is a better solution than the accepted answer, specifically using data-* attributes. Setting the id to 1 will cause you issues if any other element on the page has id=1. Instead, you can do:
<button class="btn btn-primary" data-toggle="modal" data-target="#yourModalID" data-yourparameter="whateverYouWant">Load</button>
<script>
$('#yourModalID').on('show.bs.modal', function(e) {
var yourparameter = e.relatedTarget.dataset.yourparameter;
// Do some stuff w/ it.
});
</script>
I'm using the Hadoop Mincemeat module. I think this is a great example to take a note of:
import mincemeat
def mapfn(k,v):
for w in v:
yield 'sum',w
#yield 'count',1
def reducefn(k,v):
r1=sum(v)
r2=len(v)
print r2
m=r1/r2
std=0
for i in range(r2):
std+=pow(abs(v[i]-m),2)
res=pow((std/r2),0.5)
return r1,r2,res
Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop's map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).
Hadoop is a great example for using all the advantages of Generators.
You can use the following command:
svn status -q
According to svnbook:
With --quiet (-q), it prints only summary information about locally modified items.
WARNING: The output of this command only shows your modification. So I suggest to do a svn up
to get latest version of the file and then use svn status -q
to get the files you have modified.
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
edit your .env and add this line after mail config lines
MAIL_ENCRYPTION=""
Save and try to send email
You are trying to index into a scalar (non-iterable) value:
[y[1] for y in y_test]
# ^ this is the problem
When you call [y for y in test]
you are iterating over the values already, so you get a single value in y
.
Your code is the same as trying to do the following:
y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail
I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test]
.
If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:
[results.append(..., y) for y in y_test]
Or just use a for loop:
for y in y_test:
results.append(..., y)
Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.
For those not running a mac, or having a different setup and can't find this file, the file merely runs:
pip install --upgrade certifi
Hope that helps someone :)
In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.
Had to install latest intellij compatible with gradle 5+
There is an easy way to change the colors in Actionbar
Use ActionBar Generator and copy paste all file in your res
folder and change your theme in Android.manifest file.
Breakpoints and especially conditional breakpoints are your friends.
Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)
Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"
Or possibly this
Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."
Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver... if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH!
https://secure.php.net/manual/en/mysqli-stmt.bind-result.php
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");
Find more details in the Docs
Note that Date.getDate
only returns the day of the month. You can add a day by calling Date.setDate
and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
Since you haven't made any commits yet, you can save all your changes to the stash, create and switch to a new branch, then pop those changes back into your working tree:
git stash # save local modifications to new stash
git checkout -b topic/newbranch
git stash pop # apply stash and remove it from the stash list
Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.
Casting to a money or float first handles both the currency and scientific issues:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO
CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
DECLARE @IntValue bigint;
IF (ISNUMERIC(@Value) = 1)
IF (@Value like '%e%')
SET @IntValue = CAST(Cast(@Value as float) as bigint);
ELSE
SET @IntValue = CAST(CAST(@Value as money) as bigint);
ELSE
SET @IntValue = NULL;
RETURN @IntValue;
END
The function will fail if the number is bigger than a bigint.
If you want to return a different default value, leave this function so it is generic and replace the null afterwards:
SELECT IsNull(dbo.TryConvertInt('nan') , 1000);
I would probably build the link manually, like this:
<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>
FOO='BAR * BAR'
echo "$FOO"
serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.
Suppose that we have a form with this id : "myform".
the better solution is to make a FormData and send it:
var myform = document.getElementById("myform");
var fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
}
});
In my case i change mysql_fetch_assoc to mysql_fetch_array and solve. It takes 3 days to solve :-( and the other versions of my proyect run with fetch assoc.
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
You can make your pattern case insensitive by doing:
Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
You can use the following code:
Intent i = new Intent(OldActivity.this, NewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
You can simply use the HTML onwheel attribute.
This option have no effects on scrolling over other elements of the page.
And add a listener for all inputs don't work in inputs dynamically created posteriorly.
Aditionaly, you can remove the input arrows with CSS.
input[type="number"]::-webkit-outer-spin-button, _x000D_
input[type="number"]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
margin: 0;_x000D_
}_x000D_
input[type="number"] {_x000D_
-moz-appearance: textfield;_x000D_
}
_x000D_
<input type="number" onwheel="this.blur()" />
_x000D_
the mysqli_query
excepts 2 parameters , first variable is mysqli_connect
equivalent variable , second one is the query you have provided
$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);
$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
There is no way to automatically set CMAKE_PREFIX_PATH
in a way you want. I see following ways to solve this problem:
Put all libraries files in the same dir. That is, include/
would contain headers for all libs, lib/
- binaries, etc. FYI, this is common layout for most UNIX-like systems.
Set global environment variable CMAKE_PREFIX_PATH
to D:/develop/cmake/libs/libA;D:/develop/cmake/libs/libB;...
. When you run CMake, it would aautomatically pick up this env var and populate it's own CMAKE_PREFIX_PATH
.
Write a wrapper .bat script, which would call cmake
command with -D CMAKE_PREFIX_PATH=...
argument.
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
If you use style solution with colorButtonNormal, don't forget to inherit from Widget.AppCompat.Button.Colored so the ripple effect is working ;)
Like
<style name="CustomButtonStyle" parent="Widget.AppCompat.Button.Colored">
<item name="colorButtonNormal">@android:color/white</item>
</style>
Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.
Any Alpha-numeric value and "-" and "_" is valid. But, you should start the id name with any character between A-Z or a-z.
If you're on Chrome, Firefox or IE10 + why not extend the console and use
(function() {
console.dump = function(object) {
if (window.JSON && window.JSON.stringify)
console.log(JSON.stringify(object));
else
console.log(object);
};
})();
for a concise, cross-browser solution.
I found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.
Anyway, the behaviour I wanted was for set to use id
rather than hash
. As such I found mydict[id(mylist)] = mylist
instead of myset.add(mylist)
to offer the behaviour I wanted.
Use the SelectMany extension method
list = listOfList.SelectMany(x => x).ToList();
To skip .
& ..
, you can use Dir::each_child
.
Dir.each_child('/path/to/dir') do |filename|
puts filename
end
Dir::children
returns an array of the filenames.
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}
Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.
So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.
To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"
Then will generate directly p8 file.
I hope this will solve your issue.
Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/
Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
For positive numbers
unsigned int x, y, q;
To round up ...
q = (x + y - 1) / y;
or (avoiding overflow in x+y)
q = 1 + ((x - 1) / y); // if x != 0
As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned
$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml
If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.
You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.
The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.
http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
You don't need to find the file.
Only write this instruction on terminal:
git config --global --edit
Just use the atol()
function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *c = "5";
int d = atol(c);
printf("%d\n", d);
}
You can add the port in below methods.
Run -> Configurations section
In application.xml
add server.port=XXXX
I Use simply for my app:
using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object
...
private static void CreateShortcut()
{
string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop )
+ Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
var shell = new WshShell();
var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
//shortcut...
shortcut.Save();
}
No. HTML explicitly forbids nested forms.
From the HTML 5 draft:
Content model: Flow content, but with no form element descendants.
From the HTML 4.01 Recommendation:
<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
(Note the -(FORM) section).
If you have an index and value. Then you can add to Series as:
obj = Series([4,7,-5,3])
obj.index=['a', 'b', 'c', 'd']
obj['e'] = 181
this will add a new value to Series (at the end of Series).
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
There is no function exit equivalent to php die() in JS, if you are not using any function then you can simply use return;
return;
Try, the following code..
@Override
public String toString() {
return this.name();
}
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Templates (<template>
, or <ng-template>
since 4.x) are added as embedded views and get passed a context.
With let-col
the context property $implicit
is made available as col
within the template for bindings.
With let-foo="bar"
the context property bar
is made available as foo
.
For example if you add a template
<ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
See also this answer and ViewContainerRef#createEmbeddedView.
*ngFor
also works this way. The canonical syntax makes this more obvious
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
where NgFor
adds the template as embedded view to the DOM for each item
of items
and adds a few values (item
, index
, odd
) to the context.
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
Looks like you are using maven (src/main/java)
. In this case put the applicationContext.xml
file in the src/main/resources
directory. It will be copied in the classpath directory and you should be able to access it with
@ContextConfiguration("/applicationContext.xml")
From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".
So it's important that you add the slash when referencing the file in the root directory of the classpath.
If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).
Java has a special static method:
public static void main(String[] args) { ... }
which is executed in a class when the class is started with a java command line:
$ java Class
would execute said method in the class "Class" if it existed.
public void run() { ... }
is required by the Runnable interface, or inherited from the Thread class when creating new threads.
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
You can use this library to send email ,if having issue with local xampp,wamp...
class.phpmailer.php,class.smtp.php Write this code in file where your email function calls
include('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = "your email ID";
$mail->Password = "your email password";
$fromname = "From Name in Email";
$To = trim($email,"\r\n");
$tContent = '';
$tContent .="<table width='550px' colspan='2' cellpadding='4'>
<tr><td align='center'><img src='imgpath' width='100' height='100'></td></tr>
<tr><td height='20'> </td></tr>
<tr>
<td>
<table cellspacing='1' cellpadding='1' width='100%' height='100%'>
<tr><td align='center'><h2>YOUR TEXT<h2></td></tr/>
<tr><td> </td></tr>
<tr><td align='center'>Name: ".trim(NAME,"\r\n")."</td></tr>
<tr><td align='center'>ABCD TEXT: ".$abcd."</td></tr>
<tr><td> </td></tr>
</table>
</td>
</tr>
</table>";
$mail->From = "From email";
$mail->FromName = $fromname;
$mail->Subject = "Your Details.";
$mail->Body = $tContent;
$mail->AddAddress($To);
$mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low
$mail->Send();
Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...