After updating my entity framework model, I found this error infecting several files in my solution. I simply right clicked on my .edmx file and my TT file and click "Run Custom Tool" and that had me right again after a restart of Visual Studio 2012.
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
The format that works for me (in my ~/.hgrc file) is this
[ui]
username=Chris McCauley <[email protected]>
[auth]
repo.prefix = https://server/repo_path
repo.username = username
repo.password = password
You can configure as many repos as you want by adding more triplets of prefix,username, password by prepending a unique tag.
This only works in Mercurial 1.3 and obviously your username and password are in plain text - not good.
Mercurial fully supports SSH so we can take advantage of SSH's ability to log into a server without a password - you do a once off configuration to provide a self-generated certificate. This is by far the safest way to do what you want.
You can find more information on configuring passwordless login here
If you want a secure option, but aren't familiar with SSH, why not try this?
From the docs ...
The extension prompts for the HTTP password on the first pull/push to/from given remote repository (just like it is done by default), but saves the password (keyed by the combination of username and remote repository url) in the password database. On the next run it checks for the username in .hg/hgrc, then for suitable password in the password database, and uses those credentials if found.
There is more detailed information here
To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet. I am currently implemented it for 2D view on my site here: https://papercraft-maker.com
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description = 'Refund'
GROUP BY client_id
PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description||'' = 'Refund'
GROUP BY client_id
This should work.
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
k_cleaned = []
for ele in k:
if set(ele) not in [set(x) for x in k_cleaned]:
k_cleaned.append(ele)
print(k_cleaned)
# output: [[1, 2], [4], [5, 6, 2], [3]]
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
you have to float
your image container as follows:
HTML
<div id="container">
<div id="floated">...some other random text</div>
...
some random text
...
</div>
CSS
#container{
width: 400px;
background: yellow;
}
#floated{
float: left;
width: 150px;
background: red;
}
FIDDLE
With Docmosis or JODReports you could feed your HTML and Javascript to the document render process which could produce PDF or doc or other formats. The conversion underneath is performed by OpenOffice so results will be dependent on the OpenOffice import filters. You can try manually by saving your web page to a file, then loading with OpenOffice - if that looks good enough, then these tools will be able to give you the same result as a PDF.
.net core
using System.Text.Json;
var jsonStr = JsonSerializer.Serialize(MyObject)
var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);
For more information about excluding properties and nulls check out This Microsoft side
The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.
Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.
You can use the DBMS_ALERT
package as follows:
CREATE OR REPLACE FUNCTION sleep(seconds IN NUMBER) RETURN NUMBER
AS
PRAGMA AUTONOMOUS_TRANSACTION;
message VARCHAR2(200);
status INTEGER;
BEGIN
DBMS_ALERT.WAITONE('noname', message, status, seconds);
ROLLBACK;
RETURN seconds;
END;
SELECT sleep(3) FROM dual;
Not sure if the most efficient way, but this worked for me:
from pyspark.sql.functions import col
df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])
The trick is in:
[col('a.'+xx) for xx in a.columns] : all columns in a
[col('b.other1'),col('b.other2')] : some columns of b
If you want to set to a new color or prevent the change of the color of a specific link after visiting it, add inside the tag of that link:
<a style="text-decoration:none; color:#ff0000;" href="link.html">test link</a>
Above the color is #ff0000 but you can make it anything you'd like.
Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).
Some interesting excerpts from the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from/etc/bash.bashrc
and~/.bashrc
, if these files exist. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of/etc/bash.bashrc
and~/.bashrc
.
So have a look at /etc/profile
or /etc/bash.bashrc
, these files are the right places for global settings. Put something like this in them to set up an environement variable:
export MY_VAR=xxx
A more generic solution for might be the following.
extendDf <- function (df, n) {
withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
nr <- nrow (df)
colNames <- names(df)
for (c in 1:length(colNames)) {
if (is.factor(df[,c])) {
col <- vector (mode='character', length = nr+n)
col[1:nr] <- as.character(df[,c])
col[(nr+1):(n+nr)]<- rep(col[1], n) # to avoid extra levels
col <- as.factor(col)
} else {
col <- vector (mode=mode(df[1,c]), length = nr+n)
class(col) <- class (df[1,c])
col[1:nr] <- df[,c]
}
if (c==1) {
newDf <- data.frame (col ,stringsAsFactors=withFactors)
} else {
newDf[,c] <- col
}
}
names(newDf) <- colNames
newDf
}
The function extendDf() extends a data frame with n rows.
As an example:
aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
# l i n c t
# 1 TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00
system.time (eDf <- extendDf (aDf, 100000))
# user system elapsed
# 0.009 0.002 0.010
system.time (eDf <- extendDf (eDf, 100000))
# user system elapsed
# 0.068 0.002 0.070
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).
You should better use the errbar
function from the Hmisc
package:
d = data.frame(
x = c(1:5)
, y = c(1.1, 1.5, 2.9, 3.8, 5.2)
, sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)
##install.packages("Hmisc", dependencies=T)
library("Hmisc")
# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)
# new plot (adjusts Yrange automatically)
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)
Edit file '/usr/share/phpmyadmin/libraries/sql.lib.php' Replace: (make backup)
"|| (count($analyzed_sql_results['select_expr'] == 1)
&&($analyzed_sql_results['select_expr'][0] == '*')))
&& count($analyzed_sql_results['select_tables']) == 1;"
With:
"|| (count($analyzed_sql_results['select_expr']) == 1)
&& ($analyzed_sql_results['select_expr'][0] == '*')
&& (count($analyzed_sql_results['select_tables']) == 1));"
Like the comments suggest, the solution is to use nested spans/rows.
<div class="container">
<div class="row">
<div class="span4">1</div>
<div class="span8">
<div class="row">
<div class="span4">2</div>
<div class="span4">3</div>
</div>
<div class="row">
<div class="span4">4</div>
<div class="span4">5</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">6</div>
<div class="span4">7</div>
<div class="span4">8</div>
</div>
</div>
ProgressBar is very simple and easy to use, i am intending to make this same as simple progress dialog. first step is that you can make xml layout of the dialog that you want to show, let say we name this layout
layout_loading_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ProgressBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="center"
android:text="Please wait! This may take a moment." />
</LinearLayout>
next step is create AlertDialog which will show this layout with ProgressBar
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();
now all that is left is to show and hide this dialog in our click events like this
dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog
and thats it, it should work, as you can see it is farely simple and easy to implement ProgressBar instead of ProgressDialog. now you can show/dismiss this dialog box in either Handler or ASyncTask, its up to your need
this simple script worked for me.
<?php
foreach($_FILES as $file){
//echo $file['name'];
echo $file['tmp_name'].'</br>';
move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}
?>
Simple and not time consuming answer with an example relevant to the question asked Follow this example:
user = [{"name": "Dough", "age": 55},
{"name": "Ben", "age": 44},
{"name": "Citrus", "age": 33},
{"name": "Abdullah", "age":22},
]
print(sorted(user, key=lambda el: el["name"]))
print(sorted(user, key= lambda y: y["age"]))
Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code
print(sorted(user, key=lambda el: el["name"]))
Results to:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Ben', 'age': 44},
{'name': 'Citrus', 'age': 33},
{'name': 'Dough', 'age': 55}]
sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.
The second print code
print(sorted(user, key= lambda y: y["age"]))
Result:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Citrus', 'age': 33},
{'name': 'Ben', 'age': 44},
{'name': 'Dough', 'age': 55}]
sorts by age, and hence the list returns by ascending order of age.
Try this code for better understanding.
You need to pass the values of the dict into the Bike
constructor before using like that. Or, see the namedtuple
-- seems more in line with what you're trying to do.
I am facing the same issue on Xcode 7.3 and my device version is iOS 10
.
This error is shown when your Xcode
is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.
We can solve this issue by following the below steps:-
- Open Finder select Applications
- Right click on Xcode 8, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
- Copy the 10.0 folder (or above for later version).
- Back in Finder select Applications again
- Right click on Xcode 7.3, select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"
- Paste the 10.0 folder
If everything worked properly, your Xcode
has a new developer disk image. Close the finder now, and quit your Xcode
. Open your Xcode
and the error will be gone. Now you can connect your latest device to old Xcode
versions.
Thanks
Use named parameters for readability and to avoid confusions.
@Html.ActionLink(
linkText: "Click Here",
actionName: "Action",
controllerName: "Home",
routeValues: new { Identity = 2577 },
htmlAttributes: null)
To see the dynamic SQL generated, change to text mode (shortcut: Ctrl-T), then use SELECT
PRINT LEN(@Query) -- Prints out 4273, which is correct as far as I can tell
--SET NOCOUNT ON
SELECT @Query
As for sp_executesql
, try this (in text mode), it should show the three aaaaa...
's the middle one being the longest with 'SELECT ..' added. Watch the Ln... Col..
indicator in the status bar at bottom right showing 4510 at the end of the 2nd output.
declare @n nvarchar(max)
set @n = REPLICATE(convert(nvarchar(max), 'a'), 4500)
SET @N = 'SELECT ''' + @n + ''''
print @n -- up to 4000
select @n -- up to max
exec sp_Executesql @n
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
<asp:TextBox runat="server" ID="txtPassword" placeholder="Password">
This will work you might some time feel that it is not working due to Intellisence not showing placeholder
In vi, do a :%s/^M//g
To get the ^M
hold the CTRL key, press V then M (Both while holding the control key) and the ^M
will appear. This will find all occurrences and replace them with nothing.
As described here for a post request :
var http = require('http');
var options = {
host: 'www.host.com',
path: '/',
port: '80',
method: 'POST'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();
Because that's not what strip()
does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.
You could do:
name= name.replace('(', '').replace(')', '').replace ...
or:
name= ''.join(c for c in name if c not in '(){}<>')
or maybe use a regex:
import re
name= re.sub('[(){}<>]', '', name)
The onselect
must be onclick
. This will work for keyboard users.
I would also recommend adding <label>
tags to the text of "Day", "Month", and "Year" to make them easier to click on. Example code:
<input id="day" name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/><label for="day">Day</label>
I would also recommend removing the spaces between the attribute onclick
and the value, although it can be parsed by browsers:
<input name="calendarSelection" type="radio" onclick = "go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
Should be:
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')"/>Day
Now with Java EE 7 you can find the resource more easily with
InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");
https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--
$.each(myobject, function(key, element) {
alert('key: ' + key + '\n' + 'value: ' + element);
});
This does the work for me. :)
Simple solution to drop all the table at once from terminal.
This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.
Worked for Server version: 5.6.38 MySQL Community Server (GPL)
Steps I followed:
1. generate drop query using concat and group_concat.
2. use database
3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;),
4. copy the query generated from step 1
5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
6. run show table
MySQL shell
$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0; Query OK, 0 rows affected (0.00 sec)
// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)
mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW tables;
Empty set (0.01 sec)
mysql>
Since macOS Big Sur and IntelliJ IDEA 2020.3.2 you can use "open projects in tabs on macOS Big Sur" feature. To use it, you have to enable this feature in your system settings:
System Preferences -> General -> Prefer tabs [always] when opening documents
After this step, when you will try to open second project in IntelliJ, choose New Window
(yes, New Window
, not This Window
).
It should result with opening new project in same window, but in the new card:
If you want to use bootstrap online and your application has access to the internet you can add
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');
Into you'r main style.css file. and its the simplest way.
Reference : angular.io
Note. This solution loads bootstrap from unpkg website and it need to have internet access.
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
A comprehansive comparison between diffreent formats made by me in this post- https://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/
Just one sample from the post-
Another approach depending on how you are changing the div. If you are using JQuery to change a div's contents with its html() method, you can extend that method and call a registration function each time you put html into a div.
(function( $, oldHtmlMethod ){
// Override the core html method in the jQuery object.
$.fn.html = function(){
// Execute the original HTML method using the
// augmented arguments collection.
var results = oldHtmlMethod.apply( this, arguments );
com.invisibility.elements.findAndRegisterElements(this);
return results;
};
})( jQuery, jQuery.fn.html );
We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.
For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery's site.
Based on average distance for degress in the Earth.
1° = 111km;
Converting this for radians and dividing for meters, take's a magic number for the RAD, in meters: 0.000008998719243599958;
then:
const RAD = 0.000008998719243599958;
Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(long1 - long2, 2)) / RAD;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
I think you should try
data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};
ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}
I needed to remove special characters from an XML file. Here's how I did it. char.ToString() is the hero in this code.
string item = "<item type="line" />"
char DC4 = (char)0x14;
string fixed = item.Replace(DC4.ToString(), string.Empty);
Your return data
approach is correct, that's an example of promise chaining. If you return a promise from your .then()
callback, JavaScript will resolve that promise and pass the data to the next then()
callback.
Just be careful and make sure you handle errors with .catch()
. Promise.all()
rejects as soon as one of the promises in the array rejects.
In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db
The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!
Totally depends on your usage scenario I suppose.
If you only want find missing values in b, you can do:
List toReturn = new ArrayList(a);
toReturn.removeAll(b);
return toReturn;
If you want to find out values which are present in either list you can execute upper code twice. With changed lists.
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
The best way to retrieve your public folder path from your Laravel config is the function:
$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);
There is no need to have all the variables, but this is just for a demonstrative purpose.
Hope this helps, GRnGC
You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.
function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}
And this is the
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>
Now all you need to do is call invert() We do this when the image is clicked.
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
We use this on our website
C++03 (Source: Iterator Invalidation Rules (C++03))
Sequence containers
vector
: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.2.4.3/1]deque
: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.2.1.3/1]list
: all iterators and references unaffected [23.2.2.3/1]Associative containers
[multi]{set,map}
: all iterators and references unaffected [23.1.2/8]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerSequence containers
vector
: every iterator and reference after the point of erase is invalidated [23.2.4.3/3]deque
: all iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (in which case only iterators and references to the erased members are invalidated) [23.2.1.3/4]list
: only the iterators and references to the erased element is invalidated [23.2.2.3/3]Associative containers
[multi]{set,map}
: only iterators and references to the erased elements are invalidated [23.1.2/8]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containervector
: as per insert/erase [23.2.4.2/6]deque
: as per insert/erase [23.2.1.2/1]list
: as per insert/erase [23.2.2.2/1]Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.1/11]
It's not clear in C++2003 whether "end" iterators are subject to the above rules; you should assume, anyway, that they are (as this is the case in practice).
The rules for invalidation of pointers are the sames as the rules for invalidation of references.
Each class implementing IList has a method Contains(Object value). And so does System.Array.
maybe this works:
$str='\n';
echo str_replace('\n','',$str);
You missed a space: db.execSQL("delete * from " + TABLE_NAME);
Also there is no need to even include *
, the correct query is:
db.execSQL("delete from "+ TABLE_NAME);
Yes, you can declare your new bounds object.
var bounds = new google.maps.LatLngBounds();
Then for each marker, extend your bounds object:
bounds.extend(myLatLng);
map.fitBounds(bounds);
I came across several answers in SO and at the end I realized that my error was that I had misspelled "Html.TextBoxFor." In my case what I wrote was "Html.TextboxFor." I did not uppercase the B in TextBoxFor. Fixed that and voilà. Problem solved. I hope this helps someone.
A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.
import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)
I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.
It doesn't need to be complicated:
val = df.loc[df.wd==1, 'col_name'].values[0]
This is another way to specify the range of the bit-vector.
x +: N, The start position of the vector is given by x and you count up from x by N.
There is also
x -: N, in this case the start position is x and you count down from x by N.
N is a constant and x is an expression that can contain iterators.
It has a couple of benefits -
It makes the code more readable.
You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Try match
:
df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]
name value
2 b TRUE
3 c FALSE
1 a TRUE
4 d FALSE
It will work as long as your target
contains exactly the same elements as df$name
, and neither contain duplicate values.
From ?match
:
match returns a vector of the positions of (first) matches of its first argument
in its second.
Therefore match
finds the row numbers that matches target
's elements, and then we return df
in that order.
I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts. Best solution I have found so far: https://github.com/XamlAnimatedGif/WpfAnimatedGif
You can install it with NuGet
PM> Install-Package WpfAnimatedGif
and to use it, at a new namespace to the Window where you want to add the gif image and use it as below
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
Title="MainWindow" Height="350" Width="525">
<Grid>
<!-- EXAMPLE USAGE BELOW -->
<Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
The package is really neat, you can set some attributes like below
<Image gif:ImageBehavior.RepeatBehavior="3x"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
and you can use it in your code as well:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
EDIT: Silverlight support
As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use github.com/XamlAnimatedGif/XamlAnimatedGif
I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.
I have done the following using OpenCV 3.0.0 and python:
import cv2
#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img)
#-----Converting image to LAB Color model-----------------------------------
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)
#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)
#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)
#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)
#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)
#_____END_____#
You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.
The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
You can use the following function to highlight any word in your text.
function color_word(text_id, word, color) {
words = $('#' + text_id).text().split(' ');
words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });
new_words = words.join(' ');
$('#' + text_id).html(new_words);
}
Simply target the element that contains the text, choosing the word to colorize and the color of choice.
Here is an example:
<div id='my_words'>
This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.
</div>
Usage,
color_word('my_words', 'possible', 'hotpink')
str() is used for creating output for end user while repr() is used for debuggin development.And it's represent the official of object.
Example:
>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'
From output we see that repr() shows the official representation of date object.
There is a new ISO8601DateFormatter
class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.
Swift 3.0
extension Date {
var iso8601: String {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
} else {
var buffer = [CChar](repeating: 0, count: 25)
var time = time_t(self.timeIntervalSince1970)
strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
return String(cString: buffer)
}
}
}
See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:
shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
This didn't work
=IIf((CountRows("ScannerStatisticsData") = 0),False,True)
but this did and I can't really explain why
=IIf((CountRows("ScannerStatisticsData") < 1),False,True)
guess SSRS doesn't like equal comparisons as much as less than.
When the directory already exist:
mkdir -m 777 /path/to/your/dir
When the directory does not exist and you want to create the parent directories:
mkdir -m 777 -p /parent/dirs/to/create/your/dir
Okay, how about a CSS answer! We use display: table
. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.
body { display: table; }
div { display: table-row; }
#content {
width:450px;
margin:0 auto;
text-align: center;
background-color: blue;
color: white;
height: 100%;
}
Magic commands such as
%matplotlib qt
work in the iPython console and Notebook, but do not work within a script.
In that case, after importing:
from IPython import get_ipython
use:
get_ipython().run_line_magic('matplotlib', 'inline')
for inline plotting of the following code, and
get_ipython().run_line_magic('matplotlib', 'qt')
for plotting in an external window.
Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.
Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.
The best solution i have found, which is compatible with devices having API level <11
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
This solution requires Android support library
Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.
I hope its helps
If we talk about SessionFactory.openSession()
And If we talk about SessionFactory.getCurrentSession()
No need to touch hot_standby_feedback
. As others have mentioned, setting it to on
can bloat master. Imagine opening transaction on a slave and not closing it.
Instead, set max_standby_archive_delay
and max_standby_streaming_delay
to some sane value:
# /etc/postgresql/10/main/postgresql.conf on a slave
max_standby_archive_delay = 900s
max_standby_streaming_delay = 900s
This way queries on slaves with a duration less than 900 seconds won't be cancelled. If your workload requires longer queries, just set these options to a higher value.
Simple and with little changes. And also hide load more when entire list is loaded.
jsFiddle here.
$(document).ready(function () {
// Load the first 3 list items from another HTML file
//$('#myList').load('externalList.html li:lt(3)');
$('#myList li:lt(3)').show();
$('#showLess').hide();
var items = 25;
var shown = 3;
$('#loadMore').click(function () {
$('#showLess').show();
shown = $('#myList li:visible').size()+5;
if(shown< items) {$('#myList li:lt('+shown+')').show();}
else {$('#myList li:lt('+items+')').show();
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
$('#myList li').not(':lt(3)').hide();
});
});
If you want to make a change global to the whole notebook:
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]
A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)
A bit of a different approach here.
Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types
protocol Number
{
func +(l: Self, r: Self) -> Self
func -(l: Self, r: Self) -> Self
func >(l: Self, r: Self) -> Bool
func <(l: Self, r: Self) -> Bool
}
extension Double : Number {}
extension Float : Number {}
extension Int : Number {}
infix operator += {}
func += <T:Number> (inout left: T, right: T)
{
left = left + right
}
prefix operator +/ {}
prefix func +/ <T:Number>(ar:[T]?) -> T?
{
switch true
{
case ar == nil:
return nil
case ar!.isEmpty:
return nil
default:
var result = ar![0]
for n in 1..<ar!.count
{
result += ar![n]
}
return result
}
}
use like so:
let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]
+/nmbrs // 548.1
+/intarr // 145
(updated for Swift 2.2, tested in Xcode Version 7.3)
From a book named OCA Java SE 7 Programmer I:
The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Try using an empty collapse argument within the paste function:
paste(sdata, collapse = '')
Difference between driver.close() & driver.quit()
driver.close – It closes the the browser window on which the focus is set.
driver.quit – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
For Windows users:
Set-ExecutionPolicy RemoteSigned -scope CurrentUser
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
scoop install gradle
Typically this would be handled by your Subversion server administrator. If that's you and you are using the built-in authentication, then edit your [repository]\conf\passwd
file on your Subversion server machine.
Follow these steps:
Next time you attempt an action that requires credentials you'll be asked for them.
If you're using the command-line svn.exe
use the --no-auth-cache
option so that you can specify alternate credentials without having them cached against your Windows user.
There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !
If maven works through proxy but not some of the plugins it is invoking, try setting JAVA_TOOL_OPTIONS
as well with -Dhttp*.proxy*
settings.
If you have already JAVA_OPTS
just do
export JAVA_TOOL_OPTIONS=$JAVA_OPTS
Here is an short extension for 3 or more tables to the answer of D Stanley:
INSERT INTO other_table (name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table_1 p
INNER JOIN table_2 a ON a.id = p.id
INNER JOIN table_3 b ON b.id = p.id
...
INNER JOIN table_n x ON x.id = p.id
You can also do it one line:
int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));
Reading from order of execution
findViewById(R.id.button1)
((Button)______)
to cast the View
as a Button
.GetText()
to get the text entry from Button.toString()
to convert the Character Varying to a String.ReplaceAll()
with "[\\D]"
to replace all Non Digit Characters with "" (nothing)Integer.parseInt()
grab and return an integer out of the Digit-only string.This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
Replace
volume = (4 / 3) Math.PI * Math.pow(radius, 3);
With:
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
Like it was saying previously - you can access any parameters by using injection container and use its parameter property.
"Symfony - Working with Container Service Definitions" is a good article about it.
Consider using a the transform: rotate(-90deg) style on an element. See http://www.w3schools.com/cssref/css3_pr_transform.asp
Example, In your css
.verticaltext_content {
position: relative;
transform: rotate(-90deg);
right:90px; //These three positions need adjusting
bottom:150px; //based on your actual chart size
width:200px;
}
Add a space fudge factor to the Y Axis scale so the text has room to render in your javascript.
scaleLabel: " <%=value%>"
Then in your html after your chart canvas put something like...
<div class="text-center verticaltext_content">Y Axis Label</div>
It is not the most elegant solution, but worked well when I had a few layers between the html and the chart code (using angular-chart and not wanting to change any source code).
There's a plugin for jQuery to get GET params called .getUrlParams
For POST the only solution is echoing the POST into a javascript variable using PHP, like Moran suggested.
My images were not getting displayed even after putting them in the correct folder, problem was they did not have the right permission, I changed the permission to read write execute. I used chmod 777 image.png. All worked then, images were getting displayed. :)
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
For selecting within single quotes use vi'
.
For selecting within parenthesis use vi(
.
Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).
One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream
and a FileOutputStream
, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.
I don't see anyone mentioning the elephant in the room here, so I think it's up to me :)
JavaScript is a functional language. As more and more people do more advanced things with JS, especially leveraging the finer points of jQuery, Dojo, and other frameworks, FP will be introduced by the web-developer's back-door.
In conjunction with closures, FP makes JS code really light, yet still readable.
Cheers, PS
If you are worried at all about speed, you should instead use:
mag = np.sqrt(x.dot(x))
Here are some benchmarks:
>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372
EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:
In [1]: import numpy as np
In [2]: a = np.arange(1200.0).reshape((-1,3))
In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop
In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop
In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True
As of python 3.2, using only standard library functions:
u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)
t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'
Just need to use l_tm - u_tm
or u_tm - l_tm
depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.
And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.
If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"
You may try one of these methods:
Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.
Use double quote for your password: like - "Abc@%$67eSDu"
I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create
, not having point.c will cause the compilation to fail.
I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:
gcc point.c testpoint.c
As others have pointed out, you also need to remove one of your main
functions, since you can only have one.
You can simple put like this
public sealed class Employee
{
public int Id { get; set; } = 101;
}
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
When elements are positioned outside the normal flow, they can overlap other elements.
according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp
In your component
let today: string;
ngOnInit() {
this.today = new Date().toISOString().split('T')[0];
}
and in your html file
<input name="date" [(ngModel)]="today" type="date" required>
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
If you would like to edit the property value with two way binding:
<tr ng-repeat="(key, value) in data">
<td>{{key}}<input type="text" ng-model="data[key]"></td>
</tr>
string content = System.IO.File.ReadAllText( @"C:\file.txt" );
If a <script>
has a src
then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
<script>
to load the external scripta <script>
to hold your inline code (with the call to the function in the external script)
Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.
String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
.replace("-----END RSA PRIVATE KEY-----", "");
// Base64 decode the data
byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);
try {
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
.fromByteArray(encodedPrivateKey);
Enumeration<?> e = primitive.getObjects();
BigInteger v = ((DERInteger) e.nextElement()).getValue();
int version = v.intValue();
if (version != 0 && version != 1) {
throw new IllegalArgumentException("wrong version for RSA private key");
}
/**
* In fact only modulus and private exponent are in use.
*/
BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException(e);
}
The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.
Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.
If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..
html:
<div id="a">A</div>
<div id="b">B</div>
css:
#a, #b {
width: 49%;
display: inline-block;
}
#a {background-color: red;}
#b {background-color: blue;}
echo '<pre>';
foreach($data as $entry){
foreach($entry as $entry2){
echo $entry2.'<br />';
}
}
Maybe not a direct answer to the question, but a recent addition to the official documentation describes how jQuery can be used to disable transitions entirely just by:
$.support.transition = false
Setting the .collapsing
CSS transitions to none as mentioned in the accepted answer removed the animation. But this — in Firefox and Chromium for me — creates an unwanted visual issue on collapse of the navbar.
For instance, visit the Bootstrap navbar example and add the CSS from the accepted answer:
.collapsing {
-webkit-transition: none;
transition: none;
}
What I currently see is when the navbar collapses, the bottom border of the navbar momentarily becomes two pixels instead of one, then disconcertingly jumps back to one. Using jQuery, this artifact doesn't appear.
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample
<form id="formAddName">
<fieldset>
<legend>Add Name </legend>
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" />
<button>Add</button>
</fieldset>
</form>
<ol id="demo"></ol>
<script>
var list = document.getElementById('demo');
var entry = document.getElementById('formAddName');
entry.onsubmit = function(evt) {
evt.preventDefault();
var firstName = document.getElementById('firstName').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
}
</script>
Potentially for a different question, but I'm providing my version of @Alvero's answer (using unidecode). I want to do a "regular" strip on my strings, i.e. the beginning and end of my string for whitespace characters, and then replace only other whitespace characters with a "regular" space, i.e.
"Ceñía?mañana????"
to
"Ceñía mañana"
,
def safely_stripped(s: str):
return ' '.join(
stripped for stripped in
(bit.strip() for bit in
''.join((c if unidecode(c) else ' ') for c in s).strip().split())
if stripped)
We first replace all non-unicode spaces with a regular space (and join it back again),
''.join((c if unidecode(c) else ' ') for c in s)
And then we split that again, with python's normal split, and strip each "bit",
(bit.strip() for bit in s.split())
And lastly join those back again, but only if the string passes an if
test,
' '.join(stripped for stripped in s if stripped)
And with that, safely_stripped('????Ceñía?mañana????')
correctly returns 'Ceñía mañana'
.
Not really.
Depending on what you actually need, one possibility may be to set o
as the prototype of a new object.
var o = {};
(function(x){
var obj = Object.create( x );
obj.foo = 'foo';
obj.bar = 'bar';
})(o);
alert( o.foo ); // undefined
So any properties you add to obj
will be not be added to o
. Any properties added to obj
with the same property name as a property in o
will shadow the o
property.
Of course, any properties added to o
will be available from obj
if they're not shadowed, and all objects that have o
in the prototype chain will see the same updates to o
.
Also, if obj
has a property that references another object, like an Array, you'll need to be sure to shadow that object before adding members to the object, otherwise, those members will be added to obj
, and will be shared among all objects that have obj
in the prototype chain.
var o = {
baz: []
};
(function(x){
var obj = Object.create( x );
obj.baz.push( 'new value' );
})(o);
alert( o.baz[0] ); // 'new_value'
Here you can see that because you didn't shadow the Array at baz
on o
with a baz
property on obj
, the o.baz
Array gets modified.
So instead, you'd need to shadow it first:
var o = {
baz: []
};
(function(x){
var obj = Object.create( x );
obj.baz = [];
obj.baz.push( 'new value' );
})(o);
alert( o.baz[0] ); // undefined
;WITH
CteProductLookup(ProductId, oid)
AS
...
In react, state will not change until you do it by using this.setState({});
.
That is why your console message showing old values.
If you using webpack in your application, you can simply set it there, using DefinePlugin
...
So in your plugin
section, set the NODE_ENV to production
:
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
})
]
If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .
Example:
views.py:
def my_view(request, interview_pk):
interview = Interview.objects.get(pk=interview_pk)
all_rounds = interview.round_set.order_by('created_at')
all_round_names = [rnd.name for rnd in all_rounds]
form = forms.AddRatingForRound(all_round_names)
return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})
forms.py
class AddRatingForRound(forms.ModelForm):
def __init__(self, round_list, *args, **kwargs):
super(AddRatingForRound, self).__init__(*args, **kwargs)
self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))
class Meta:
model = models.RatingSheet
fields = ('name', )
template:
<form method="post">
{% csrf_token %}
{% if interview %}
{{ interview }}
{% endif %}
{% if rounds %}
<hr>
{{ form.as_p }}
<input type="submit" value="Submit" />
{% else %}
<h3>No rounds found</h3>
{% endif %}
</form>
The ideal solution would be to use inline-block
for the columns instead of floating. I think the browser support is pretty good if you follow (a) apply inline-block
only to elements that are normally inline (eg span
); and (b) add -moz-inline-box
for Firefox.
Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress
, write the name of your installed instance (by default it's .\SQLEXPRESS
for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI
.
I bet the onchange
is getting fired after the onselect
, essentially re-enabling the select.
I'd recommend you implement only the onchange
, inspect which option has been selected, and enable or disabled based on that.
To get the value of the selected option use:
document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].value
Which will yield .. nothing since you haven't specified a value for each option .. :(
<select id="mySelect" onChange="enable();">
<option onSelect="disable();" value="no">No</option>
<option onSelect="enable();" value="yes">Yes</option>
</select>
Now it will yield "yes"
or "no"
one way...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
If you are using form control then the simplest way to do this:
this.FormName.get('ControlName').setValue(value);
Definitely makes a difference: How To… Speed up Gradle build time
Just create a file named gradle.properties
in the following directory:
/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)
Add this line to the file:
org.gradle.daemon=true
It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.
The query will return all rows that
(common identical rows will be excluded).
"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.
select pk
,decode(a.rowid, null, null, 'A') as a
,decode(b.rowid, null, null, 'B') as b
,a.col1, b.col1
,a.col2, b.col2
,a.col3, b.col3
,...
from table1 a
full outer
join table2 b using(pk)
where decode(a.col1, b.col1, 1, 0) = 0
or decode(a.col2, b.col2, 1, 0) = 0
or decode(a.col3, b.col3, 1, 0) = 0
or ...;
Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.
with a as(
select 0 as col1 from dual union all
select 1 as col1 from dual union all
select null as col1 from dual
)
,b as(
select 1 as col1 from dual union all
select 2 as col1 from dual union all
select null as col1 from dual
)
select a.col1
,b.col1
,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2
from a,b
order
by a.col1
,b.col1;
col1 col1_1 approach_1 approach_2
==== ====== ========== ==========
0 1 Different Different
0 2 Different Different
0 null Different Same <---
1 1 Same Same
1 2 Different Different
1 null Different Same <---
null 1 Different Same <---
null 2 Different Same <---
null null Same Same
When making a toast in fragment do as following:
Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();
When class is extending fragment it is necessary to use getActivity() since fragment is a subclass of activity.
Cheerse
This site might help you out with all of that:
printAccountSummary: function()
{return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method
Prints:
Welcome!
Your balance is currently $1000 and your interest rate is 1%.
There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features
Features:
I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:
function showMessage(msg) {
alert(msg);
};
<input type="button" value="ahaha" onclick="showMessage('msg');" />
UPDATE: With a small change to how your method is defined I can get it to work:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">
// define the function within the global scope
$.fn.MessageBox = function(msg) {
alert(msg);
};
// or, if you want to encapsulate variables within the plugin
(function($) {
$.fn.MessageBoxScoped = function(msg) {
alert(msg);
};
})(jQuery); //<-- make sure you pass jQuery into the $ parameter
</script>
</head>
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>
Read the existing answers first, this is just an addendum.
Notice that you can raise exceptions with or without arguments.
Example:
raise SystemExit
exits the program but you might want to know what happened.So you can use this.
raise SystemExit("program exited")
this will print "program exited" to stderr before closing the program.
The above is correct if we assume that arrays can contain only strings, but arrays can contain other arrays as well. Also in_array() function can accept an array for $needle, so strtolower($needle) is not going to work if $needle is an array and array_map('strtolower', $haystack) is not going to work if $haystack contains other arrays, but will result in "PHP warning: strtolower() expects parameter 1 to be string, array given".
Example:
$needle = array('p', 'H');
$haystack = array(array('p', 'H'), 'U');
So i created a helper class with the releveant methods, to make case-sensitive and case-insensitive in_array() checks. I am also using mb_strtolower() instead of strtolower(), so other encodings can be used. Here's the code:
class StringHelper {
public static function toLower($string, $encoding = 'UTF-8')
{
return mb_strtolower($string, $encoding);
}
/**
* Digs into all levels of an array and converts all string values to lowercase
*/
public static function arrayToLower($array)
{
foreach ($array as &$value) {
switch (true) {
case is_string($value):
$value = self::toLower($value);
break;
case is_array($value):
$value = self::arrayToLower($value);
break;
}
}
return $array;
}
/**
* Works like the built-in PHP in_array() function — Checks if a value exists in an array, but
* gives the option to choose how the comparison is done - case-sensitive or case-insensitive
*/
public static function inArray($needle, $haystack, $case = 'case-sensitive', $strict = false)
{
switch ($case) {
default:
case 'case-sensitive':
case 'cs':
return in_array($needle, $haystack, $strict);
break;
case 'case-insensitive':
case 'ci':
if (is_array($needle)) {
return in_array(self::arrayToLower($needle), self::arrayToLower($haystack), $strict);
} else {
return in_array(self::toLower($needle), self::arrayToLower($haystack), $strict);
}
break;
}
}
}
You can remove it with command sudo docker rm YOUR_CONTAINER_ID
, then run a new container with sudo docker run ...
;
or restart an existing container with sudo docker start YOUR_CONTAINER_ID
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
System.Collections.Generic.Dictionary<TKey, TValue>
and System.Collections.Hashtable
classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.
Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.
The primary structural difference between them is that Dictionary
relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable
uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).
There is little benefit to use Hashtable
class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>
.
I know it's a little off-topic, but following up with the solution presented by Jonas Bøhmer, actually I think that MOD is the best solution to your example.
If your intention was to limit the result to one digit, MOD is the best approach to achieve it.
ie. Let's suppose that VLOOKUP(A1, B:B, 1, 0) returns 23. Your IF formula would simply make this calculation: 23 - 10 and return 13 as the result.
On the other hand, MOD(VLOOKUP(A1, B:B, 1, 0), 10) would divide 23 by 10 and show the remainder: 3.
Back to the main topic, when I need to use a formula that repeats some part, I usually put it on another cell and then hide it as some people already suggested.
You can also use the box-shadow property to simulate an underline.
Here is a fiddle. The idea is to use two layered box shadows to position the line in the same place as an underline.
a.underline {
text-decoration: none;
box-shadow: inset 0 -4px 0 0 rgba(255, 255, 255, 1), inset 0 -5px 0 0 rgba(255, 0, 0, 1);
}
I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
You do not need any external command at all, just use Parameter Expansion in bash:
hostname=aaa0.bbb.ccc
echo ${hostname%%.*}
If I were you I would not use either of them.
The disadvantage of the first one is that the parameter names might collide if there are same values in the list.
The disadvantage of the second one is that you are creating command and parameters for each entity.
The best way is to have the command text and parameters constructed once (use Parameters.Add
to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.
If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:
{
"typescript.tsdk": "./node_modules/typescript/lib"
}
Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode.
Now auto-imports should work.
I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ files
CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];
Mark was right this code is MUCH more efficient to manage dates hours min and secs. But he forgot the @ at the beginning of format string declaration.
I am an account exec at a web and mobile development company and hear this question everyday. Unfortunately, iPhone apps are not cheap. You can expect around $100 per hour if you are staying on US soil. I have seen some offshore Indian developers out there for as low as $20 per hour. It all depends on the number and complexity of the functions you wish the app to perform. Simple one function apps are normally around 4-5k. They are so expensive because you are paying a team of people a healthy hourly wage and any type of raw prototyping, development, and coding takes time. Apps can exceed 60-100k pretty easily. Southwest Airlines making an app with a full ecommerce platform that allows you to buy tickets over your phone is an example. All of that porting into their IT is a big job.
And offshoring the project is definitely not always a better option. If you do so you better know who you are dealing with. Do not get me wrong there folks over there who do a bad ass job for a way better deal, but they are not that easy to find. Those guys could fuck around for 5 months on a simple project that would take 6 weeks here, or just not complete it at all and hand it over half finished. I have seen this scenario many times where we finish the work. The project management becomes a challenge. It can be difficult to communicate exactly what you want the app to do.
For my Qt 5.7, open QtCreator, go to Tools -> Options -> Build & Run -> Qt Versions gave me the location of qmake.
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.
[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];
Not too hard to explain... This is like typing hello worl
, hitting the left-arrow key twice, typing d
, and hitting the down-arrow key.
At least, that is how I infer your terminal is interpeting the \b
and \n
codes.
Redirect the output to a file and I bet you get something else entirely. Although you may have to look at the file's bytes to see the difference.
[edit]
To elaborate a bit, this printf
emits a sequence of bytes: hello worl^H^Hd^J
, where ^H
is ASCII character #8 and ^J
is ASCII character #10. What you see on your screen depends on how your terminal interprets those control codes.
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
Assuming that your table name is city
and your existing Primary Key is pk_city
, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time
is NULL
, otherwise you won't be able to re-create the constraint.
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
File SqlStudio.bin actually contains binary serialized data of type "Microsoft.SqlServer.Management.UserSettings.SqlStudio".
Using BinaryFormatter class you can write simple .NET application in order to edit file content.
Principles to keep in mind if you want your applications to be secure:
There are some excellent books and articles online about making your applications secure:
Train your developers on application security best pratices
Codebashing (paid)
Security Innovation(paid)
Security Compass (paid)
OWASP WebGoat (free)
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
How about this:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, [bars]*len(foos))
/etc/mysql$ sudo nano my.cnf
Relevant portion that works for me:
#skip-networking
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = MY_IP
MY_IP
can be found using ifconfig
or curl -L whatismyip.org |grep blue
.
Restart mysql to ensure the new config is loaded:
/etc/mysql$ sudo service mysql restart
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) {
return '[object Object]' === Object.prototype.toString.call(v);
};
JSON.sort = function(o) {
if (Array.isArray(o)) {
return o.sort().map(JSON.sort);
} else if (isObject(o)) {
return Object
.keys(o)
.sort()
.reduce(function(a, k) {
a[k] = JSON.sort(o[k]);
return a;
}, {});
}
return o;
}
It can be used as follows:
JSON.sort({
c: {
c3: null,
c1: undefined,
c2: [3, 2, 1, 0],
},
a: 0,
b: 'Fun'
});
That will output:
{
a: 0,
b: 'Fun',
c: {
c2: [3, 2, 1, 0],
c3: null
}
}
You can also use jQuery's delay()
method instead of setTimeout()
. It'll give you much more readable code. Here's an example from the docs:
$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout
thrusts upon you.
What other folks posted here mainly worked, but using onchange
doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput
. My code (mainly borrowing from MC9000):
HTML
<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
JS
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
You have to override the bootstrap default by being a bit more specific. Try this for a black background:
html body {
background-color: rgba(0,0,0,1.00);
}
In my case I had to remove this block:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
It was showing error near Fragment.showDialog()
method call.
At first you need to add semi colon (;) after quantity INT NOT NULL)
then remove ** from ,genre,quantity)**
.
to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.
Just to share a similar problem I had in case it might help some one, I was using:
var NextSlidePage = $("bottomcontent" + Slide + ".html");
to make the variable for the load function, But I should have used:
var NextSlidePage = "bottomcontent" + Slide + ".html";
without the $( )
Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!
Google only allows images which are coming from trusted source .
So I solved this issue by hosting my images in google drive and using its url as source for my images.
Example: with: http://drive.google.com/uc?export=view&id=FILEID'>
to form URL please refer here.
For Website you can use 'Roboto' font as below:
If you have created separate css file then put below line at the top of css file as:
@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
Or if you don't want to create separate file then add above line in between <style>...</style>
:
<style>
@import url('https://fonts.googleapis.com/css?
family=Roboto:300,300i,400,400i,500,500i,700,700i,900,900i');
</style>
then:
html, body {
font-family: 'Roboto', sans-serif;
}
Actually just adding margin-bottom: -20px; to the tag class fixed it right up.
Being block elements, div's naturally have defined borders that they try not to violate. To get them to layer for images, which have no content beside the image because they have no closing tag, you just have to force them to do what they do not want to do, like violate their natural boundaries.
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
}
.tag {
float: left;
position: relative;
left: 0px;
top: 0px;
background-color: green;
z-index: 1000;
margin-bottom: -20px;
}
Another toue to take would be to create div's using an image as the background, and then place content where ever you like.
<div id="imgContainer" style="
background-image: url("foo.jpg");
background-repeat: no-repeat;
background-size: cover;
-webkit-background-size: cover;
-mox-background-size: cover;
-o-background-size: cover;">
<div id="theTag">BLAH BLAH BLAH</div>
</div>
Here is a simple query containing coalesce -
select * from person where coalesce(addressId, ContactId) is null.
It will return the persons where both addressId and contactId are null.
coalesce function
e.g.
Just updating this for 2017 and later, as CentOS 5 has reached EOL and the URL for EPEL has changed:
sudo rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo yum install git
This gets you git 1.8.2.3
On Windows, if you are unwilling or unable to restart the machine see below.
Install Process Explorer: https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
In Process Explorer, Find > File Handle or DLL ...
Type in the file name mentioned in the error (for my error it was 'git-rebase-todo' but in the question above, 'done').
Process Explorer will highlight the process holding a lock on the file (for me it was 'grep').
Kill the process and you will be able to abort the git action in the standard way.
Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $
are global, variables with @
are instance variables, @@
means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.
I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:
Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo
and create a constant Offset
, so then all the classes could access Foo::Offset
.
Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
Just like in Java, using CommonsIO library:
FileUtils.readFileToString(file, StandardCharsets.UTF_8)
Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.
Yes, fill in a Rectangle with a solid color across the canvas, use the height
and width
of the canvas itself:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
canvas{ border: 1px solid black; }
_x000D_
<canvas width=300 height=150 id="canvas">
_x000D_
In addition to bcrypt and PBKDF2 mentioned in other answers, I would recommend looking at scrypt
MD5 and SHA-1 are not recommended as they are relatively fast thus using "rent per hour" distributed computing (e.g. EC2) or a modern high end GPU one can "crack" passwords using brute force / dictionary attacks in relatively low costs and reasonable time.
If you must use them, then at least iterate the algorithm a predefined significant amount of times (1000+).
See here for more: https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
And here: http://codahale.com/how-to-safely-store-a-password/ (criticizes SHA family, MD5 etc for password hashing purposes)
You can use multiselect
function for this.
CriteriaBuilder cb=session.getCriteriaBuilder();
CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
Root<Car> root=cquery.from(User.class);
cquery.multiselect(root.get("id"),root.get("Name"));
Query<Object[]> q=session.createQuery(cquery);
List<Object[]> list=q.getResultList();
System.out.println("id Name");
for (Object[] objects : list) {
System.out.println(objects[0]+" "+objects[1]);
}
This is supported by hibernate 5. createCriteria
is deprecated in further version of hibernate. So you can use criteria builder
instead.
I had a similar issue and found out that if you have a class that contains transitions, the element will blink. I tried to add ng-cloak without success, but by removing the transition the button stopped blinking.
I'm using ionic framework and the button-outline has this transition
.button-outline {
-webkit-transition: opacity .1s;
transition: opacity .1s;
}
Simply overwrite the class to remove the transition and the button will stop blinking.
Update
Again on ionic there is a flicker when using ng-show/ng-hide. Adding the following CSS resolves it:
.ng-hide-add,
.ng-hide-remove {
display: none !important;
}
Source: http://forum.ionicframework.com/t/beta-14-ng-hide-show/14270/9
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:
from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
<td width="580" valign="top">.......</td>\
<td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')
This is your best tool for performing this task. You can generate a script that will build whichever tables you wish from a database as well as insert the data in those tables (as far as I know you have to export all of the data in the selected tables however).
To do this follow these steps:
To restore your database, simply create a new database and change the first line of your generated script to USE [Your.New.Database.Name]
, then execute. Your new database will now have all of the tables and data you selected from the original database.
I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:
public static String getString( final JSONObject response,
final String key )
{ return getString( response, key, "" ); }
public static String getString( final JSONObject response,
final String key, final String defVal )
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }
public static long getLong( final JSONObject response,
final String key )
{ return getLong( response, key, 0 ); }
public static long getLong( final JSONObject response,
final String key, final long defVal )
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }
public static float getFloat( final JSONObject response,
final String key )
{ return getFloat( response, key, 0.0f ); }
public static float getFloat( final JSONObject response,
final String key, final float defVal )
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }
public static List<JSONObject> getList( final JSONObject response,
final String key )
{ return getList( response, key, new ArrayList<JSONObject>() ); }
public static List<JSONObject> getList( final JSONObject response,
final String key, final List<JSONObject> defVal ) {
try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
catch( ClassCastException e ) { return defVal; }
}
INDEXES
- to find data easily
UNIQUE INDEX
- duplicate values are not allowed
Syntax for INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Syntax for UNIQUE INDEX
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033
is the ESC character, ASCII 27. It is followed by [
, then zero or more numbers separated by ;
, and finally the letter m
. The numbers describe the colour and format to switch to from that point onwards.
The codes for foreground and background colours are:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
Additionally, you can use these:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27
See the table on Wikipedia for other, less widely supported codes.
To determine whether your terminal supports colour sequences, read the value of the TERM
environment variable. It should specify the particular terminal type used (e.g. vt100
, gnome-terminal
, xterm
, screen
, ...). Then look that up in the terminfo database; check the colors
capability.
Looks like this will be finally supported in the SQL Server 2019! SQL Server 2019 - whats new?
From BOL:
UTF-8 support
Full support for the widely used UTF-8 character encoding as an import or export encoding, or as database-level or column-level collation for text data. UTF-8 is allowed in the
CHAR
andVARCHAR
datatypes, and is enabled when creating or changing an object’s collation to a collation with theUTF8
suffix.For example,
LATIN1_GENERAL_100_CI_AS_SC
toLATIN1_GENERAL_100_CI_AS_SC_UTF8
. UTF-8 is only available to Windows collations that support supplementary characters, as introduced in SQL Server 2012.NCHAR
andNVARCHAR
allow UTF-16 encoding only, and remain unchanged.This feature may provide significant storage savings, depending on the character set in use. For example, changing an existing column data type with ASCII strings from
NCHAR(10)
toCHAR(10)
using an UTF-8 enabled collation, translates into nearly 50% reduction in storage requirements. This reduction is becauseNCHAR(10)
requires 22 bytes for storage, whereasCHAR(10)
requires 12 bytes for the same Unicode string.
2019-05-14 update:
Documentation seems to be updated now and explains our options staring in MSSQL 2019 in section "Collation and Unicode Support".
2019-07-24 update:
Article by Pedro Lopes - Senior Program Manager @ Microsoft about introducing UTF-8 support for Azure SQL Database
A simple inline JavaScript confirm would suffice:
<form onsubmit="return confirm('Do you really want to submit the form?');">
No need for an external function unless you are doing validation, which you can do something like this:
<script>
function validate(form) {
// validation code here ...
if(!valid) {
alert('Please correct the errors in the form!');
return false;
}
else {
return confirm('Do you really want to submit the form?');
}
}
</script>
<form onsubmit="return validate(this);">
In very short
git branch --set-upstream yourLocalBranchName origin/develop
This will make your yourLocalBranchName
track the remote branch called develop
.
You can use IF EXIST to check for a file:
IF EXIST "filename" (
REM Do one thing
) ELSE (
REM Do another thing
)
If you do not need an "else", you can do something like this:
set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=
Here's a working example of searching for a file or a folder:
REM setup
echo "some text" > filename
mkdir "foldername"
REM finds file
IF EXIST "filename" (
ECHO file filename exists
) ELSE (
ECHO file filename does not exist
)
REM does not find file
IF EXIST "filename2.txt" (
ECHO file filename2.txt exists
) ELSE (
ECHO file filename2.txt does not exist
)
REM folders must have a trailing backslash
REM finds folder
IF EXIST "foldername\" (
ECHO folder foldername exists
) ELSE (
ECHO folder foldername does not exist
)
REM does not find folder
IF EXIST "filename\" (
ECHO folder filename exists
) ELSE (
ECHO folder filename does not exist
)