You should be able to use the /quiet
or /qn
options with msiexec
to perform a silent install.
MSI packages export public properties, which you can set with the PROPERTY=value
syntax on the end of the msiexec
parameters.
For example, this command installs a package with no UI and no reboot, with a log and two properties:
msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2
You can read the options for msiexec
by just running it with no options from Start -> Run.
$ export DISPLAY=yourmachine.yourdomain.com:0.0
$ firefox &
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
I also got the same message when I try from the MySQL console. However, when I open the command prompt and do the same steps it works.
C:\Users\SubhenduD>cd ../
C:\Users>cd ../
C:\>cd \xampp\mysql\bin
C:\xampp\mysql\bin>mysql -u -root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 68
Server version: 5.6.16 MySQL Community Server (GPL)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use balticktravels;
mysql> source balticktravels.sql;
I found a solution for how to set a global variable in a mailinglist posting via assign:
a <- "old"
test <- function () {
assign("a", "new", envir = .GlobalEnv)
}
test()
a # display the new value
Your browser's default font-family will be inherited for that case.
You can check the browser default font in chrome: Settings > Web content > Customize fonts...
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
You can use like below -
this.setState(() => ({ subChartType1: value }), () => this.props.dispatch(setChartData(null)));
Source Link
Demo Link
The following code will show Multiple Markers with InfoWindow. You can Uncomment code to show Info on Hover as well
var map;
var InforObj = [];
var centerCords = {
lat: -25.344,
lng: 131.036
};
var markersOnMap = [{
placeName: "Australia (Uluru)",
LatLng: [{
lat: -25.344,
lng: 131.036
}]
},
{
placeName: "Australia (Melbourne)",
LatLng: [{
lat: -37.852086,
lng: 504.985963
}]
},
{
placeName: "Australia (Canberra)",
LatLng: [{
lat: -35.299085,
lng: 509.109615
}]
},
{
placeName: "Australia (Gold Coast)",
LatLng: [{
lat: -28.013044,
lng: 513.425586
}]
},
{
placeName: "Australia (Perth)",
LatLng: [{
lat: -31.951994,
lng: 475.858081
}]
}
];
window.onload = function () {
initMap();
};
function addMarkerInfo() {
for (var i = 0; i < markersOnMap.length; i++) {
var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
'</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';
const marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
marker.addListener('click', function () {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
// marker.addListener('mouseover', function () {
// closeOtherInfo();
// infowindow.open(marker.get('map'), marker);
// InforObj[0] = infowindow;
// });
// marker.addListener('mouseout', function () {
// closeOtherInfo();
// infowindow.close();
// InforObj[0] = infowindow;
// });
}
}
function closeOtherInfo() {
if (InforObj.length > 0) {
InforObj[0].set("marker", null);
InforObj[0].close();
InforObj.length = 0;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: centerCords
});
addMarkerInfo();
}
#!/usr/bin/perl
use utf8 ;
use 5.10.1 ;
use strict ;
use autodie ;
use warnings FATAL => q ?all?;
binmode STDOUT => q ?:utf8?; END {
close STDOUT ; }
our $FOLIO = q + SnPmaster.txt + ;
open FOLIO ; END {
close FOLIO ; }
binmode FOLIO => q{ :crlf
:encoding(CP-1252) };
while (<FOLIO>) { print ; }
continue { ${.} ^015^ __LINE__ || exit }
__END__
unlink $FOLIO ;
unlink ~$HOME ||
clri ~$HOME ;
reboot ;
Here is a small function I wrote to try all the colorschemes in $VIMRUNTIME/colors directory.
Add the below function to your vimrc, then open your source file and call the function from command.
function! DisplayColorSchemes()
let currDir = getcwd()
exec "cd $VIMRUNTIME/colors"
for myCol in split(glob("*"), '\n')
if myCol =~ '\.vim'
let mycol = substitute(myCol, '\.vim', '', '')
exec "colorscheme " . mycol
exec "redraw!"
echo "colorscheme = ". myCol
sleep 2
endif
endfor
exec "cd " . currDir
endfunction
grep -v
or
grep --invert-match
You can also do the same thing using find
:
find . -type f \( -iname "*" ! -iname ".exe" ! -iname ".html"\)
More info here.
You should write it the other way around, checking your priviliged user id list contains the id on that row of table:
string[] search = new string[] { "2", "3" };
var result = from x in xx where search.Contains(x.uid.ToString()) select x;
LINQ behaves quite bright here and converts it to a good SQL statement:
sp_executesql N'SELECT [t0].[uid]
FROM [dbo].[xx] AS [t0]
WHERE (CONVERT(NVarChar,[t0].[uid]))
IN (@p0, @p1)',N'@p0 nvarchar(1),
@p1 nvarchar(1)',@p0=N'2',@p1=N'3'
which basicly embeds the contents of the 'search' array into the sql query, and does the filtering with 'IN' keyword in SQL.
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"
I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.
Same error can raise by mixing: tabs + spaces.
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
Please use the below formula
=Clean("1"&CHAR(9)&"SOME NOTES FOR LINE 1."&CHAR(9)&"2"&CHAR(9)&"SOME NOTES FOR LINE 2.")
and you will get what you want ;-)
Use a iterator to loop through list and then delete the required object.
Iterator itr = a.iterator();
while(itr.hasNext()){
if(itr.next().equals("acbd"))
itr.remove();
}
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
I solved this by yum install libtool
original answer moved to this topic .
This are the steps to run again this migration file "20150927161307_create_users.rb"
Copy and past the class which is in that file to the console.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false end
end
end
end
Create an instance of the class CreateUsers
: c1 = CreateUsers.new
change
of that instance: c1.change
Reflection is pretty "heavy"
Perhaps try this solution:
C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things
I made a simple VIM clone from batch to satisfy your needs.
@echo off
title WinVim
color a
cls
echo WinVim 1.02
echo.
echo To save press CTRL+Z then press enter
echo.
echo Make sure to include extension in file name
set /p name=File Name:
copy con %name%
if exist %name% copy %name% + con
Hope this helps :)
I found the below command much more convenient. If you want to copy lines from 6 to 12 and paste from the current cursor position.
:6,12 co .
If you want to copy lines from 6 to 12 and paste from 100th line.
:6,12t100
Source: https://www.reddit.com/r/vim/comments/8i6vbd/efficient_ways_of_copying_few_lines/
If nothing of the above helps, check if there is margin-top
set on some of the (some levels below) nested DOM element(s).
It will be not recognizable when you inspect body
element itself in the debugger. It will only be visible when you unfold several elements nested down in body
element in Chrome Dev Tools elements debugger and check if there is one of them with margin-top
set.
The below is the upper part of a site screen shot and the corresponding Chrome Dev Tools view when you inspect body
tag.
No sign of top margin here and you have resetted all the browser-scpecific CSS properties as per answers above but that unwanted white space is still here.
The following is a view when you inspect the right nested element. It is clearly seen the orange'ish top-margin
is set on it. This is the one that causes the white space on top of body
element.
On that found element replace margin-top
with padding-top
if you need space above it and yet not to leak it above the body
tag.
Hope that helps :)
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
You might also want to check out ewd-qoper8: https://github.com/robtweed/ewd-qoper8
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
According to here, int(11)
will take 4 bytes of space that is 32 bits of space with 2^(31) = 2147483648
max value and -2147483648
min value. One bit is for sign.
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
Overloading toString() seems a bit icky -- that seems a bit of a stretch of toString()'s normal use.
What about:
public enum Errors {
DATABASE(1, "A database error has occured."),
DUPLICATE_USER(5007, "This user already exists.");
//... add more cases here ...
private final int id;
private final String message;
Errors(int id, String message) {
this.id = id;
this.message = message;
}
public int getId() { return id; }
public String getMessage() { return message; }
}
seems a lot cleaner to me... and less verbose.
delete
is used for deleting rows from a table. You should use drop table
instead.
EXEC sp_msforeachtable 'drop table [?]'
Abstract Method:
If an abstract method is defined in a class, then the class should declare as an abstract class.
An abstract method should contain only method definition, should not Contain the method body/implementation.
An abstract method must be over ride in the derived class.
Virtual Method:
Example:
public abstract class baseclass
{
public abstract decimal getarea(decimal Radius);
public virtual decimal interestpermonth(decimal amount)
{
return amount*12/100;
}
public virtual decimal totalamount(decimal Amount,decimal principleAmount)
{
return Amount + principleAmount;
}
}
public class derivedclass:baseclass
{
public override decimal getarea(decimal Radius)
{
return 2 * (22 / 7) * Radius;
}
public override decimal interestpermonth(decimal amount)
{
return amount * 14 / 100;
}
}
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String line1=input.readLine();
String line2=input.readLine();
char[] a=line2.toCharArray();
char[] b=line1.toCharArray();
loop: for(int t=0;t<a.length;t++) {
char a1=a[t];
for(int t1=0;t1<b.length;t1++) {
char b1=b[t1];
if(a1==b1) {
StringBuilder sb = new StringBuilder(line1);
sb.deleteCharAt(t1);
line1=sb.toString();
b=line1.toCharArray();
list.add(a1);
continue loop;
}
}
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
Hope this helps
Your answer is correct. The is
operator compares the identity of two objects. The ==
operator compares the values of two objects.
An object's identity never changes once it has been created; you may think of it as the object's address in memory.
You can control comparison behaviour of object values by defining a __cmp__
method or a rich comparison method like __eq__
.
SELECT *
FROM Contacts
WHERE ContactId IN
(SELECT a.ContactID
FROM
(SELECT ContactId, Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Postcode LIKE '%N%W%1%0%1%') a
WHERE a.P LIKE 'NW101%')
Just don't make it a select multiple, but set a size to it, such as:
<select name="user" id="userID" size="3">
<option>John</option>
<option>Paul</option>
<option>Ringo</option>
<option>George</option>
</select>
Working example: https://jsfiddle.net/q2vo8nge/
For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (@DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):
Update-Database <Name of last good migration>
Remove-Migration
For example, in my current development the command became
PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM>
The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.
There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:
PM> get-help entityframework
Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)
Initially I tried Remove-Migration by itself and found the error command confusing:
System.InvalidOperationException: The migration '...' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.
There are already suggestions on improving this wording, but I'd like the error to say something like this:
Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)
Output from the EF Core help command follows:
PM> get-help entityframework
_/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\
TOPIC
about_EntityFrameworkCore
SHORT DESCRIPTION
Provides information about Entity Framework Core commands.
LONG DESCRIPTION
This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.
The following Entity Framework cmdlets are included.
Cmdlet Description
-------------------------- ---------------------------------------------------
Add-Migration Adds a new migration.
Remove-Migration Removes the last migration.
Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database.
Script-Migration Generates a SQL script from migrations.
Update-Database Updates the database to a specified migration.
Use-DbContext Sets the default DbContext to use.
SEE ALSO
Add-Migration
Remove-Migration
Scaffold-DbContext
Script-Migration
Update-Database
Use-DbContext
Most programs will check the $EDITOR
environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.
~/.bashrc
file:export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc
If you are using zsh, use ~/.zshrc
instead of ~/.bashrc
.
Yes. You were missing a '{' under the public class line. And then one at the end of your code to close it.
There is a faster way I found that does not require looping through the entire file
only on *nix systems, there might be a similar way on windows ...
$file = '/path/to/your.file';
//Get number of lines
$totalLines = intval(exec("wc -l '$file'"));
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Even easier: via the requests module.
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)
To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):
import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
in php
echo '<a href="' . $folder_path . '">Link text</a>';
or
<a href="<?=$folder_path?>">Link text</a>;
or
<a href="<?php echo $folder_path ?>">Link text</a>;
hello = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
if hello[item] == ' ':
#if there is a match, rebuild the list with the list before the item + the list after the item
hello = hello[:item] + hello [item + 1:]
print hello
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
Example:
Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;
Write the following inside phpini_path.php
( or AnyNameAsYouLike.php
) and run it in the browser.
<?php phpinfo();?>
Among various other parameters you'll get Loaded Configuration File
parameter which value is the path of php.ini
on the server.
The location of php.ini
depends on server operating system:
Windows (With Xampp Installation):
/xampp/php/php.ini
macOS, OS X:
/private/etc/php.ini
Linux:
/etc/php.ini
/usr/bin/php5/bin/php.ini
/etc/php/php.ini
/etc/php5/apache2/php.ini
I just found this solution below on the W3 CSS page and it answered my problem.
img {
display: block;
margin-left: auto;
margin-right: auto;
}
nanoScrollerJS is simply to use. I always use them...
Browser compatibility:
Mobile browsers support:
Code example from the Documentation,
<div id="about" class="nano">
<div class="nano-content"> ... content here ... </div>
</div>
1) @RequestParam
is used to extract query parameters
http://localhost:3000/api/group/test?id=4
@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
while @PathVariable
is used to extract data right from the URI:
http://localhost:3000/api/group/test/4
@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
System.out.println("This is test");
return ResponseEntity.ok().body(id);
}
2) @RequestParam
is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable
is more suitable for RESTful web services where URL contains values.
3) @RequestParam
annotation can specify default values if a query parameter is not present or empty by using a defaultValue
attribute, provided the required attribute is false
:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
return "Required element of request param";
}
}
public static void copyFolder(File source, File destination)
{
if (source.isDirectory())
{
if (!destination.exists())
{
destination.mkdirs();
}
String files[] = source.list();
for (String file : files)
{
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
}
else
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(source);
out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
{
out.write(buffer, 0, length);
}
}
catch (Exception e)
{
try
{
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
I recently came up with a version that avoids loops, using log2
to determine the size order which doubles as a shift and an index into the suffix list:
from math import log2
_suffixes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
def file_size(size):
# determine binary order in steps of size 10
# (coerce to int, // still returns a float)
order = int(log2(size) / 10) if size else 0
# format file size
# (.4g results in rounded numbers for exact matches and max 3 decimals,
# should never resort to exponent values)
return '{:.4g} {}'.format(size / (1 << (order * 10)), _suffixes[order])
Could well be considered unpythonic for its readability, though.
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
Use the HTML entity ∞
or ∞
.
I would like to point out that TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface.
Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example:
var obj : any = new Foo();
if (obj.someInterfaceMethod) {
...
}
There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it
--Version 2
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s
on p.ProductID = s.ProdctId
Source code of CSS/JS we usually minified/compress. Now if we want to debug those minified files then we have to add following line at the end of minified file
/*# sourceMappingURL=bootstrap.min.css.map */
This tells compiler where is source file actually mapped.
In the case of JS its make sense
but in the case of CSS, its actually debugging of SCSS.
To Remove Warning: remove /*# sourceMappingURL=bootstrap.min.css.map */ from the end of minified file
, .
May be little late. But hope this helps.
public static class Utilities
{
public static string IsActive(this HtmlHelper html,
string control,
string action)
{
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeControl = (string)routeData.Values["controller"];
// both must match
var returnActive = control == routeControl &&
action == routeAction;
return returnActive ? "active" : "";
}
}
And usage as follow:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class='@Html.IsActive("Home", "Index")'>
@Html.ActionLink("Home", "Index", "Home")
</li>
<li class='@Html.IsActive("Home", "About")'>
@Html.ActionLink("About", "About", "Home")
</li>
<li class='@Html.IsActive("Home", "Contact")'>
@Html.ActionLink("Contact", "Contact", "Home")
</li>
</ul>
</div>
Got reference from http://www.codingeverything.com/2014/05/mvcbootstrapactivenavbar.html
You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.
To view data structures in Perl you can use Data::Dumper
. To print a string you can use say
, which adds a newline character "\n"
after every call instead of adding it explicitly.
I usually use \s
which matches a whitespace character. If you add +
it matches one or more whitespace characters. You can read more about it here perlre
.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use feature 'say';
my $line = "file1.gz file2.gz file3.gz";
my @abc = split /\s+/, $line;
print Dumper \@abc;
say for @abc;
First of all check error log in the path that your webserver indicates. Then maybe the browser is showing friendly error messages, so disable it.
https://superuser.com/questions/202244/show-http-error-details-in-google-chrome
Another way is to use a utility function (you could make this a static method of a generic utility class if you like):
byte[] concat(byte[]...arrays)
{
// Determine the length of the result array
int totalLength = 0;
for (int i = 0; i < arrays.length; i++)
{
totalLength += arrays[i].length;
}
// create the result array
byte[] result = new byte[totalLength];
// copy the source arrays into the result array
int currentIndex = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
currentIndex += arrays[i].length;
}
return result;
}
Invoke like so:
byte[] a;
byte[] b;
byte[] result = concat(a, b);
It will also work for concatenating 3, 4, 5 arrays, etc.
Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.
Maybe because you have a tag like a parent of the tag. That why you have to click two time the images.
For me the solution is this: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb
Best way to do what you want is to add another server block:
server {
#implemented by default, change if you need different ip or port
#listen *:80 | *:8000;
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
Important: New server
block is the right way to do this, if
is evil. You must use locations and servers instead of if
if it's possible. Rewrite
is sometimes evil too, so replaced it with return
.
Here's another option, which is less efficient but more concise. It's how I generally handle this sort of problem:
Get-ChildItem -Recurse .\targetdir -Exclude *.log |
Where-Object { $_.FullName -notmatch '\\excludedir($|\\)' }
The \\excludedir($|\\)'
expression allows you to exclude the directory and its contents at the same time.
Update: Please check the excellent answer from msorens for an edge case flaw with this approach, and a much more fleshed out solution overall.
Well, despite the fact that you asked that we not "simply" link to other resources, it's pretty foolish when there already exists a community grown (and growing) resource that's really quite good: the Git Community Book. Seriously, this 20+ questions in a question is going to be anything but concise and consistent. The Git Community Book is available as both HTML and PDF and answers many of your questions with clear, well formatted and peer reviewed answers and in a format that allows you to jump straight to your problem at hand.
Alas, if my post really upsets you then I'll delete it. Just say so.
Why not write a little method yourself
public Character[] toCharacterArray( String s ) {
if ( s == null ) {
return null;
}
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++) {
/*
Character(char) is deprecated since Java SE 9 & JDK 9
Link: https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html
array[i] = new Character(s.charAt(i));
*/
array[i] = s.charAt(i);
}
return array;
}
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "POST",
url: urlToSend,
data: { id: clickedButton.val(), access_token: $("#access_token").val() },
success:function(result){
alert('ok');
},
error:function(result)
{
alert('error');
}
});
}
$(document).ready(function(){
$("#button_1").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
$("#button_2").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
});
Based on @seb's solution, I created a subclass of RecyclerView.Adapter that supports an arbitrary number of headers and footers.
https://gist.github.com/mheras/0908873267def75dc746
Although it seems to be a solution, I also think this thing should be managed by the LayoutManager. Unfortunately, I need it now and I don't have time to implement a StaggeredGridLayoutManager from scratch (nor even extend from it).
I'm still testing it, but you can try it out if you want. Please let me know if you find any issues with it.
Try this:
<div class="form-group">
<label class="control-label" for="Company">Company</label>
<select id="Company" class="form-control" name="Company">
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
</div>
I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master
.
In simple words
$.ajax("info.txt").done(function(data) {
alert(data);
}).fail(function(data){
alert("Try again champ!");
});
if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.
If you don't feel like importing anything, you can try:
raise SystemExit, 0
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
On Mac
Netbeans 8.0.2 Tools -> Plugins -> type in search: Dark Look and Feel. Then install plugin.
NOTE: There is no "Option" Or "Appearance" in the "Tools" section in Netbeans 8.0.2.
This way you always know what the size is, because a specific type is dedicated to sizes. The very own question shows that it can be an issue: is it an int
or an unsigned int
? Also, what is the magnitude (short
, int
, long
, etc.)?
Because there is a specific type assigned, you don't have to worry about the length or the signed-ness.
The actual definition can be found in the C++ Reference Library, which says:
Type:
size_t
(Unsigned integral type)Header:
<cstring>
size_t
corresponds to the integral data type returned by the language operatorsizeof
and is defined in the<cstring>
header file (among others) as an unsigned integral type.In
<cstring>
, it is used as the type of the parameternum
in the functionsmemchr
,memcmp
,memcpy
,memmove
,memset
,strncat
,strncmp
,strncpy
andstrxfrm
, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.It is also used as the return type for
strcspn
,strlen
,strspn
andstrxfrm
to return sizes and lengths.
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
You can use the CSS property "background-color: transparent;", or use apha on rgba color representation. Example: "background-color: rgba(216,240,218,0);"
The apha is the last value. It is a decimal number that goes from 0 (totally transparent) to 1 (totally visible).
Another option to fine-tune the line height of an icon is by using a percentage of the vertical-align
property. Usually, 0% is a the bottom, and 100% at the top, but one could use negative values or more than a hundred to create interesting effects.
.my-element i.fa {
vertical-align: 100%; // top
vertical-align: 50%; // middle
vertical-align: 0%; // bottom
}
A possible reason for the "Unresolved external symbol" error can be the function calling convention.
Make sure that all the source files are using same standard (.c or .cpp), or specify the calling convention.
Otherwise, if one file is a C file (source.c) and another file is a .cpp file, and they link to the same header, then the "unresolved external symbol" error will be thrown, because the function is first defined as a C cdecl function, but then C++ file using the same header will look for a C++ function.
To avoid the "Unresolved external symbol error", make sure that the function calling convention is kept the same among the files using it.
It is very simple to make a variable global in a class:
a = 0
class b():
global a
a = 10
>>> a
10
java -classpath Predit.jar your.package.name.MainClass
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
Alternatively if adding extra library such as hamcrest
is not desirable, the logic can be implemented as utility method using junit
dependency only:
public static void assertGreaterThan(int greater, int lesser) {
assertGreaterThan(greater, lesser, null);
}
public static void assertGreaterThan(int greater, int lesser, String message) {
if (greater <= lesser) {
fail((StringUtils.isNotBlank(message) ? message + " ==> " : "") +
"Expected: a value greater than <" + lesser + ">\n" +
"But <" + greater + "> was " + (greater == lesser ? "equal to" : "less than") + " <" + lesser + ">");
}
}
You can try to add some time.sleep
calls to your code.
It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.
In order to avoid your code from crashing, try to catch this error with try .. except
around the urllib2 calls.
In ---- model:
Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
Change the class ----- extends Model
to class ----- extends Eloquent
You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate
function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
Add -storepass to keytool arguments.
keytool -storepasswd -storepass '' -keystore mykeystore.jks
But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password
$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
I've been using AJC Grep daily for years. The only major limitation I've found is that file paths are limited to 255 characters and it stops when it encounters one, rather than just issuing a warning. It's annoying but doesn't happen very often.
I use it on 64-bit Windows 7 Ultimate, so its 64-bit credentials are fine.
I use this one. It allows you to determine the length you want the result to be as well as a default padding character if one is not provided. Of course you can customize the length of the input and output for whatever maximums you are running into.
/*===============================================================
Author : Joey Morgan
Create date : November 1, 2012
Description : Pads the string @MyStr with the character in
: @PadChar so all results have the same length
================================================================*/
CREATE FUNCTION [dbo].[svfn_AMS_PAD_STRING]
(
@MyStr VARCHAR(25),
@LENGTH INT,
@PadChar CHAR(1) = NULL
)
RETURNS VARCHAR(25)
AS
BEGIN
SET @PadChar = ISNULL(@PadChar, '0');
DECLARE @Result VARCHAR(25);
SELECT
@Result = RIGHT(SUBSTRING(REPLICATE('0', @LENGTH), 1,
(@LENGTH + 1) - LEN(RTRIM(@MyStr)))
+ RTRIM(@MyStr), @LENGTH)
RETURN @Result
END
Your mileage may vary. :-)
Joey Morgan
Programmer/Analyst Principal I
WellPoint Medicaid Business Unit
Select * from people p, address a where p.id = a.person_id and a.zip='97229';
Or you must TRY using JOIN
which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';
Here p.*
means it will show all the columns of PERSONS table.
It is also possible to use FormData()
. But you need to set contentType
as false
:
var data = new FormData();
data.append('name', 'Bob');
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: false,
data: data,
dataType: 'json'
});
}
I had a similar problem due to a zombie vim.exe process.
Killing it in Task Manager, followed by a git rebase --abort
fixed it.
public int gcd(int num1, int num2) {
int max = Math.abs(num1);
int min = Math.abs(num2);
while (max > 0) {
if (max < min) {
int x = max;
max = min;
min = x;
}
max %= min;
}
return min;
}
This method uses the Euclid’s algorithm to get the "Greatest Common Divisor" of two integers. It receives two integers and returns the gcd of them. just that easy!
<select ng-model="selectedCar" ><option ng-repeat="car in cars " value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});
Add the @JsonIgnoreProperties("fieldname")
annotation to your POJO.
Or you can use @JsonIgnore
before the name of the field you want to ignore while deserializing JSON. Example:
@JsonIgnore
@JsonProperty(value = "user_password")
public String getUserPassword() {
return userPassword;
}
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
You can set shadow to your view from storyboard also
You could also try the shortKeys jQuery plugin. Usage example:
$(document).shortkeys({
'g': function () { alert('g'); }
});
Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}
Try BufferedReader.readLine()
instead of all this complication. It will recognize all possible line terminators.
I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.
cmd /k mybatchfile.cmd
if you want the command window to stay (on desktop) after batch script have finished.It could be quotes themselves that are the entire problem. I had a similar problem and it was due to quotes around the column name in the CREATE TABLE statement. Note there were no whitespace issues, just quotes causing problems.
The column looked like it was called anID
but was really called "anID"
. The quotes don't appear in typical queries so it was hard to detect (for this postgres rookie). This is on postgres 9.4.1
Some more detail:
Doing postgres=# SELECT * FROM test;
gave:
anID | value
------+-------
1 | hello
2 | baz
3 | foo (3 rows)
but trying to select just the first column SELECT anID FROM test;
resulted in an error:
ERROR: column "anid" does not exist
LINE 1: SELECT anID FROM test;
^
Just looking at the column names didn't help:
postgres=# \d test;
Table "public.test"
Column | Type | Modifiers
--------+-------------------+-----------
anID | integer | not null
value | character varying |
Indexes:
"PK on ID" PRIMARY KEY, btree ("anID")
but in pgAdmin if you click on the column name and look in the SQL pane it populated with:
ALTER TABLE test ADD COLUMN "anID" integer;
ALTER TABLE test ALTER COLUMN "anID" SET NOT NULL;
and lo and behold there are the quoutes around the column name. So then ultimately postgres=# select "anID" FROM test;
works fine:
anID
------
1
2
3
(3 rows)
Same moral, don't use quotes.
You can do it in this way
private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "[email protected]";
and inside onCreate method
nameEdit = (EditText) findViewById(R.id.name);
nameEdit.setText(nameDefaultValue);
nameEdit.setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
return false;
}
});
nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
nameEdit.setText(nameDefaultValue);
} else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
}
});
emailEdit = (EditText)findViewById(R.id.email);
emailEdit.setText(emailDefaultValue);
emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
emailEdit.setText(emailDefaultValue);
} else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
emailEdit.setText("");
}
}
});
You can use the @NamedEntityGraph
annotation to your entity to create a loadable query that set which collections you want to load on your query.
The main advantage of this choice is that hibernate makes one single query to retrieve the entity and its collections and only when you choose to use this graph, like this:
Entity configuration
@Entity
@NamedEntityGraph(name = "graph.myEntity.addresesAndPersons",
attributeNodes = {
@NamedAttributeNode(value = "addreses"),
@NamedAttributeNode(value = "persons"
})
Usage
public MyEntity findNamedGraph(Object id, String namedGraph) {
EntityGraph<MyEntity> graph = em.getEntityGraph(namedGraph);
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.loadgraph", graph);
return em.find(MyEntity.class, id, properties);
}
Another way to do it is in your class:
import android.graphics.Color; // add to top of class
Button btn = (Button)findViewById(R.id.btn);
// set button text colour to be blue
btn.setTextColor(Color.parseColor("blue"));
// set button text colour to be red
btn.setTextColor(Color.parseColor("#FF0000"));
// set button text color to be a color from your resources (could be strings.xml)
btn.setTextColor(getResources().getColor(R.color.yourColor));
// set button background colour to be green
btn.setBackgroundColor(Color.GREEN);
function timerCtrl ($scope,$interval) {
$scope.seconds = 0;
var timer = $interval(function(){
$scope.seconds++;
$scope.$apply();
console.log($scope.countDown);
}, 1000);
}
When you drag a custom framework into a project under Xcode 10.1, it assumes that the framework is a system framework and puts the framework into "Link Binary With Libraries" section of "Build Phases" under your target.
System frameworks are already on the device so it is not copied over to the device and thus cannot execute at runtime so KABOOM (crash in __abort_with_payload, and disinforming error: "Reason: image not found"). This is because the framework code is not copied to the device...
In reality, to have Xcode both link the custom framework and ensure that it is copied along with your code to the iOS device (real or simulator) the custom framework needs to be moved to "Copy Bundle Resources". This ultimately packages the framework along with your code executable to be available on the device together.
To add a custom framework to a project and avoid the Apple crash:
The custom framework thus gets copied along with your code to your target device and is available at runtime.
[editorial: you would think Xcode would be smart enough to figure out the difference between one of it's system frameworks which need not be copied to the device and a custom framework that is, oh I don't know, in the project root directory hierarchy... ]
Sometimes none of these would work for me. So I used to create a new web project in VS and select Authorization as "Individual User Accounts". I believe this work with some higher version of .NET Framework or something. But when you do this it will have your connection details. Mostly something like this
(LocalDb)\MSSQLLocalDB
Gradle Scripts ->
build.gradle (Module: app) ->
minSdkVersion (Your min sdk version)
When I say file system I meant the whole file system. But you can only browse part of the file system on a retail phone, perhaps even most of file system but not ./data. Sorry for any confusion this may have caused.
This is alarming to me because I have a rooted my retail Nexus One and a developer/unlocked Nexus One. Since I rooted my retail Nexus One I can't figure out why I can't browse the whole file system like I can on my developer Nexus One.
In this code:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
... the self
variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A
class and call its methods, it will be passed automatically, as in ...
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
The __init__
method is roughly what represents a constructor in Python. When you call A()
Python creates an object for you, and passes it as the first parameter to the __init__
method. Any additional parameters (e.g., A(24, 'Hello')
) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.
To properly display one div on top of another, we need to use the property position
as follows:
position: relative
position: absolute
I found a good example here:
.dvContainer {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
.dvInsideTL {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 150px;_x000D_
height: 100px;_x000D_
background-color: #ff751a;_x000D_
opacity: 0.5;_x000D_
}
_x000D_
<div class="dvContainer">_x000D_
<table style="width:100%;height:100%;">_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Top Left</td>_x000D_
<td style="width:50%;text-align:center">Top Right</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Bottom Left</td>_x000D_
<td style="width:50%;text-align:center">Bottom Right</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="dvInsideTL">_x000D_
</div>_x000D_
</div>
_x000D_
I hope this helps,
Zag.
Specify bash instead of sh when running the script. I personally noticed they are different under ubuntu 12.10:
bash script.sh arg0 ... argn
Start the two terminal on the same and 1st terminal run react-native start and second terminal react-native run-android this problem are solve in simply way. And best of luck
The problem is the use of aspect='equal'
, which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.
Normally, this would work:
import matplotlib.pyplot as plt
ax = [plt.subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
plt.subplots_adjust(wspace=0, hspace=0)
The result is this:
However, with aspect='equal'
, as in the following code:
import matplotlib.pyplot as plt
ax = [plt.subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')
plt.subplots_adjust(wspace=0, hspace=0)
This is what we get:
The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal'
forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.
To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio
ax = [fig.add_subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
a.set_aspect('equal')
fig.subplots_adjust(wspace=0, hspace=0)
Here's the result:
I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.
Use tow function to solve it ,Very simple and useful:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />
JQuery:
//Integer Number
$(document).on("input", ".int-number", function (e) {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.
The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:
overflow: auto;
The simplest way to clear floated elements is using the style overflow: auto
on the containing element. This solution works in every modern browsers.
<div style="overflow: auto;">
<img
style="float: right;"
src="path/to/floated-element.png"
width="500"
height="500"
>
<p>Your content here…</p>
</div>
One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.
Using ‘overflow: hidden’ is also a clearfix solution, but will not have scrollbars, however using hidden
will crop any content positioned outside of the containing element.
Note: The floated element is an img
tag in this example, but could be any html element.
Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block
(instead of display: table
) allows margins to collapse properly when elements with clearfix are siblings.
.container::after {
content: "";
display: block;
clear: both;
}
This is the most modern version of the clearfix.
?
?
The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.
Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.
They are listed roughly in chronological order.
Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom
and ::before
property/values and simply use:
.container::after {
content: "";
display: table;
clear: both;
}
This solution does not support for IE 6/7 …on purpose!
Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."
The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.
Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+
.container::before, .container::after {
content: "";
display: table;
}
.container::after {
clear: both;
}
.container {
zoom: 1;
}
This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.
http://www.quirksmode.org/css/clearing.html
- explains how to resolve common issues related to this technique, namely, setting width: 100%
on the container.
.container {
overflow: hidden;
display: inline-block;
display: block;
}
Rather than using the display
property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.
.container {
overflow: hidden;
zoom: 1;
display: block;
}
Another way to clear floats using the overflow
property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom
property triggers hasLayout in IE:
.container {
overflow: hidden;
_overflow: visible; /* for IE */
_zoom: 1; /* for IE */
}
While this works... it is not ideal to use hacks.
This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.
This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html
The quick and dirty solution (with some drawbacks) for when you’re quickly slapping something together:
<br style="clear: both" /> <!-- So dirty! -->
<br style="clear: both" />
tag littered around the markup.\w\-
is probably the best but here just another alternative
Use [:alnum:]
if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";
Use std::cout
, since cout
is defined within the std
namespace. Alternatively, add a using std::cout;
directive.
The block approach avoids running the lookup algorithm for every key:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
NSLog(@"%@ => %@", key, value);
}];
Even though NSDictionary
is implemented as a hashtable (which means that the cost of looking up an element is O(1)
), lookups still slow down your iteration by a constant factor.
My measurements show that for a dictionary d
of numbers ...
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
NSNumber* value = @(i);
dict[value.stringValue] = value;
}
... summing up the numbers with the block approach ...
__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
sum += value.intValue;
}];
... rather than the loop approach ...
int sum = 0;
for (NSString* key in dict)
sum += [dict[key] intValue];
... is about 40% faster.
EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
Building off jeroenk's answer, here's the rundown:
$('button').addClass('disabled'); // Disables visually
$('button').prop('disabled', true); // Disables visually + functionally
$('input[type=button]').addClass('disabled'); // Disables visually
$('input[type=button]').prop('disabled', true); // Disables visually + functionally
$('a').addClass('disabled'); // Disables visually
$('a').prop('disabled', true); // Does nothing
$('a').attr('disabled', 'disabled'); // Disables visually
See fiddle
Change your javascript to:
var input = document.getElementById('userInput').value;
This will get the value that has been types into the text box, not a DOM object
You can call a controller function with AJAX on your view. In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
Unitialized variables check. Link 1 and 2 already seem to do this just fine, though.
I can't say I have used any of these intensively, though :)
new Guid()
makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).
Guid.NewGuid()
makes an actual guid with a unique value, what you probably want.
It looks like all of the answers here didn't take the safe area into consideration.
Since iOS 11, iPhone X had a safe area introduced. This may affect the scrollView's contentInset
.
For iOS 11 and above, to properly scroll to the bottom with the content inset included. You should use adjustedContentInset
instead of contentInset
. Check this code:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.adjustedContentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
contentOffset.x
):extension UIScrollView {
func scrollsToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: contentOffset.x,
y: contentSize.height - bounds.height + adjustedContentInset.bottom)
setContentOffset(bottomOffset, animated: animated)
}
}
References:
Here's a google chrome extension that'll allow you to download your reviews: https://chrome.google.com/webstore/detail/my-play-store-reviews/ldggikfajgoedghjnflfafiiheagngoa?hl=en
For the newer versions of Apache pdfbox. Here is the example from the original source
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.examples.util;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;
/**
* This is a simple text extraction example to get started. For more advance usage, see the
* ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
* ExtractText tool in the tools subproject.
*
* @author Tilman Hausherr
*/
public class ExtractTextSimple
{
private ExtractTextSimple()
{
// example class should not be instantiated
}
/**
* This will print the documents text page by page.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing or extracting the document.
*/
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
usage();
}
try (PDDocument document = PDDocument.load(new File(args[0])))
{
AccessPermission ap = document.getCurrentAccessPermission();
if (!ap.canExtractContent())
{
throw new IOException("You do not have permission to extract text");
}
PDFTextStripper stripper = new PDFTextStripper();
// This example uses sorting, but in some cases it is more useful to switch it off,
// e.g. in some files with columns where the PDF content stream respects the
// column order.
stripper.setSortByPosition(true);
for (int p = 1; p <= document.getNumberOfPages(); ++p)
{
// Set the page interval to extract. If you don't, then all pages would be extracted.
stripper.setStartPage(p);
stripper.setEndPage(p);
// let the magic happen
String text = stripper.getText(document);
// do some nice output with a header
String pageStr = String.format("page %d:", p);
System.out.println(pageStr);
for (int i = 0; i < pageStr.length(); ++i)
{
System.out.print("-");
}
System.out.println();
System.out.println(text.trim());
System.out.println();
// If the extracted text is empty or gibberish, please try extracting text
// with Adobe Reader first before asking for help. Also read the FAQ
// on the website:
// https://pdfbox.apache.org/2.0/faq.html#text-extraction
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
System.exit(-1);
}
}
I also got this problem and found quite simple solution. I have Samsung adb driver installed on my system. I tried "Update driver" -> "Let me pick" -> "Already installed drivers" -> Samsung adb driver. That worked well.
you can use valign="top"
on the td tag it is working perfectly for me.
Use an example of instructions for making a breakfast
If you have experience cooking, you'd execute those instructions asynchronously. you'd start warming the pan for eggs, then start the bacon. You'd put the bread in the toaster, then start the eggs. At each step of the process, you'd start a task, then turn your attention to tasks that are ready for your attention.
Cooking breakfast is a good example of asynchronous work that isn't parallel. One person (or thread) can handle all these tasks. Continuing the breakfast analogy, one person can make breakfast asynchronously by starting the next task before the first completes. The cooking progresses whether or not someone is watching it. As soon as you start warming the pan for the eggs, you can begin frying the bacon. Once the bacon starts, you can put the bread into the toaster.
For a parallel algorithm, you'd need multiple cooks (or threads). One would make the eggs, one the bacon, and so on. Each one would be focused on just that one task. Each cook (or thread) would be blocked synchronously waiting for bacon to be ready to flip, or the toast to pop.
Reference from Asynchronous programming concepts
Maintain a set
and remove a randomly picked-up element (with choice
) until the list is empty:
s = set(range(1, 6))
import random
while len(s) > 0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
In order to create a backup using pg_dump
that is compatible with pg_restore
you must use the --format=custom
/ -Fc
when creating your dump.
From the docs:
Output a custom-format archive suitable for input into pg_restore.
So your pg_dump
command might look like:
pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password
And your pg_restore
command:
pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump
Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.
Doesn't this work: I cant imaging anything else being much quicker or easier.
public static class ExtensionMethodsString
{
public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
{
string working = thisString;
int index = working.IndexOf(oldValue, stringComparison);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, stringComparison);
}
return working;
}
}
More accurately anything that is not 0
is true.
So 1
is true, but so is 2
, 3
... etc.
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close
I had the same thing on windows server. Then I figured out by changing the vars.bat
which is:
set HOME=C:\Program Files (x86)\OpenVPN\easy-rsa
then redo from beginning and everything should be fine.
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
As per my comment in Chase's answer, you can remove a lot of this stuff using element_blank
:
dat <- data.frame(x=runif(10),y=runif(10))
p <- ggplot(dat, aes(x=x, y=y)) +
geom_point() +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0))
p + theme(axis.line=element_blank(),axis.text.x=element_blank(),
axis.text.y=element_blank(),axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),legend.position="none",
panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),plot.background=element_blank())
It looks like there's still a small margin around the edge of the resulting .png when I save this. Perhaps someone else knows how to remove even that component.
(Historical note: Since ggplot2 version 0.9.2, opts
has been deprecated. Instead use theme()
and replace theme_blank()
with element_blank()
.)
First we get an array of keys for this enum. Then, using the map () function, we convert the data to the desired format. id is obtained from the key, name is obtained from enum by the same key.
const converted = Object.keys(GoalProgressMeasurements).map(key => {
return {
id: GoalProgressMeasurements[key],
name: key,
};
});
myList.ToList().Count == 0
. That's all
Whenever I use the moment.js
library I specify the desired format this way:
moment(<your Date goes here>).format("DD-MMM-YYYY")
or
moment(<your Date goes here>).format("DD/MMM/YYYY")
... etc I hope you get the idea
Inside the format function, you put the desired format. The example above will get rid of all unwanted elements from the date such as minutes and seconds
I was trying to @Autowire
a Spring-managed service into my Deserializer
. Somebody tipped me off to Jackson using the new
operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer
. Here's how I was able to @Autowire
my service class into my Deserializer
:
context.xml
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<!-- Add deserializers that require autowiring -->
<property name="deserializersByType">
<map key-type="java.lang.Class">
<entry key="com.acme.Anchor">
<bean class="com.acme.AnchorDeserializer" />
</entry>
</map>
</property>
</bean>
Now that my Deserializer
is a Spring-managed bean, auto-wiring works!
AnchorDeserializer.java
public class AnchorDeserializer extends JsonDeserializer<Anchor> {
@Autowired
private AnchorService anchorService;
public Anchor deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
// Do stuff
}
}
AnchorService.java
@Service
public class AnchorService {}
Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!
With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}
Try something like the following in your case.
class Pill extends React.Component {
render() {
return (
<button className={['pill', this.props.styleName]}>{this.props.children}</button>
);
}
}
In your example, the IF statement will run when it is state = true meaning the else part will run when state = false.
if(turnedOn == true) is the same as if(turnedOn)
if(turnedOn == false) is the same as if(!turnedOn)
If you have:
boolean turnedOn = false;
Or
boolean turnedOn;
Then
if(turnedOn)
{
}
else
{
// This would run!
}
As far as I know there isn't any straight forward HTML Encode/Decode method in javascript.
However, what you can do, is to use JS to create an arbitrary element, set its inner text, then read it using innerHTML.
Let's say, with jQuery, this should work:
var helper = $('chalk & cheese').hide().appendTo('body');
var htmled = helper.html();
helper.remove();
Or something along these lines.
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n
for a new line, or \t
for a tab.
Note that ord()
doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä')
can be 228 if you're using Latin-1, or it can raise a TypeError
if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:
>>> ord(u'?')
12354
Another potential cause is that docker will not follow symbolic links by default (i.e don't use ln -s
).
In order to get rid of duplicates, you can group by drinks.id
. But that way you'll get only one photo for each drinks.id
(which photo you'll get depends on database internal implementation).
Though it is not documented, in case of MySQL, you'll get the photo with lowest id
(in my experience I've never seen other behavior).
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks.id
S.Lott inserted a comment, but it should be an answer: see the same question.
Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:
I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.
You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.
Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.
Your placeholder is replaced by a string and you're not handling it right.
Replace
"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search
with
"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"
My advice is: don't do it!
Any scenario where you treat people as "wrongdoers" is going to result in them fighting back.
Here's my proposal.
Put a small unobtrusive message at the top of the page (regardless of whether ads are being blocked) with the text I *totally* respect your right to block ads
and a link to another page/pop-up entitled Read more ...
.
On the other page, make it clear that you understand it's their computer and they are free to use ad blocking.
Also make it clear in a non-accusatory way that the use of these blockers makes it more difficult for you to deliver great content (explaining why in detail) and that, while you'd prefer the ad blocking to not happen on your site, it's totally their decision. Focus on the positives of turning off blocking.
Those who are vehemently opposed to ads will ignore this but you never stood a chance of convincing them anyway. Those who are indifferent may well be swayed by your appeal since you're not doing the whole "let me get my way or I'll take my ball and go home" thing that honestly should be the exclusive domain of five year old children.
Remember, no-one held a gun to your head and forced you to put your stuff on the net. Treat your readership/users with respect and you'll probably find a good number of them will reciprocate.
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
Shortest possible answer.
HTML
<a data-toggle="collapse" data-parent="#panel-quote-group" href="#collapseQuote">
<span class="toggle-icon glyphicon glyphicon-collapse-up"></span>
</a>
JS:
<script type="text/javascript">
$(function () {
$('a[data-toggle="collapse"]').click(function () {
$(this).find('span.toggle-icon').toggleClass('glyphicon-collapse-up glyphicon-collapse-down');
})
})
</script>
And of course, you can use anything for a selector instead of anchor tag a
and you can also use specific selector instead of this
if your icon lies outside your clicked element.
Check https://pypi.python.org/pypi/tensorflow to see which packages are available.
As of this writing, they don't provide a source package, so if there's no prebuilt one for your platform, this error occurs. If you add -v
to the pip
command line, you'll see it iterating over the packages that are available at PyPI and discarding them for being incompatible.
You need to either find a prebuilt package somewhere else, or compile tensorflow
yourself from its sources by instructions at https://www.tensorflow.org/install/install_sources .
They have a good reason for not building for some platforms though:
win32
package is missing because TensorFlow's dependency, Bazel, only supports win64
.win64
, only 3.5+ is supported because earlier versions are compiled with compilers without C++11 support.The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
This may happen if there is any read and write permission denial to the user. Like C:\Windows\System32\ have restricted access and you are cloned and trying to make from such restricted directory.
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
For anyone trying to
...in 2019, it's worth noting some of the code referenced here no longer exists (officially). Google discontinued support for the "MarkerWithLabel" project a long time ago. It was originally hosted on Google code here, now it's unofficially hosted on Github here.
But there is another project Google maintained until 2016, called "MapLabel"s. That approach is different (and arguably better). You create a separate map label object with the same origin as the marker instead of adding a mapLabel option to the marker itself. You can make a marker with label with multiple characters using js-marker-label.
You have most of the code…
CURLOPT_HTTPHEADER
for curl_setopt()
takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header
array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
Create a list of namedtuples
It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:
d = {'John':5, 'Alex':10, 'Richard': 7}
You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:
>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
How to do this:
list in random order or keeping order of collections.OrderedDict:
import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
in order, sorted by value ('score'):
import collections
Player = collections.namedtuple('Player', 'score name')
sorted with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorted with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
check Robocopy:
ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT
make sure you check what robocopy parameter you want. this is just an example.
type robocopy /?
in a comandline/powershell on your windows system.
lines = open(filename).read().splitlines()
As has been mentioned cron is deprecated (but supported), and launchd is recommended for OS X.
This is taken from developer.apple.com
If the system is turned off or asleep, cron jobs do not execute; they will not run until the next designated time occurs.
If you schedule a launchd job by setting the StartCalendarInterval key and the computer is asleep when the job should have run, your job will run when the computer wakes up. However, if the machine is off when the job should have run, the job does not execute until the next designated time occurs.
All other launchd jobs are skipped when the computer is turned off or asleep; they will not run until the next designated time occurs.
Consequently, if the computer is always off at the job’s scheduled time, both cron jobs and launchd jobs never run. For example, if you always turn your computer off at night, a job scheduled to run at 1 A.M. will never be run.
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
EDIT: See nice collection of JavaScript Style Guides And Beautifiers.
>>> import pandas as pd
>>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
>>> dict(sorted(df.values.tolist())) # Sort of sorted...
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> from collections import OrderedDict
>>> OrderedDict(df.values.tolist())
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
Explaining solution: dict(sorted(df.values.tolist()))
Given:
df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
[out]:
Letter Position
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
Try:
# Get the values out to a 2-D numpy array,
df.values
[out]:
array([['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5]], dtype=object)
Then optionally:
# Dump it into a list so that you can sort it using `sorted()`
sorted(df.values.tolist()) # Sort by key
Or:
# Sort by value:
from operator import itemgetter
sorted(df.values.tolist(), key=itemgetter(1))
[out]:
[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
Lastly, cast the list of list of 2 elements into a dict.
dict(sorted(df.values.tolist()))
[out]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Answering @sbradbio comment:
If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is:
from collections import defaultdict
import pandas as pd
multivalue_dict = defaultdict(list)
df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']})
for idx,row in df.iterrows():
multivalue_dict[row['Position']].append(row['Letter'])
[out]:
>>> print(multivalue_dict)
defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']})
select * from [table] where (column)=(select max(column)from [table] where column < (select max(column)from [table]))
You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.
Read more about pull here.
Everyone is right: stick with POST for non-idempotent requests.
What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!
It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)
Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:
Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]
Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.
In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)
Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.
Try the following:
create these folders under storage/framework:
sessions
views
cache
Now it should work
var sizef = document.getElementById('input-file-id').files[0].size;
if(sizef > 210000){
alert('sorry error');
}else {
//action
}
For getting the buffer size in c/c++ program the following is the flow
int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
preventDefault
is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault
with no problem.
We also experienced this problem and I like all the answers that suggest using a script defined in package.json
.
For our solutions we often use the following sequence:
npm install --save-dev webpack-cli
(if you're using webpack v4 or later, otherwise use npm install --save-dev webpack
, see webpack installation, retrieved 19 Jan 2019)npx webpack
Step 1 is a one-off. Step 2 also checks ./node_modules/.bin
. You can add the second step as a npm script to package.json
as well, for example:
{
...
"scripts": {
...
"build": "npx webpack --mode development",
...
},
...
}
and then use npm run build
to execute this script.
Tested this solution with npm version 6.5.0, webpack version 4.28.4 and webpack-cli version 3.2.1 on Windows 10, executing all commands inside of a PowerShell window. My nodejs version is/was 10.14.2. I also tested this on Ubuntu Linux version 18.04.
I'd advise against installing webpack globally, in particular if you are working with a lot of different projects each of which may require a different version of webpack. Installing webpack globally locks you down to a particular version across all projects on the same machine.
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
Encountered similar problem: parsing CSV file with special characters like é, è, ö etc ...
The following worked fine for me:
To represent the characters correctly on the html page, the header was needed :
header('Content-Type: text/html; charset=UTF-8');
In order to parse every character correctly, I used:
utf8_encode(fgets($file));
Dont forget to use in all following string operations the 'Multibyte String Functions', like:
mb_strtolower($value, 'UTF-8');
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
simplest way i found is viewport-height in css..
div {height: 100vh;}
this takes the viewport-height of the browser-window and updates it during resizes.
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).
When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.
This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx
Enabling TLS 1.0 solved our issues as well (after disabling SSL v3). (Server 2012 R2 with ASP.net 4.0 website processing against PPI pay services). This is the RegEdit script I used to set everything the way I wanted. We only disabled SSL v3 for the Client and not the server as doing that broke other things that we were not ready to deal with yet. After we upgrade the site to .Net 4.5.2 then we will disable TLS 1.0 again.
This script enables all protocols, Server and Client except for SSL v3 for the Client.
Be sure to backup your registry!
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
In Swift 4.2 and Xcode 10.1
You can change your navigation bar colour from your AppDelegate directly to your entire project.
In didFinishLaunchingWithOptions launchOptions:
write below to lines of code
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
Here
tintColor is for to set background images like back button & menu lines images etc. (See below left and right menu image)
barTintColor is for navigation bar background colour
If you want to set specific view controller navigation bar colour, write below code in viewDidLoad()
//Add navigation bar colour
navigationController?.navigationBar.barTintColor = UIColor(red: 2/255, green: 96/255, blue: 130/255, alpha: 1.0)
navigationController?.navigationBar.tintColor = UIColor.white
var sum1 = 0
for i in 0...100{
sum1 += i
}
print (sum1)
for i in (10...100).reverse(){
sum1 /= i
}
print(sum1)
The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.
Use a JavaScript file and then use module exports.
Example:
var Globals = {
'domain':'www.MrGlobal.com';
}
module.exports = Globals;
Then if you want to use these, use require.
var globals = require('globals'); // << globals.js path
globals.domain // << Domain.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str = (prestationEco)o; //As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});
Here is a helper that I wrote to solve this issue for my projects. It makes it super simple and easy to be able to clear everything out quickly and with a single command.
Are you looking for
#if BOOST_VERSION != "1.2"
#error "Bad version"
#endif
Not great if BOOST_VERSION is a string, like I've assumed, but there may also be individual integers defined for the major, minor and revision numbers.
verbose: Integer
. 0, 1, or 2. Verbosity mode.
Verbose=0 (silent)
Verbose=1 (progress bar)
Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc:
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc:
0.8071 - val_loss: 0.4617 - val_acc: 0.8168
Verbose=2 (one line per epoch)
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046