When creating the colors, you may use rgb
and set its alpha
argument:
plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
pch = 16, cex = 4)
Please see ?rgb
for details.
<ImageView
android:id="@+id/listViewIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/settings"/>
Remove android:alpha=0.2
from XML-> ImageView.
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
Hopefully, this reply will save beginners a lot of aggravation.
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
in Swift 3.0
yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
This works for me in xcode 8.2.
It may helps you.
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.
Use attribute fill-opacity
in your element of SVG.
Default value is 1, minimum is 0, in step use decimal values EX: 0.5 = 50% of alpha. Note: It is necessary to define fill
color to apply fill-opacity
.
See my example.
The alpha can be set along with the color using the following hex format #ARGB or #AARRGGBB. See http://developer.android.com/guide/topics/resources/color-list-resource.html
This is what I'm currently using, it will list a table and it's fkey constraints [remove table clause and it will list all tables in current catalog]:
SELECT
current_schema() AS "schema",
current_catalog AS "database",
"pg_constraint".conrelid::regclass::text AS "primary_table_name",
"pg_constraint".confrelid::regclass::text AS "foreign_table_name",
(
string_to_array(
(
string_to_array(
pg_get_constraintdef("pg_constraint".oid),
'('
)
)[2],
')'
)
)[1] AS "foreign_column_name",
"pg_constraint".conindid::regclass::text AS "constraint_name",
TRIM((
string_to_array(
pg_get_constraintdef("pg_constraint".oid),
'('
)
)[1]) AS "constraint_type",
pg_get_constraintdef("pg_constraint".oid) AS "constraint_definition"
FROM pg_constraint AS "pg_constraint"
JOIN pg_namespace AS "pg_namespace" ON "pg_namespace".oid = "pg_constraint".connamespace
WHERE
--fkey and pkey constraints
"pg_constraint".contype IN ( 'f', 'p' )
AND
"pg_namespace".nspname = current_schema()
AND
"pg_constraint".conrelid::regclass::text IN ('whatever_table_name')
BufferedReader#read
reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.
String s= inp.readLine();
int[] m= new int[2];
String[] s1 = inp.readLine().split(" ");
m[0]=Integer.parseInt(s1[0]);
m[1]=Integer.parseInt(s1[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
You can check also Scanner vs. BufferedReader.
Set ${COMMAND}
to g++
on Linux
Under "Preprocessor Include Paths, Macros, etc." and "CDT GCC Built-in Compiler Settings" there is an undefined ${COMMAND}
variable if you imported the sources from an existing Makefile project.
Eclipse tries to run that command to parse its stdout to find headers, but ${COMMAND}
is not set by default, and so it is not able to do so.
I have explained this in more detail at: How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
See the traceback
module, specifically the format_exc()
function. Here.
import traceback
try:
raise ValueError
except ValueError:
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
Use:
function console_log($data) {
$bt = debug_backtrace();
$caller = array_shift($bt);
if (is_array($data))
$dataPart = implode(',', $data);
else
$dataPart = $data;
$toSplit = $caller['file'])) . ':' .
$caller['line'] . ' => ' . $dataPart
error_log(end(split('/', $toSplit));
}
Current date time to formated string:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM
{{ ['foo', 'bar'|capitalize]|join }}
As you can see this works with filters and functions without needing to use set
on a seperate line.
You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content -Type: t 0020 65 78 74 2f 68 74 6d 6c 0d 0a 43 61 63 68 65 2d ext/html ..Cache- 0030 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 Control: no-cach
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 .Cache-C ontrol: 0020 6e 6f 2d 63 61 63 68 65 0d 0a 43 6f 6e 74 65 6e no-cache ..Conten 0030 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d t-Type: text/htm 0040 6c 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 l; chars et=ISO-8 0050 38 35 39 2d 31 0d 0a 43 6f 6e 6e 65 63 74 69 6f 859-1..C onnectio
Why is that? because we can not put on the page of JSON a goal like this:
In my case I use the manufacturer Connect Me 9210 Digi:
It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...
See the relevel()
function. Here is an example:
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
head(DF)
str(DF)
m1 <- lm(y ~ x + b, data = DF)
summary(m1)
Now alter the factor b
in DF
by use of the relevel()
function:
DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
The models have estimated different reference levels.
> coef(m1)
(Intercept) x b2 b3 b4 b5
3.2903239 1.4358520 0.6296896 0.3698343 1.0357633 0.4666219
> coef(m2)
(Intercept) x b1 b2 b4 b5
3.66015826 1.43585196 -0.36983433 0.25985529 0.66592898 0.09678759
I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.
set.seed(1234)
total_bill <- rnorm(50, 25, 3)
tip <- 0.15 * total_bill + rnorm(50, 0, 1)
sex <- rbinom(50, 1, 0.5)
smoker <- rbinom(50, 1, 0.3)
day <- ceiling(runif(50, 0,7))
time <- ceiling(runif(50, 0,3))
size <- 1 + rpois(50, 2)
my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
my.data
my.table <- table(my.data$smoker)
my.prop <- prop.table(my.table)
cbind(my.table, my.prop)
You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.
Try the following
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
Just export you view and you will have all SQL need to make some change on it.
Just need to add your change in SQL query for the view and change :
CREATE for CREATE OR REPLACE
If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.
On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)
On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.
Don't forget to include
import Image
In order to show it use this :
Image.open('pathToFile').show()
You can make SQL server to select last N rows using this SQL:
select * from tbl_name order by id desc limit N;
You can add a custom legend documentation
first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first, 'g--', second, 'r--')
plt.legend(['First List', 'Second List'], loc='upper left')
plt.show()
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
This is going to work for all situations while working with width.
`<asp:TemplateField HeaderText="DATE">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("date") %>' Width="100px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>`
Just to complete the answers available:
An input element can be either readonly or disabled (none of them is editable, but there are a couple of differences: focus,...)
Good explanation can be found here:
What's the difference between disabled=“disabled” and readonly=“readonly” for HTML form input fields?
How to use:
<input type="text" value="Example" disabled />
<input type="text" value="Example" readonly />
There are also some solutions to make it through CSS or JavaScript as explained here.
Expanding on the answers provided here.
You can just do set idx = 1
to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1
would not be valid.
This means that you should prefer the syntax: set variable idx = 1
or set var idx = 1
.
Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.
(gdb) p idx = 1
$1 = 1
You can read more about gdb here.
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
An alternative way using Vim(Vi compatible):
Delete duplicate, consecutive lines from a file:
vim -esu NONE +'g/\v^(.*)\n\1$/d' +wq
Delete duplicate, nonconsecutive and nonempty lines from a file:
vim -esu NONE +'g/\v^(.+)$\_.{-}^\1$/d' +wq
For those who are getting the "Unable to resolve dependencies" error:
Toggle "Offline Mode" off
('View'->Tool Windows->Gradle)
Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?
@SqlResultSetMapping(
name="groupDetailsMapping",
classes={
@ConstructorResult(
targetClass=GroupDetails.class,
columns={
@ColumnResult(name="GROUP_ID"),
@ColumnResult(name="USER_ID")
}
)
}
)
@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
and use following in repository interface:
GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery
, @SqlResultSetMapping
and @ConstructorResult
you should be able to achieve that behaviour
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
Try:
select * from v$session where sid = SYS_CONTEXT('USERENV','SID');
You might also be interested in this AskTom post
After seing your comment, you can do:
SELECT * FROM global_name;
%load_ext snakeviz
%%snakeviz
It just takes those 2 lines of code in a Jupyter notebook, and it generates a nice interactive diagram. For example:
Here is the code. Again, the 2 lines starting with %
are the only extra lines of code needed to use snakeviz:
# !pip install snakeviz
%load_ext snakeviz
import glob
import hashlib
%%snakeviz
files = glob.glob('*.txt')
def print_files_hashed(files):
for file in files:
with open(file) as f:
print(hashlib.md5(f.read().encode('utf-8')).hexdigest())
print_files_hashed(files)
It also seems possible to run snakeviz outside notebooks. More info on the snakeviz website.
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
There are three options:
results = Model.objects.exclude(a=True).filter(x=5)
Use Q()
objects and the ~
operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_lookup
class NotEqual(Lookup):
lookup_name = 'ne'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return '%s <> %s' % (lhs, rhs), params
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)
This worked for me - just changed INSERT to UPDATE for my table.
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
the cause is that SQL SERVER is stopped from services.msc a solution for this problem could be starting SQL SERVER from services.msc
Depending on your needs, you have a few options here.
If you don't need to do key/value lookups and want to stick with a List<>
, you can make use of Tuple<int, string>
:
List<Tuple<int, string>> mylist = new List<Tuple<int, string>>();
// add an item
mylist.Add(new Tuple<int, string>(someInt, someString));
If you do want key/value lookups, you could move towards a Dictionary<int, string>
:
Dictionary<int, string> mydict = new Dictionary<int, string>();
// add an item
mydict.Add(someInt, someString);
The package "tictoc" gives you a very simple way of measuring execution time. The documentation is in: https://cran.fhcrc.org/web/packages/tictoc/tictoc.pdf.
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
toc()
To save the elapsed time into a variable you can do:
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
exectime <- toc()
exectime <- exectime$toc - exectime$tic
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
For me, nothing from this list of answers worked.
What finally did the trick is:
These instructions apply if you installed using the official Jenkins Mac installer from http://jenkins-ci.org/
Execute uninstall script from terminal:
'/Library/Application Support/Jenkins/Uninstall.command'
or use Finder to navigate into that folder and double-click on Uninstall.command.
Finally delete last configuration bits which might have been forgotten:
sudo rm -rf /var/root/.jenkins ~/.jenkins
If the uninstallation script cannot be found (older Jenkins version), use following commands:
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins
and if you want to get rid of all the jobs and builds:
sudo rm -rf /Users/Shared/Jenkins
and to delete the jenkins user and group (if you chose to use them):
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
These commands are also invoked by the uninstall script in newer Jenkins versions, and should be executed too:
sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget
Here is:
var array : [String] = ["One", "Two", "Three"]
let userDefault = UserDefaults.standard
// set
userDefault.set(array, forKey: "array")
// retrieve
if let fetchArray = userDefault.array(forKey: "array") as? [String] {
// code
}
I think it could also be the http server settings. Mine is still broken and had ALLOWED_HOSTS the entire time. I can access it locally (i use gunicorn), but not via the domain name when DEBUG=False. when I try using the domain name it then gives me the error, so makes me think its a nginx related issue.
Here is my conf file for nginx:
server {
listen 80;
server_name localhost myproject.ca www.myproject.ca;
root /var/web/myproject/deli_cms;
# serve directly - analogous for static/staticfiles
location /media/ {
# if asset versioning is used
if ($query_string) {
expires max;
}
}
location /admin/media/ {
# this changes depending on your python version
root /var/web/myproject/lib/python2.6/site-packages/django/contrib;
}
location /static/ {
alias /var/web/myproject/deli_cms/static_root/;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://localhost:8000/;
}
# what to serve if upstream is not available or crashes
error_page 500 502 503 504 /media/50x.html;
}
All other answers sounds good, I would like to cover my case, where I had to make an animated LaunchScreen, then after 3 to 4 seconds of animation the next task was to move to Home screen. I tried segues, but that created problem for destination view. So at the end I accessed AppDelegates's Window property and I assigned a new NavigationController screen to it,
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
//Below's navigationController is useful if u want NavigationController in the destination View
let navigationController = UINavigationController(rootViewController: homeVC)
appDelegate.window!.rootViewController = navigationController
If incase, u don't want navigationController in the destination view then just assign as,
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
appDelegate.window!.rootViewController = homeVC
If you want multiple lines consider this:
<textarea rows="2"></textarea>
Specify rows as needed.
add --spring.profiles.active=production
Example:
java -jar file.jar --spring.profiles.active=production
If we are not sure that the list is sorted, we could use the built-in min()
function, to find the element which has the minimum distance from the specified number.
>>> min(myList, key=lambda x:abs(x-myNumber))
4
Note that it also works with dicts with int keys, like {1: "a", 2: "b"}
. This method takes O(n) time.
If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)
Microsoft's GUID
's textual representation can be in the form of a UUID being surrounded by two curly braces {}
.
Update
RouteData.Values["id"] + Request.Url.Query
Will match all your examples
It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.
public class CustomerController : Controller {
public ActionResult Edit(int id) {
int customerId = id //the id in the URL
return View();
}
}
public class ProductController : Controller {
public ActionResult Edit(int id, bool allowed) {
int productId = id; // the id in the URL
bool isAllowed = allowed // the ?allowed=true in the URL
return View();
}
}
Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.
routes.MapRoute(
"Admin", // Route name
"Administration/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action
string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];
It sounds like Request.Url.PathAndQuery
could be what you want.
If you want access to the raw posted data you can use
string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];
Try c.ToString("F6");
(For a full explanation of numeric formatting, see MSDN)
I know its about a year late, but you can also create a 9 path image There's a tool that comes with android SDK which helps in creating such image See this link: http://developer.android.com/tools/help/draw9patch.html
PS: the image can be infinitely scaled as well
You could use RGBa ('a' being alpha transparency), but it's not widely supported yet. It will be, though, so you could use it now and add a fallback:
a:link {
color: rgb(0,0,255);
}
a:link.lighter {
color: rgb(128,128,255); /* This gets applied only in browsers that don't apply the rgba line */
}
a:link.lighter { /* This comes after the previous line, so has priority in supporting browsers */
color: rgba(0,0,255,0.5); /* last value is transparency */
}
If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100
/\d*/.exec(MyElement.style.width)
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Here is the best Maven-Environment Setup tutorial for Windows, Unix and Mac Operating systems.
But in the last you have to set value of PATH
variable as ";%M2_HOME%\bin"
instead of "%M2%"
, because PATH
variable is not able to reduce the value using "%M2%"
In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.
$this->container->getParameter('api_user');
This documentation chapter explains it.
While $this->get()
method in a controller will load a service (doc)
In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:
$this->getParameter('api_user');
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
My version of this is an adaptation of Arvo's work, with a little more added on to ensure two other cases.
1) If we have all 0s, we should return the digit 0.
2) If we have a blank, we should still return a blank character.
CASE
WHEN PATINDEX('%[^0]%', str_col + '.') > LEN(str_col) THEN RIGHT(str_col, 1)
ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col + '.'), LEN(str_col))
END
public byte[] loadBinaryFile (String name) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(name));
byte[] theBytes = new byte[dis.available()];
dis.read(theBytes, 0, dis.available());
dis.close();
return theBytes;
} catch (IOException ex) {
}
return null;
} // ()
A lot (I would even say most) people do.
What's really important about exceptions, is that if you don't write any handling code - the result is perfectly safe and well-behaved. Too eager to panic, but safe.
You need to actively make mistakes in handlers to get something unsafe, and only catch(...){} will compare to ignoring error code.
It's a ternary operator, or the short form for if..else
.
condition ? value if true : value if false
In case you want to pass multiple arguments you can use a tuple
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
For Mac you can use fn + Left control + F12.
Spark SQL supports join on tuple of columns when in parentheses, like
... WHERE (list_of_columns1) = (list_of_columns2)
which is a way shorter than specifying equal expressions (=) for each pair of columns combined by a set of "AND"s.
For example:
SELECT a,b,c
FROM tab1 t1
WHERE
NOT EXISTS
( SELECT 1
FROM t1_except_t2_df e
WHERE (t1.a, t1.b, t1.c) = (e.a, e.b, e.c)
)
instead of
SELECT a,b,c
FROM tab1 t1
WHERE
NOT EXISTS
( SELECT 1
FROM t1_except_t2_df e
WHERE t1.a=e.a AND t1.b=e.b AND t1.c=e.c
)
which is less readable too especially when list of columns is big and you want to deal with NULLs easily.
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
You can do this using the sysctl utility:
sysctl -n hw.ncpu
You can do this by calling the constructor each time with is slightly better
var tupleList = new List<Tuple<int, string>>
{
new Tuple<int, string>(1, "cow" ),
new Tuple<int, string>( 5, "chickens" ),
new Tuple<int, string>( 1, "airplane" )
};
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Hiding an element and then showing it again within a setTimeout of 0 will force a redraw.
$('#page').hide();
setTimeout(function() {
$('#page').show();
}, 0);
You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).
You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
I fixed it without deleting apply plugin: 'com.google.gms.google-services'
I had the error Execution failed for task ':app:processDebugGoogleServices'
because I was using two different versions of google services in my dependencies :
implementation "com.google.android.gms:play-services-maps:11.8.0"
implementation "com.google.android.gms:play-services-nearby:16.0.0"
I changed it to :
implementation "com.google.android.gms:play-services-maps:11.8.0"
implementation "com.google.android.gms:play-services-nearby:11.8.0"
Then it worked
You can use routerLink in the following manner,
<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">
or use <button [routerLink]="['./url']">
in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471
the other methods are also correct but they create a dependency on the component file.
Hope your concern is resolved.
But we can declare a function inside main():
int main()
{
void a();
}
Although the syntax is correct, sometimes it can lead to the "Most vexing parse":
#include <iostream>
struct U
{
U() : val(0) {}
U(int val) : val(val) {}
int val;
};
struct V
{
V(U a, U b)
{
std::cout << "V(" << a.val << ", " << b.val << ");\n";
}
~V()
{
std::cout << "~V();\n";
}
};
int main()
{
int five = 5;
V v(U(five), U());
}
=> no program output.
(Only Clang warning after compilation).
Another approach would be to use MERGE
;WITH cteTable1(CalculatedColumn, CommonField)
AS
(
select CalculatedColumn, CommonField from Table1 Where BatchNo = '110'
)
MERGE cteTable1 AS target
USING (select "Calculated Column", "Common Field" FROM dbo.Table2) AS source ("Calculated Column", "Common Field")
ON (target.CommonField = source."Common Field")
WHEN MATCHED THEN
UPDATE SET target.CalculatedColumn = source."Calculated Column";
-Merge is part of the SQL Standard
-Also I'm pretty sure inner join updates are non deterministic.. Similar question here where the answer talks about that http://ask.sqlservercentral.com/questions/19089/updating-two-tables-using-single-query.html
Another java 8 lambda option :
String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);
And the ugly but optimized version without new array creation
Arrays.stream(array).map(String::trim).toArray(unused -> array);
Original "array" is modified.
This one works in Textmate and it matches everything in a CSS file between the curly brackets.
\{(\s*?.*?)*?\}
selector {.
.
matches here
including white space.
.
.}
If you want to further be able to return the content, then wrap it all in one more set of parentheses like so:
\{((\s*?.*?)*?)\}
and you can access the contents via $1.
This also works for functions, but I haven't tested it with nested curly brackets.
In all filesystems that I am familiar with, you can't do this in-place. You have to use an auxiliary file (which you can then rename to take the name of the original file).
Very Clever and easy way to detect your string is contains only digits or not is this way:
string s = "12fg";
if(s.All(char.IsDigit))
{
return true; // contains only digits
}
else
{
return false; // contains not only digits
}
You could use a string stream and read the elements into the vector.
Here are many different examples...
A copy of one of the examples:
std::vector<std::string> split(const std::string& s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while((pos = s.find(seperator, pos)) != std::string::npos)
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
The answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.
Statements that include a subquery usually take one of these forms:
Check for more subquery rules and subquery types.
More examples of Nested Subqueries.
IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
Usually if you use space as delimiter, you want to treat multiple spaces as one, because you parse the output of a command aligning some columns with spaces. (and the google search for that lead me here)
In this case a single cut
command is not sufficient, and you need to use:
tr -s ' ' | cut -d ' ' -f 2
Or
awk '{print $2}'
On BSD systems and Android you can also use fgetln
:
#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
Like so:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
The line
is not null terminated and contains \n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned line
buffer.
I'm late to the game, but an anonymous objects would do the trick:
[HttpGet]
public HttpResponseMessage Me(string hash)
{
HttpResponseMessage httpResponseMessage;
List<Something> somethings = ...
var returnObjects = somethings.Select(x => new {
Id = x.Id,
OtherField = x.OtherField
});
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK,
new { result = true, somethings = returnObjects });
return httpResponseMessage;
}
The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):
printf("%.9g", number)
.printf("%.17g", number)
.Do NOT use %f
, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h
which defines FLT_DECIMAL_DIG
and DBL_DECIMAL_DIG
.
I'm doing it like this at the moment:
// Requires NuGet package Microsoft.Extensions.Configuration.Json
using Microsoft.Extensions.Configuration;
using System.IO;
namespace ImagesToMssql.AppsettingsJson
{
public static class AppSettingsJson
{
public static IConfigurationRoot GetAppSettings()
{
string applicationExeDirectory = ApplicationExeDirectory();
var builder = new ConfigurationBuilder()
.SetBasePath(applicationExeDirectory)
.AddJsonFile("appsettings.json");
return builder.Build();
}
private static string ApplicationExeDirectory()
{
var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
var appRoot = Path.GetDirectoryName(location);
return appRoot;
}
}
}
And then I use this where I need to get the data from the appsettings.json file:
var appSettingsJson = AppSettingsJson.GetAppSettings();
// appSettingsJson["keyName"]
I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.
D:\>InterlockVsMonitor.exe 16
Using 16 threads:
InterlockAtomic.RunIncrement (ns): 8355 Average, 8302 Minimal, 8409 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 7077 Average, 6843 Minimal, 7243 Maxmial
D:\>InterlockVsMonitor.exe 4
Using 4 threads:
InterlockAtomic.RunIncrement (ns): 4319 Average, 4319 Minimal, 4321 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 933 Average, 802 Minimal, 1018 Maxmial
With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...
Take a look at it's quickStart guide to see how to create an archetype based on this Framework.
Foundational frameworks in AppFuse:
For example to create an appFuse light archetype :
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1
-DgroupId=com.mycompany -DartifactId=myproject
We use a combination of the processor id number (ProcessorID
) from Win32_processor
and the universally unique identifier (UUID
) from Win32_ComputerSystemProduct
:
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
processorId = mo["ProcessorID"] as string;
}
mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
systemId = mo["UUID"] as string;
}
var compIdStr = $"{processorId}{systemId}";
Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor"
) and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"
), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:
Therefore, it is worth considering this situation.
Also keep in mind that the ProcessorID
number may be the same on different computers.
The shape of your matrix C
is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)
It's so simple with URLSearchParams
, supported in all modern browsers (caniuse).
let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());
_x000D_
If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search)
and assign the string to window.location.search
.
Sure you can!
I do this as a fallback for header logo images, I think some versions of IE will not abide. Edit: Or Chrome apparently - I don't even see alt text in the demo(?). Firefox works well however.
img {_x000D_
color: green;_x000D_
font: 40px Impact;_x000D_
}
_x000D_
<img src="404" alt="Alt Text">
_x000D_
Here is a condensed replacement for the ConvertToLetter function that in theory should work for all possible positive integers. For example, 1412 produces "BBH" as the result.
Public Function ColumnNumToStr(ColNum As Integer) As String
Dim Value As Integer
Dim Rtn As String
Rtn = ""
Value = ColNum - 1
While Value > 25
Rtn = Chr(65 + (Value Mod 26)) & Rtn
Value = Fix(Value / 26) - 1
Wend
Rtn = Chr(65 + Value) & Rtn
ColumnNumToStr = Rtn
End Function
You can achieve this in quite a few different ways.
let foo = {
bar: 'Hello World'
};
foo.bar;
foo['bar'];
The bracket notation is specially powerful as it let's you access a property based on a variable:
let foo = {
bar: 'Hello World'
};
let prop = 'bar';
foo[prop];
This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
for (let prop in foo.getOwnPropertyNames()) {
console.log(foo[prop]);
}
Both dot and bracket notation also work as expected for nested objects:
let foo = {
bar: {
baz: 'Hello World'
}
};
foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;
Object destructuring
We could also consider object destructuring as a means to access a property in an object, but as follows:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
let prop = 'last';
let { bar, baz, [prop]: customName } = foo;
// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'
I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.
function tryToXml($dom,$content) {
if(!$content) return false;
// xml well formed content can be loaded as xml node tree
$fragment = $dom->createDocumentFragment();
// wonderfull appendXML to add an XML string directly into the node tree!
// aappendxml will fail on a xml declaration so manually skip this when occurred
if( substr( $content,0, 5) == '<?xml' ) {
$content = substr($content,strpos($content,'>')+1);
if( strpos($content,'<') ) {
$content = substr($content,strpos($content,'<'));
}
}
// if appendXML is not working then use below htmlToXml() for nasty html correction
if(!@$fragment->appendXML( $content )) {
return $this->htmlToXml($dom,$content);
}
return $fragment;
}
// convert content into xml
// dom is only needed to prepare the xml which will be returned
function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {
// no xml when html is empty
if(!$content) return false;
// real content and possibly it needs encoding
if( $needEncoding ) {
// no need to convert character encoding as loadHTML will respect the content-type (only)
$content = '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
}
// return a dom from the content
$domInject = new DOMDocument("1.0", "UTF-8");
$domInject->preserveWhiteSpace = false;
$domInject->formatOutput = true;
// html type
try {
@$domInject->loadHTML( $content );
} catch(Exception $e){
// do nothing and continue as it's normal that warnings will occur on nasty HTML content
}
// to check encoding: echo $dom->encoding
$this->reworkDom( $domInject );
if( $bodyOnly ) {
$fragment = $dom->createDocumentFragment();
// retrieve nodes within /html/body
foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
foreach( $elementLevel1->childNodes as $elementInject ) {
$fragment->insertBefore( $dom->importNode($elementInject, true) );
}
}
}
} else {
$fragment = $dom->importNode($domInject->documentElement, true);
}
return $fragment;
}
protected function reworkDom( $node, $level = 0 ) {
// start with the first child node to iterate
$nodeChild = $node->firstChild;
while ( $nodeChild ) {
$nodeNextChild = $nodeChild->nextSibling;
switch ( $nodeChild->nodeType ) {
case XML_ELEMENT_NODE:
// iterate through children element nodes
$this->reworkDom( $nodeChild, $level + 1);
break;
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
// do nothing with text, cdata
break;
case XML_COMMENT_NODE:
// ensure comments to remove - sign also follows the w3c guideline
$nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
break;
case XML_DOCUMENT_TYPE_NODE: // 10: needs to be removed
case XML_PI_NODE: // 7: remove PI
$node->removeChild( $nodeChild );
$nodeChild = null; // make null to test later
break;
case XML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
case XML_HTML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
default:
throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
}
$nodeChild = $nodeNextChild;
} ;
}
Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:
$c='<p>test<font>two</p>';
$dom=new DOMDocument('1.0', 'UTF-8');
$n=$dom->appendChild($dom->createElement('info')); // make a root element
if( $valueXml=tryToXml($dom,$c) ) {
$n->appendChild($valueXml);
}
echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';
In this example '<p>test<font>two</p>'
will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>
'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>
' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info>
tag can be skipped.
With this I'm getting real nice XML out of unstructured and even corrupted HTML!
I hope it's a bit clear and might contribute to other people to use it.
I ran into this problem because one level of tag, <ListView.View>
to be specirfic, was missing in my XAML.
This code produced this error.
<Grid>
<ListView Margin="10" Name="lvDataBinding" >
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView>
</Grid>
The following fixed it
<Grid>
<ListView Margin="10" Name="lvDataBinding" >
<ListView.View> <!-- This was missing in top! -->
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
I have also got stuck into this and believe me disabling SELinux is not a good idea.
Please just use below and you are good,
sudo restorecon -R /var/www/mysite
Enjoy..
The solution to the problem is already defined in some of the answers. But there is still a need to express a detail. The problem is totally related to maven, and the solution is also in the pom.xml configuration. IntelliJ only reads maven configuration, and if the configuration has wrong information, IntelliJ also tries to use that.
To solve the problem, as expressed in the most of the answers, just add the below properties to the pom.xml of the project.
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
After that, on the IntelliJ side, reimport maven configuration. To reimport the maven configuration, right click on pom.xml file of the project and select Reimport. Compiler version related information in IntelliJ preferences will be automatically updated according to the values in the pom.xml.
As a general (see Stackblitz here: https://stackblitz.com/edit/angular-gh2rjx):
HTML
<select [(ngModel)]="selectedOption">
<option *ngFor="let o of options">
{{o.name}}
</option>
</select>
<button (click)="print()">Click me</button>
<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>
Typescript
export class AppComponent {
selectedOption: string;
printedOption: string;
options = [
{ name: "option1", value: 1 },
{ name: "option2", value: 2 }
]
print() {
this.printedOption = this.selectedOption;
}
}
In your specific case you can use ngModel like this:
<form class="form-inline" (ngSubmit)="HelloCorp()">
<div class="select">
<select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
<option *ngFor="let corporation of corporations"></option>
</select>
<button type="submit" class="btn btn-primary manage">Submit</button>
</div>
</form>
HelloCorp() {
console.log("My input: ", corporationObj);
}
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
Something like this:
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);
I have experienced the same problem with Eclipse Indigo release - even though the project set up was correct. The main cause I suspect is that the workspace is defined in a separate folder from the actual source folders (as mentioned user748337). To fix the problem, I had to enable the project specific settings option (in the Porject preference) although it wasn't different from the workspace settings.
in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded()
. It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.
1: a pair of brackets is missing.
case TelephonyManager.CALL_STATE_IDLE:
// Went to idle- this is the end of a call. What type depends on previous state(s)
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
// Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
} else {
// this one is missing
if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
}
// this one is missing
break;
2: lastState
is not updated by the state
if it is at the end of the function. It should be replaced to the first line of this function by
public void onCallStateChanged(Context context, int state, String number) {
int lastStateTemp = lastState;
lastState = state;
// todo replace all the "lastState" by lastStateTemp from here.
if (lastStateTemp == state) {
//No change, debounce extras
return;
}
//....
}
Additional I've put lastState
and savedNumber
into shared preference as you suggested.
Just tested it with above changes. Bug fixed at least on my phones.
You can simple put the default value using default(). See the example
$table->enum('is_approved', array('0','1'))->default('0');
I have used enum here and the default value is 0.
Well, I like MONEY
! It's a byte cheaper than DECIMAL
, and the computations perform quicker because (under the covers) addition and subtraction operations are essentially integer operations. @SQLMenace's example—which is a great warning for the unaware—could equally be applied to INT
egers, where the result would be zero. But that's no reason not to use integers—where appropriate.
So, it's perfectly 'safe' and appropriate to use MONEY
when what you are dealing with is MONEY
and use it according to mathematical rules that it follows (same as INT
eger).
Would it have been better if SQL Server promoted division and multiplication of MONEY
's into DECIMAL
s (or FLOAT
s?)—possibly, but they didn't choose to do this; nor did they choose to promote INT
egers to FLOAT
s when dividing them.
MONEY
has no precision issue; that DECIMAL
s get to have a larger intermediate type used during calculations is just a 'feature' of using that type (and I'm not actually sure how far that 'feature' extends).
To answer the specific question, a "compelling reason"? Well, if you want absolute maximum performance in a SUM(x)
where x
could be either DECIMAL
or MONEY
, then MONEY
will have an edge.
Also, don't forget it's smaller cousin, SMALLMONEY
—just 4 bytes, but it does max out at 214,748.3647
- which is pretty small for money—and so is not often a good fit.
To prove the point around using larger intermediate types, if you assign the intermediate explicitly to a variable, DECIMAL
suffers the same problem:
declare @a decimal(19,4)
declare @b decimal(19,4)
declare @c decimal(19,4)
declare @d decimal(19,4)
select @a = 100, @b = 339, @c = 10000
set @d = @a/@b
set @d = @d*@c
select @d
Produces 2950.0000
(okay, so at least DECIMAL
rounded rather than MONEY
truncated—same as an integer would.)
var str = "hello world & hello universe"
In order to replace both Spaces and Symbols in one shot, we can use the below regex code.
str.replaceAll("\\W+","")
Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches
Try it!
You can just use an import statement:
from file import *
So, for example, if you had a file named my_script.py
you'd load it like so:
from my_script import *
This is a jQuery version of Moussawi7's answer.
$(function() {
$("textarea.auto-grow").on("input", function() {
var element = $(this)[0];
element.style.height = "5px";
element.style.height = (element.scrollHeight) + "px";
});
})
_x000D_
textarea {
resize: none;
overflow: auto;
width: 100%;
min-height: 50px;
max-height: 150px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="auto-grow"></textarea>
_x000D_
Actually the following code is valid for API levels 5 and up, so if your target API is lower than this, you'll end up with something very similar to EboMike's code.
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
is
and ==
?==
and is
are different comparison! As others already said:
==
compares the values of the objects.is
compares the references of the objects.In Python names refer to objects, for example in this case value1
and value2
refer to an int
instance storing the value 1000
:
value1 = 1000
value2 = value1
Because value2
refers to the same object is
and ==
will give True
:
>>> value1 == value2
True
>>> value1 is value2
True
In the following example the names value1
and value2
refer to different int
instances, even if both store the same integer:
>>> value1 = 1000
>>> value2 = 1000
Because the same value (integer) is stored ==
will be True
, that's why it's often called "value comparison". However is
will return False
because these are different objects:
>>> value1 == value2
True
>>> value1 is value2
False
Generally is
is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.
You should only use is
if you:
want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.
want to compare a value to a Python constant. The constants in Python are:
None
True
1False
1NotImplemented
Ellipsis
__debug__
int is int
or int is float
)np.ma.masked
from the NumPy module)In every other case you should use ==
to check for equality.
There is some aspect to ==
that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__
method. For example:
class MyClass(object):
def __init__(self, val):
self._value = val
def __eq__(self, other):
print('__eq__ method called')
try:
return self._value == other._value
except AttributeError:
raise TypeError('Cannot compare {0} to objects of type {1}'
.format(type(self), type(other)))
This is just an artificial example to illustrate that the method is really called:
>>> MyClass(10) == MyClass(10)
__eq__ method called
True
Note that by default (if no other implementation of __eq__
can be found in the class or the superclasses) __eq__
uses is
:
class AClass(object):
def __init__(self, value):
self._value = value
>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a
So it's actually important to implement __eq__
if you want "more" than just reference-comparison for custom classes!
On the other hand you cannot customize is
checks. It will always compare just if you have the same reference.
Because __eq__
can be re-implemented or overridden, it's not limited to return True
or False
. It could return anything (but in most cases it should return a boolean!).
For example with NumPy arrays the ==
will return an array:
>>> import numpy as np
>>> np.arange(10) == 2
array([False, False, True, False, False, False, False, False, False, False], dtype=bool)
But is
checks will always return True
or False
!
1 As Aaron Hall mentioned in the comments:
Generally you shouldn't do any is True
or is False
checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if
statement). So doing the is True
comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).
Like PEP8 mentions:
Don't compare boolean values to
True
orFalse
using==
.Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
Simply add these to your ggplot:
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge'
could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.
select
count(1) "NO. Of DB Users",
to_char(sysdate,'DD-MON-YYYY:HH24:MI:SS') sys_time
from
v$session
where
username is NOT NULL;
I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.
So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.
Do this:
box-shadow: 0 4px 2px -2px gray;
It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.
You could use the System.Web.UI.WebControls.CheckBoxList
control or use the System.Web.UI.WebControls.ListBox
control with the SelectionMode
property set to Multiple
.
If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.
import { Component, OnInit, Renderer, ElementRef} from '@angular/core';
constructor( elementRef: ElementRef, renderer: Renderer) {
dragulaService.drop.subscribe((value) => {
this.onDrop(value.slice(1));
});
}
public onDrop(args) {
let [e, el] = args;
this.toggleClassComTitle(e,'checked');
}
public toggleClassComTitle(el: any, name: string) {
el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {
item.addEventListener('click', function(event) {
console.log("item-clicked");
});
});
}
To anyone else who finds this older question, you can now download all old versions.
Xcode
-> Preferences
-> Components
(Click on Simulators tab).
Install all the versions you want/need.
To show all installed simulators:
Target -> In dropdown "deployment target" choose the installed version with lowest version nr.
You should now see all your available simulators in the dropdown.
Javascript doesn't have threads, but we do have workers.
Workers may be a good choice if you don't need shared objects.
Most browser implementations will actually spread workers across all cores allowing you to utilize all cores. You can see a demo of this here.
I have developed a library called task.js that makes this very easy to do.
task.js Simplified interface for getting CPU intensive code to run on all cores (node.js, and web)
A example would be
function blocking (exampleArgument) {
// block thread
}
// turn blocking pure function into a worker task
const blockingAsync = task.wrap(blocking);
// run task on a autoscaling worker pool
blockingAsync('exampleArgumentValue').then(result => {
// do something with result
});
Note: The solution here needs to be done at application design stage. It would be difficult to engineer this in later.
Use a hidden field to pass around the session identifier.
For this to work each page must include a form:
<form method="post" action="/handler">
<input type="hidden" name="sessionId" value="123456890123456890ABCDEF01" />
<input type="hidden" name="action" value="" />
</form>
Every action on your side, including navigation, POSTs the form back (setting the action
as appropriate). For "unsafe" requests, you could include another parameter, say containing a JSON value of the data to be submitted:
<input type="hidden" name="action" value="completeCheckout" />
<input type="hidden" name="data" value='{ "cardNumber" : "4111111111111111", ... ' />
As there are no cookies, each tab will be independent and will have no knowledge of other sessions in the same browser.
Lots of advantages, particularly when it comes to security:
Some disadvantages:
First part of accepted answer does not work for MSSQL.
This worked for me:
select email, COUNT(*) as C from table
group by email having COUNT(*) >1 order by C desc
Too late for you, but for anyone else with the same question...
//a[contains(text(), 'programming')]/@href
Of course, 'programming' can be any text fragment.
The environment variables displayed in Jenkins (Manage Jenkins -> System information) are inherited from the system (i.e. inherited environment variables)
If you run env
command in a shell you should see the same environment variables as Jenkins shows.
These variables are either set by the shell/system or by you in ~/.bashrc
, ~/.bash_profile
.
There are also environment variables set by Jenkins when a job executes, but these are not displayed in the System Information.
So, I tried these other ways, but there was a VERY slight irritant and that was if you keep the modal-content border radius, in FF and Chrome, there is a slight bit of white trim showing along the borders, even if you use 5px on the modal-header border radius. (standard modal-content border radius is 6px, so 5px on the modal-header border top radius covers some white).
My solution:
.modal-body
{
background-color: #FFFFFF;
}
.modal-content
{
border-radius: 6px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
background-color: transparent;
}
.modal-footer
{
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
-webkit-border-bottom-left-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
-moz-border-radius-bottomleft: 6px;
-moz-border-radius-bottomright: 6px;
}
.modal-header
{
border-top-left-radius: 6px;
border-top-right-radius: 6px;
-webkit-border-top-left-radius: 6px;
-webkit-border-top-right-radius: 6px;
-moz-border-radius-topleft: 6px;
-moz-border-radius-topright: 6px;
}
!! CAVEAT !!
You must then set the background colors of the modal-header, modal-content, and modal-footer. This is not bad trade-off, because it allows you to do this:
<div class="modal-header bg-primary">
<div class="modal-body bgColorWhite">
<div class="modal-footer bg-info">
EDIT
Or even better:
<div class="modal-header alert-primary">
If you don't have to support devices with API < 21, use backgroundHint in xml, for example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Task Name"
android:ems="10"
android:id="@+id/task_name"
android:layout_marginBottom="15dp"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textColorLink="@color/blue"
android:textColorHint="@color/blue"
android:backgroundTint="@color/lighter_blue" />
For better support and fallbacks use @Akariuz solution. backgroundHint is the most painless solution, but not backward compatible, based on your requirements make a call.
Here's a nice and simple cache helper class/service I use:
using System.Runtime.Caching;
public class InMemoryCache: ICacheService
{
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
{
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
{
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
}
return item;
}
}
interface ICacheService
{
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));
Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.
var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
string name= "abc";
IList<string> strList = new List<string>() { "abc", "def", "ghi", "jkl", "mno" };
if (strList.Contains(name))
{
Console.WriteLine("Got It");
}
///////////////// OR ////////////////////////
IList<int> num = new List<int>();
num.Add(10);
num.Add(20);
num.Add(30);
num.Add(40);
Console.WriteLine(num.Count); // to count the total numbers in the list
if(num.Contains(20)) {
Console.WriteLine("Got It"); // if condition to find the number from list
}
I need a query with constant time response
By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...})
will not provide constant time, O(1) responses.
That stated, you can also sort by the _id
if you are using ObjectId
for you IDs. See here for details. Of course, even that is only good to the last second.
You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.
This work in C#:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int idx = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[idx];
long newNo = idx;
if (!_RowNumberStartFromZero)
newNo += 1;
long oldNo = -1;
if (row.HeaderCell.Value != null)
{
if (IsNumeric(row.HeaderCell.Value))
{
oldNo = System.Convert.ToInt64(row.HeaderCell.Value);
}
}
if (newNo != oldNo)
{
row.HeaderCell.Value = newNo.ToString();
row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
First delete the constraint "fk_comments_projects1" and also its index. After that recreate it.
just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:
<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female
in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.
I don't know if it is only me, the highest ranked solution doesn't work for me, my eclipse version is just normal eclipse platform installed by using sudo apt-get install eclipse in Ubuntu But I found a solution which adopts method together from both the highest ranked solution and the second, what I did to make it work is described as below (Note that the other steps like creating a C++ project etc. is ignored for simplicity)
Once you have created the C++ project
(1) C/C++ General -> Paths and Symbols -> Symbols -> GNU C++. Click "Add..." and paste GXX_EXPERIMENTAL_CXX0X (ensure to append and prepend two underscores) into "Name" and leave "Value" blank.
(2) Under C/C++ Build (at project settings), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs
After performed above 2 and 2 only steps, it works, the eclipse is able to resolve the unique_ptr, I don't know why this solution works, hope that it can help people.
Here is my strategy to solve the problem.
Problem Statement
We need to make changes in more than 10 files. We tried PULL (git pull origin master)
, but Git shouted:
error: Your local changes to the following files would be overwritten by merge: Please, commit your changes or stash them before you can merge.
We tried to execute commit
and then pull
, but they didn't work either.
Solution
We were in the dirty stage actually, because the files were in the "Staging Area" a.k.a "Index Area" and some were in the "Head Area" a.k.a "local Git directory". And we wanted to pull the changes from the server.
Check this link for information about different stages of Git in a clear manner: GIT Stages
We followed the following steps
git stash
(this made our working directory clean. Your changes are stored on the stack by Git).git pull origin master
(Pull the changes from the server)git stash apply
(Applied all the changes from stack)git commit -m 'message'
(Committed the changes)git push origin master
(Pushed the changes to the server)git stash drop
(Drop the stack)Let's understand when and why you need stashing
If you are in the dirty state, means you are making changes in your files and then you are compelled, due to any reason, to pull or switch to another branch for some very urgent work, so at this point you can't pull or switch until you commit your change. The stash
command is here as a helping hand.
From the book ProGIT, 2nd Edition:
Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command. Stashing takes the dirty state of your working directory – that is, your modified tracked files and staged changes – and saves it on a stack of unfinished changes that you can reapply at any time.
I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --
df <- df [(!(df$A=="no") & !(df$A=="unknown")),]
While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.
I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/
You can Bing for other similar blogs and posts regarding Reporting Services licensing.
Just use for True:
<li ng-if="area"></li>
and for False:
<li ng-if="area === false"></li>
Completing @chuck answer for using composite indices with foreign keys.
You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.
For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:
class Company
{
public Guid Id { get; set; }
}
class Employee
{
public Guid Id { get; set; }
[Required]
public String Name { get; set; }
public Company Company { get; set; }
[Required]
public Guid CompanyId { get; set; }
}
Now the mapping of the Employee class:
class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap ()
{
ToTable("Employee");
Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(p => p.Name)
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 0);
Property(p => p.CompanyId )
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 1);
HasRequired(p => p.Company)
.WithMany()
.HasForeignKey(p => p.CompanyId)
.WillCascadeOnDelete(false);
}
}
Note that I also used @niaher extension for unique index annotation.
Here's my idea on how to fix this:
j = 19
def calc(y):
global j
try:
j = j + 8 - y
x = int(y/j) # this will eventually raise DIV/0 when j=0
print("i = ", str(y), " j = ", str(j), " x = ", str(x))
except:
j = j + 1 # when the exception happens, increment "j" and retry
calc(y)
for i in range(50):
calc(i)
The output of ps aux
looks like you did not start docker through systemd/systemctl.
It looks like you started it with:
sudo dockerd -H gridsim1103:2376
When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.
The correct way to start docker is to use systemd/systemctl:
systemctl enable docker
systemctl start docker
After this, docker should start on system start.
EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
Coloured, word-level diff
ouput
Here's what you can do with the the below script and diff-highlight:
#!/bin/sh -eu
# Use diff-highlight to show word-level differences
diff -U3 --minimal "$@" |
sed 's/^-/\x1b[1;31m-/;s/^+/\x1b[1;32m+/;s/^@/\x1b[1;34m@/;s/$/\x1b[0m/' |
diff-highlight
(Credit to @retracile's answer for the sed
highlighting)
1) Right Click on **Solution Explorer**
2) Go to the **Properties**
3) Expand **Common Properties**
4) Select **Start Up Project**
5) click the radio button (**Single Start_up Project**)
6) select your Project name
7) Then Debug Your project
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
Perhaps you could try ([^ ]+) .*
, which should give you everything to the first blank in your first group.
OS version: 10.14.6 MYSQL version: 8.0.14
Goto System preferences -> MYSQL
Stop MySQL server
One option will be shown here to uninstall MYSQL 8 after stopping Mysql server
If linking to the shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function
Shove it in the ViewBag
:
Controller:
ViewBag.ProductId = 1;
View:
@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})
I don't think you have to check if file exists or not, fs.unlink
will check it for you.
fs.unlink('fileToBeRemoved', function(err) {
if(err && err.code == 'ENOENT') {
// file doens't exist
console.info("File doesn't exist, won't remove it.");
} else if (err) {
// other errors, e.g. maybe we don't have enough permission
console.error("Error occurred while trying to remove file");
} else {
console.info(`removed`);
}
});
One liner:
total_line_count = sum(1 for line in open("filename.txt"))
print(total_line_count)
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
You can get its address by using:
document.getElementById('myframe').src
Not sure if I understood your question correctly but anyways :)
You can also use replaceAll(search, replaceWith)
[MDN].
Then, make sure you have a string by wrapping one type of quotes by a different type:
'a "b" c'.replaceAll('"', "'")
// result: "a 'b' c"
'a "b" c'.replaceAll(`"`, `'`)
// result: "a 'b' c"
// Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
'a "b" c'.replaceAll(/\"/g, "'")
// result: "a 'b' c"
Important(!) if you choose regex:
when using a
regexp
you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".
In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();
component.html:
<div class="doNotPrint">
Header is here.
</div>
<div>
all my beautiful print-related material is here.
</div>
<div class="doNotPrint">
my footer is here.
<button (click)="onPrint()">Print</button>
</div>
component.ts:
onPrint(){
window.print();
}
component.css:
@media print{
.doNotPrint{display:none !important;}
}
You can optionally also add other elements / sections you do not wish to print in the media query.
You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes/ It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.
The image should be embedded in the message as an attachment like this:
--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png
base64 data
--boundary
And, the HTML part would reference the image like this:
<img src="cid:0123456789">
In some clients, src="sig.png" will work too.
You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.
Clients shouldn't block this image either as it isn't remote.
Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):
From
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"
This is a message with multiple parts in MIME format.
--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
test
--
[Picture of a Christmas Tree]
--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"
--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>test</p>
<p class="sig">-- <br><img src="cid:0123456789"></p>
</body>
</html>
--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64
R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7
--related_boundary--
--alternative_boundary--
You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.
It's time I post an answer about RVO, me too...
If you return an object by value, the compiler often optimizes this so it doesn't get constructed twice, since it's superfluous to construct it in the function as a temporary and then copy it. This is called return value optimization: the created object will be moved instead of being copied.
This is most easiest way to let NPM do everything for you
npm --add-python-to-path='true' --debug install --global windows-build-tools
If you want to combine some activities with actionbar and others not, you should use the base theme have actionbar enabled and then create a sub theme that you gonna use it on activities that don't require actionbar
For example you can use a sub style like this
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
While the base theme extends say
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
and then use the non actionbar theme in the AndroidManifest File within the activity tag say
<activity
android:name="com.example.NonActionBarActivity"
android:theme="@style/AppTheme.NoActionBar"
you must apply this to each individual activity that don't need actionbar so if your project requires fewer action bar activities than non, then it's better to apply this on the base theme level
Yes, you can use substitutions and check against the original string:
if not x%str1:bcd=%==x%str1% echo It contains bcd
The %str1:bcd=%
bit will replace a bcd
in str1
with an empty string, making it different from the original.
If the original didn't contain a bcd
string in it, the modified version will be identical.
Testing with the following script will show it in action:
@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal
And the results of various runs:
c:\testarea> testprog hello
c:\testarea> testprog abcdef
It contains bcd
c:\testarea> testprog bcd
It contains bcd
A couple of notes:
if
statement is the meat of this solution, everything else is support stuff.x
before the two sides of the equality is to ensure that the string bcd
works okay. It also protects against certain "improper" starting characters.Without redundant intermediate arrays:
arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
See jsfiddle demo
Make sure upload
plugin implements this.each
in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
Use
datatable.select("col1='test'","col1 ASC")
Then before binding your data to the grid or repeater etc, use this
datatable.defaultview.sort()
That will solve your problem.
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
Okay, it is going to be extremely late answer to this question. But here is just one sample if you want to do it in Kotlin.
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:<number>")
startActivity(intent)
Thought it might help someone.
You could create a patch from the commits that you want to copy and apply the patch to the destination branch.
"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"
^--- As per OP's request. ---^
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Change upload folder to preferred name. Presently saves to upload/
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast
, NETWORK_STATE_CHANGED_ACTION
, at every network connectivity state change.
AndroidManifest:
<receiver
android:name=".WifiReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<!--protected-broadcast: Special broadcast that only the system can send-->
<!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
BroadcastReceiver class:
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
or CONNECTED
(Those states can be obtained as NetworkInfo.DetailedState objects by calling
the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
/*
* NetworkInfo object associated with the Wi-Fi network.
* It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
*/
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.isConnected()) {
// TODO: Place the work here, like retrieving the access point's SSID
/*
* WifiInfo object giving information about the access point we are connected to.
* It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
* null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
*/
WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
String ssid = wifiInfo.getSSID();
}
}
}
Permissions:
None
Simple code please check
SELECT * FROM table_name WHERE created <= (NOW() - INTERVAL 1 MONTH)
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
@implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
@end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
In mac I did this
You can get the column value in VB.net
Dim row As DataRow = fooTable.Rows(0)
Dim temp = Convert.ToString(row("ColumnName"))
And in C# you can use Jimmy's Answer, just be careful while converting it to ToString()
. It can throw null exception if the data is null
instead Use Convert.ToString(your_expression)
to avoid null exception reference
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
One possible solution to this issue is ng-model
attribute is required to use that directive.
Hence adding in the 'ng-model' attribute can resolve the issue.
<input submit-required="true" ng-model="user.Name"></input>
You don't have access to the right image as far my knowledge, unless you override the onTouch
event. I suggest to use a RelativeLayout
, with one editText
and one imageView
, and set OnClickListener
over the image view as below:
<RelativeLayout
android:id="@+id/rlSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text"
android:padding="5dip" >
<EditText
android:id="@+id/txtSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/imgSearch"
android:background="#00000000"
android:ems="10"/>
<ImageView
android:id="@+id/imgSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/btnsearch" />
</RelativeLayout>
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time
"prob" is not a graphical parameter
I read through ?hist
and found about freq: a logical vector set TRUE by default.
the code that worked for me is
hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)
Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.
As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):
These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.
In addition to Richard Cresswells and dpbradleys answer: If you neither want to create a TNS name nor the '//123.45.67.89:1521/Test' input works (some configurations wont), you can put
(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521)) (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED)))
(as one line) into the 'database' section of the login dialog.
I really like CherryPy. Here's an example of a restful web service:
import cherrypy
from cherrypy import expose
class Converter:
@expose
def index(self):
return "Hello World!"
@expose
def fahr_to_celc(self, degrees):
temp = (float(degrees) - 32) * 5 / 9
return "%.01f" % temp
@expose
def celc_to_fahr(self, degrees):
temp = float(degrees) * 9 / 5 + 32
return "%.01f" % temp
cherrypy.quickstart(Converter())
This emphasizes what I really like about CherryPy; this is a completely working example that's very understandable even to someone who doesn't know the framework. If you run this code, then you can immediately see the results in your web browser; e.g. visiting http://localhost:8080/celc_to_fahr?degrees=50 will display 122.0
in your web browser.
What about this:
git diff abcdef 123456 | less
It's handy to just pipe it to less if you want to compare many different diffs on the fly.
just wanted to leave my .scss
example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.
Im looking forward for your feedback!
// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;
// Prepare your "function"
@mixin in-between {
@media (min-width:$widthSmall) and (max-width:$widthMedium) {
@content;
}
}
// Apply your "function"
main {
@include in-between {
//Do something between two media queries
padding-bottom: 20px;
}
}
In my case it was due to passing in \r\n characters inside TestCase's. Not sure why it's causing intermittent issues, as it works most of the time. But if I remove \r\n the test is never inconclusive:
[TestCase("test\r\n1,2\r\n3,4", 1, 2)]
public void My_Test(string message, double latitude, double longitude)
As others have posted: rails server -e production
Or, my personal fave: RAILS_ENV=production
rails s
For most use cases, it's not correct to register MultipartFilter in web.xml because Spring MVC already does the work of processing your multipart request. It's even written in the filter's javadoc.
On the server side, define a multipartResolver bean in your app context:
@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(50000000);
return commonsMultipartResolver;
}
On the client side, here's how to prepare the request for use with Spring RestTemplate API:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, String> pdfHeaderMap = new LinkedMultiValueMap<>();
pdfHeaderMap.add("Content-disposition", "form-data; name=filex; filename=" + file.getOriginalFilename());
pdfHeaderMap.add("Content-type", "application/pdf");
HttpEntity<byte[]> doc = new HttpEntity<byte[]>(file.getBytes(), pdfHeaderMap);
LinkedMultiValueMap<String, Object> multipartReqMap = new LinkedMultiValueMap<>();
multipartReqMap.add("filex", doc);
HttpEntity<LinkedMultiValueMap<String, Object>> reqEntity = new HttpEntity<>(multipartReqMap, headers);
ResponseEntity<MyResponse> resE = restTemplate.exchange(uri, HttpMethod.POST, reqEntity, MyResponse.class);
The important thing is really to provide a Content-disposition header using the exact case, and adding name and filename specifiers, otherwise your part will be discarded by the multipart resolver.
Then, your controller method can handle the uploaded file with the following argument:
@RequestParam("filex") MultipartFile file
Hope this helps.
As others have said, use ArrayList
. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add
method just calls the ArrayList
's add method. This is only useful if your variable is private (which it is).
This one is working for me for settings environment variable for the test plugin
test {
systemProperties = [
'catalina.home': 'c:/test'
]
println "Starting Tests"
beforeTest { descriptor ->
logger.lifecycle("Running test: " + descriptor)
}
}
I had similar problem against 2 different databases (DB2 and SQL), finally I solved it by using CAST
in the source query from DB2. I also take advantage of using a query by adapting the source column to varchar
and avoiding the useless blank spaces:
CAST(RTRIM(LTRIM(COLUMN_NAME)) AS VARCHAR(60) CCSID UNICODE
FOR SBCS DATA) COLUMN_NAME
The important issue here is the CCSID conversion.
I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,
SELECT * FROM some_table WHERE id_column = ANY(@id_list)
where @id_list is bound to an int[] parameter by way of
command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;
where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).
I agree with Reto and fiXedd. Objectively speaking it doesn't make a lot of sense investing significant time and effort into encrypting passwords in SharedPreferences since any attacker that has access to your preferences file is fairly likely to also have access to your application's binary, and therefore the keys to unencrypt the password.
However, that being said, there does seem to be a publicity initiative going on identifying mobile applications that store their passwords in cleartext in SharedPreferences and shining unfavorable light on those applications. See http://blogs.wsj.com/digits/2011/06/08/some-top-apps-put-data-at-risk/ and http://viaforensics.com/appwatchdog for some examples.
While we need more attention paid to security in general, I would argue that this sort of attention on this one particular issue doesn't actually significantly increase our overall security. However, perceptions being as they are, here's a solution to encrypt the data you place in SharedPreferences.
Simply wrap your own SharedPreferences object in this one, and any data you read/write will be automatically encrypted and decrypted. eg.
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
// eg.
prefs.edit().putString("foo","bar").commit();
prefs.getString("foo", null);
Here's the code for the class:
/**
* Warning, this gives a false sense of security. If an attacker has enough access to
* acquire your password store, then he almost certainly has enough access to acquire your
* source binary and figure out your encryption key. However, it will prevent casual
* investigators from acquiring passwords, and thereby may prevent undesired negative
* publicity.
*/
public class ObscuredSharedPreferences implements SharedPreferences {
protected static final String UTF8 = "utf-8";
private static final char[] SEKRIT = ... ; // INSERT A RANDOM PASSWORD HERE.
// Don't use anything you wouldn't want to
// get out there if someone decompiled
// your app.
protected SharedPreferences delegate;
protected Context context;
public ObscuredSharedPreferences(Context context, SharedPreferences delegate) {
this.delegate = delegate;
this.context = context;
}
public class Editor implements SharedPreferences.Editor {
protected SharedPreferences.Editor delegate;
public Editor() {
this.delegate = ObscuredSharedPreferences.this.delegate.edit();
}
@Override
public Editor putBoolean(String key, boolean value) {
delegate.putString(key, encrypt(Boolean.toString(value)));
return this;
}
@Override
public Editor putFloat(String key, float value) {
delegate.putString(key, encrypt(Float.toString(value)));
return this;
}
@Override
public Editor putInt(String key, int value) {
delegate.putString(key, encrypt(Integer.toString(value)));
return this;
}
@Override
public Editor putLong(String key, long value) {
delegate.putString(key, encrypt(Long.toString(value)));
return this;
}
@Override
public Editor putString(String key, String value) {
delegate.putString(key, encrypt(value));
return this;
}
@Override
public void apply() {
delegate.apply();
}
@Override
public Editor clear() {
delegate.clear();
return this;
}
@Override
public boolean commit() {
return delegate.commit();
}
@Override
public Editor remove(String s) {
delegate.remove(s);
return this;
}
}
public Editor edit() {
return new Editor();
}
@Override
public Map<String, ?> getAll() {
throw new UnsupportedOperationException(); // left as an exercise to the reader
}
@Override
public boolean getBoolean(String key, boolean defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Boolean.parseBoolean(decrypt(v)) : defValue;
}
@Override
public float getFloat(String key, float defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Float.parseFloat(decrypt(v)) : defValue;
}
@Override
public int getInt(String key, int defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Integer.parseInt(decrypt(v)) : defValue;
}
@Override
public long getLong(String key, long defValue) {
final String v = delegate.getString(key, null);
return v!=null ? Long.parseLong(decrypt(v)) : defValue;
}
@Override
public String getString(String key, String defValue) {
final String v = delegate.getString(key, null);
return v != null ? decrypt(v) : defValue;
}
@Override
public boolean contains(String s) {
return delegate.contains(s);
}
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
delegate.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
}
protected String encrypt( String value ) {
try {
final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);
} catch( Exception e ) {
throw new RuntimeException(e);
}
}
protected String decrypt(String value){
try {
final byte[] bytes = value!=null ? Base64.decode(value,Base64.DEFAULT) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(pbeCipher.doFinal(bytes),UTF8);
} catch( Exception e) {
throw new RuntimeException(e);
}
}
}
you would have to write down some method to create a temporary array and then copy it like
public String[] increaseArray(String[] theArray, int increaseBy)
{
int i = theArray.length;
int n = ++i;
String[] newArray = new String[n];
for(int cnt=0;cnt<theArray.length;cnt++)
{
newArray[cnt] = theArray[cnt];
}
return newArray;
}
or The ArrayList would be helpful to resolve your problem.
This is a very old thread, but here's a very thorough answer and sample code.
\r
is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015
[chr(0o15)
] or hexidecimal 0d
[chr(0x0d)
] or decimal 13
[chr(13)
]. See man ascii
for a boring read. It (\r
) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR
part of CRLF
which means Carriage Return and Line Feed.
print()
is a function in Python 3. In Python 2 (any version that you'd be interested in using), print
can be forced into a function by importing its definition from the __future__
module. The benefit of the print
function is that you can specify what to print at the end, overriding the default behavior of \n
to print a newline at the end of every print()
call.
sys.stdout.flush
tells Python to flush the output of standard output, which is where you send output with print()
unless you specify otherwise. You can also get the same behavior by running with python -u
or setting environment variable PYTHONUNBUFFERED=1
, thereby skipping the import sys
and sys.stdout.flush()
calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.
And a sample. Note that this runs perfectly in Python 2 or 3.
from __future__ import print_function
import sys
import time
ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
for i in range(1, ANS + 1):
if i in FACTORS:
print('\r{0:d}'.format(i), end='')
sys.stdout.flush()
time.sleep(ANS / 100.0)
else:
print()
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
if tableFields
is an array , you can loop through elements as following :
for (item in tableFields); {
console.log(tableFields[item]);
}
by the way i saw a logical error in you'r code.just remove ;
from end of for loop
right here :
for (item in tableFields); {
.
this will cause you'r loop to do just nothing.and the following line will be executed only once :
// Do stuff
Everyone: I Solved the problem like this. In Android Studio go to File menu and select the Invalidate Caches/Restart... I hope it will work for you. Thanks
Another simple way get by using findall in yii
$id =101;
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1)
{
echo "email:".$comments_1['email_id'];
}
First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.
Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)
Here is a good JSON reference to clarify this difference:
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.