I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.
It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.
Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export
Using only ES6 module syntax:
// esModule.js
export default 'defaultExport';
export const namedExport = () => {};
// esModule.test.js
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function
Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.
Adding Quotes
I started using this quick and dirty function in my .vimrc
:
vnoremap q <esc>:call QuickWrap("'")<cr>
vnoremap Q <esc>:call QuickWrap('"')<cr>
function! QuickWrap(wrapper)
let l:w = a:wrapper
let l:inside_or_around = (&selection == 'exclusive') ? ('i') : ('a')
normal `>
execute "normal " . inside_or_around . escape(w, '\')
normal `<
execute "normal i" . escape(w, '\')
normal `<
endfunction
So now, I visually select whatever I want (typically via viw
- visually select inside word) in quotes and press Q for double quotes, or press q for single quotes.
Removing Quotes
vnoremap s <esc>:call StripWrap()<cr>
function! StripWrap()
normal `>x`<x
endfunction
I use vim-textobj-quotes so that vim treats quotes as a text objects. This means I can do vaq
(visually select around quotes. This finds the nearest quotes and visually selects them. (This is optional, you can just do something like f"vww
). Then I press s
to strip the quotes from the selection.
Changing Quotes
KISS. I remove quotes then add quotes.
For example, to replace single quotes with double quotes, I would perform the steps:
1. remove single quotes: vaqs
, 2. add new quotes: vwQ
.
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
There's actually a pretty easy way to do this. The code should be something like:
<script type="test/javascript">
function showcontent(x){
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 1) {
document.getElementById('content').innerHTML = "<img src='loading.gif' />";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('content').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', x+'.html', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(null);
}
And in the HTML:
<body onload="showcontent(main)"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>
I did something like that on my page and it works great.
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
I have a tip for those, who want to get various aggregated values from the same table.
Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).
Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points)
AND then by SUM(points WHERE type = x)
. That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).
The SQL would be:
SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id
The beauty of this is in the SUM(points.points * (points.type = 7))
where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.
You can use CreateDefaultBuilder
which will automatically build and pass a configuration object to your startup class:
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
public class Startup
{
public Startup(IConfiguration configuration) // automatically injected
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
/* ... */
}
CreateDefaultBuilder
automatically includes the appropriate appsettings.Environment.json
file so add a separate appsettings file for each environment:
Then set the ASPNETCORE_ENVIRONMENT
environment variable when running / debugging
Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:
For Visual Studio go to Project > Properties > Debug > Environment Variables:
For Visual Studio Code, edit .vscode/launch.json
> env
:
Using Launch Settings, edit Properties/launchSettings.json
> environmentVariables
:
Which can also be selected from the Toolbar in Visual Studio
Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS
Note: When an app is launched with dotnet run,
launchSettings.json
is read if available, andenvironmentVariables
settings in launchSettings.json override environment variables.
Host.CreateDefaultBuilder
work?.NET Core 3.0 added Host.CreateDefaultBuilder
under platform extensions which will provide a default initialization of IConfiguration
which provides default configuration for the app in the following order:
appsettings.json
using the JSON configuration provider.appsettings.Environment.json
using the JSON configuration provider. For example:
appsettings.Production.json
orappsettings.Development.json
- App secrets when the app runs in the Development environment.
- Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
It has to be any one of the given sizes and a minimum of 2 but up to 8 screenshots are accepted in Google Playstore.
Fast-forward almost 9 years since this was first asked, and in the world of .NET Core and .NET Standard, it seems the most common options we have for URL-encoding are WebUtility.UrlEncode (under System.Net
) and Uri.EscapeDataString. Judging by the most popular answer here and elsewhere, Uri.EscapeDataString appears to be preferable. But is it? I did some analysis to understand the differences and here's what I came up with:
WebUtility.UrlEncode
encodes space as +
; Uri.EscapeDataString
encodes it as %20
.Uri.EscapeDataString
percent-encodes !
, (
, )
, and *
; WebUtility.UrlEncode
does not.WebUtility.UrlEncode
percent-encodes ~
; Uri.EscapeDataString
does not.Uri.EscapeDataString
throws a UriFormatException
on strings longer than 65,520 characters; WebUtility.UrlEncode
does not. (A more common problem than you might think, particularly when dealing with URL-encoded form data.)Uri.EscapeDataString
throws a UriFormatException
on the high surrogate characters; WebUtility.UrlEncode
does not. (That's a UTF-16 thing, probably a lot less common.)For URL-encoding purposes, characters fit into one of 3 categories: unreserved (legal in a URL); reserved (legal in but has special meaning, so you might want to encode it); and everything else (must always be encoded).
According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=
And the unreserved characters are alphanumeric and -._~
Uri.EscapeDataString clearly defines its mission: %-encode all reserved and illegal characters. WebUtility.UrlEncode is more ambiguous in both definition and implementation. Oddly, it encodes some reserved characters but not others (why parentheses and not brackets??), and stranger still it encodes that innocently unreserved ~
character.
Therefore, I concur with the popular advice - use Uri.EscapeDataString when possible, and understand that reserved characters like /
and ?
will get encoded. If you need to deal with potentially large strings, particularly with URL-encoded form content, you'll need to either fall back on WebUtility.UrlEncode and accept its quirks, or otherwise work around the problem.
EDIT: I've attempted to rectify ALL of the quirks mentioned above in Flurl via the Url.Encode
, Url.EncodeIllegalCharacters
, and Url.Decode
static methods. These are in the core package (which is tiny and doesn't include all the HTTP stuff), or feel free to rip them from the source. I welcome any comments/feedback you have on these.
Here's the code I used to discover which characters are encoded differently:
var diffs =
from i in Enumerable.Range(0, char.MaxValue + 1)
let c = (char)i
where !char.IsHighSurrogate(c)
let diff = new {
Original = c,
UrlEncode = WebUtility.UrlEncode(c.ToString()),
EscapeDataString = Uri.EscapeDataString(c.ToString()),
}
where diff.UrlEncode != diff.EscapeDataString
select diff;
foreach (var diff in diffs)
Console.WriteLine($"{diff.Original}\t{diff.UrlEncode}\t{diff.EscapeDataString}");
I am reproducing the same issue and it's really annoying. I've found these useful:
HttpClient - dealing with aggregate exceptions
Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException
Some code in case the links go nowhere:
var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
var x = await c.GetAsync("http://linqpad.net", cts.Token);
}
catch(WebException ex)
{
// handle web exception
}
catch(TaskCanceledException ex)
{
if(ex.CancellationToken == cts.Token)
{
// a real cancellation, triggered by the caller
}
else
{
// a web request timeout (possibly other things!?)
}
}
NOTE: the author of this polyfill claims it "works in pretty much any browser you can imagine" but according to the comments that's not true for IE11, however IE11 has native support, as do most modern browsers
Placeholders.js is the best placeholder polyfill I've seen, is lightweight, doesn't depend on JQuery, covers other older browsers (not just IE), and has options for hide-on-input and run-once placeholders.
I needed a solution to convert columns to rows in Microsoft SQL Server, without knowing the colum names (used in trigger) and without dynamic sql (dynamic sql is too slow for use in a trigger).
I finally found this solution, which works fine:
SELECT
insRowTbl.PK,
insRowTbl.Username,
attr.insRow.value('local-name(.)', 'nvarchar(128)') as FieldName,
attr.insRow.value('.', 'nvarchar(max)') as FieldValue
FROM ( Select
i.ID as PK,
i.LastModifiedBy as Username,
convert(xml, (select i.* for xml raw)) as insRowCol
FROM inserted as i
) as insRowTbl
CROSS APPLY insRowTbl.insRowCol.nodes('/row/@*') as attr(insRow)
As you can see, I convert the row into XML (Subquery select i,* for xml raw, this converts all columns into one xml column)
Then I CROSS APPLY a function to each XML attribute of this column, so that I get one row per attribute.
Overall, this converts columns into rows, without knowing the column names and without using dynamic sql. It is fast enough for my purpose.
(Edit: I just saw Roman Pekar answer above, who is doing the same. I used the dynamic sql trigger with cursors first, which was 10 to 100 times slower than this solution, but maybe it was caused by the cursor, not by the dynamic sql. Anyway, this solution is very simple an universal, so its definitively an option).
I am leaving this comment at this place, because I want to reference this explanation in my post about the full audit trigger, that you can find here: https://stackoverflow.com/a/43800286/4160788
If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.
What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:
header('Content-Type: application/json; charset=utf-8');
The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.
When you have two or more (in the example below there're three) elements in the string, then you can use comma to separate these items:
date, time, event_name = ev.get_text(separator='@').split("@")
After this line of code, the three variables will have values from three parts of the variable ev
So, if the variable ev contains this string and we apply separator '@':
Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL
Then, after split operation the variable
You can use RelativeLayout. Let's say you wanted a 30x40 ImageView at position (50,60) inside your layout. Somewhere in your activity:
// Some existing RelativeLayout from your layout xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
More examples:
Places two 30x40 ImageViews (one yellow, one red) at (50,60) and (80,90), respectively:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
rl.addView(iv, params);
Places one 30x40 yellow ImageView at (50,60) and another 30x40 red ImageView <80,90> relative to the yellow ImageView:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int yellow_iv_id = 123; // Some arbitrary ID value.
iv = new ImageView(this);
iv.setId(yellow_iv_id);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
// This line defines how params.leftMargin and params.topMargin are interpreted.
// In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);
rl.addView(iv, params);
I've tried many times.
And at last I just put autoindex on;
in http
but outside of server
, and it's OK.
Three alternative solutions:
1) With data.table:
You can use the same melt
function as in the reshape2
package (which is an extended & improved implementation). melt
from data.table
has also more parameters that the melt
-function from reshape2
. You can for example also specify the name of the variable-column:
library(data.table)
long <- melt(setDT(wide), id.vars = c("Code","Country"), variable.name = "year")
which gives:
> long Code Country year value 1: AFG Afghanistan 1950 20,249 2: ALB Albania 1950 8,097 3: AFG Afghanistan 1951 21,352 4: ALB Albania 1951 8,986 5: AFG Afghanistan 1952 22,532 6: ALB Albania 1952 10,058 7: AFG Afghanistan 1953 23,557 8: ALB Albania 1953 11,123 9: AFG Afghanistan 1954 24,555 10: ALB Albania 1954 12,246
Some alternative notations:
melt(setDT(wide), id.vars = 1:2, variable.name = "year")
melt(setDT(wide), measure.vars = 3:7, variable.name = "year")
melt(setDT(wide), measure.vars = as.character(1950:1954), variable.name = "year")
2) With tidyr:
library(tidyr)
long <- wide %>% gather(year, value, -c(Code, Country))
Some alternative notations:
wide %>% gather(year, value, -Code, -Country)
wide %>% gather(year, value, -1:-2)
wide %>% gather(year, value, -(1:2))
wide %>% gather(year, value, -1, -2)
wide %>% gather(year, value, 3:7)
wide %>% gather(year, value, `1950`:`1954`)
3) With reshape2:
library(reshape2)
long <- melt(wide, id.vars = c("Code", "Country"))
Some alternative notations that give the same result:
# you can also define the id-variables by column number
melt(wide, id.vars = 1:2)
# as an alternative you can also specify the measure-variables
# all other variables will then be used as id-variables
melt(wide, measure.vars = 3:7)
melt(wide, measure.vars = as.character(1950:1954))
NOTES:
NA
values, you can add na.rm = TRUE
to the melt
as well as the gather
functions.Another problem with the data is that the values will be read by R as character-values (as a result of the ,
in the numbers). You can repair that with gsub
and as.numeric
:
long$value <- as.numeric(gsub(",", "", long$value))
Or directly with data.table
or dplyr
:
# data.table
long <- melt(setDT(wide),
id.vars = c("Code","Country"),
variable.name = "year")[, value := as.numeric(gsub(",", "", value))]
# tidyr and dplyr
long <- wide %>% gather(year, value, -c(Code,Country)) %>%
mutate(value = as.numeric(gsub(",", "", value)))
Data:
wide <- read.table(text="Code Country 1950 1951 1952 1953 1954
AFG Afghanistan 20,249 21,352 22,532 23,557 24,555
ALB Albania 8,097 8,986 10,058 11,123 12,246", header=TRUE, check.names=FALSE)
You need to mount a remote share on your windows machine. This is what Samba/smb is for.
What you'll be doing is turning your Linux box into an SMB server, which lets it share files in a way that plays nice with Windows.
If you're not on the same network, you'll need to tunnel this through your SSH connection which may not be worth the effort.
There is difference between both $(this).closest('div')
and $(this).parents('div').eq(0)
Basically closest
start matching element from the current element whereas parents
start matching elements from parent (one level above the current element)
See http://jsfiddle.net/imrankabir/c1jhocre/1/
When you write a lambda expression, the argument list to the left of ->
can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
is incorrect syntax; but
this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
is correct. Or:
this.stops.stream().filter(s -> s.getStation().getName().equals(name));
is also correct if the compiler has enough information to figure out the types.
Make sure you are connecting with a USB and not a lightning cable. I had this problem trying to connect using a cord with lightning cables on both ends and it would not list the device. But switching to a USB to lightning cable worked.
The first argument to printf()
is always a string value, known as a format control string. This string may be regular text, such as
printf("Hello, World\n"); // \n indicates a newline character
or
char greeting[] = "Hello, World\n";
printf(greeting);
This string may also contain one or more conversion specifiers; these conversion specifiers indicate that additional arguments have been passed to printf()
, and they specify how to format those arguments for output. For example, I can change the above to
char greeting[] = "Hello, World";
printf("%s\n", greeting);
The "%s" conversion specifier expects a pointer to a 0-terminated string, and formats it as text.
For signed decimal integer output, use either the "%d" or "%i" conversion specifiers, such as
printf("%d\n", addNumber(a,b));
You can mix regular text with conversion specifiers, like so:
printf("The result of addNumber(%d, %d) is %d\n", a, b, addNumber(a,b));
Note that the conversion specifiers in the control string indicate the number and types of additional parameters. If the number or types of additional arguments passed to printf()
don't match the conversion specifiers in the format string then the behavior is undefined. For example:
printf("The result of addNumber(%d, %d) is %d\n", addNumber(a,b));
will result in anything from garbled output to an outright crash.
There are a number of additional flags for conversion specifiers that control field width, precision, padding, justification, and types. Check your handy C reference manual for a complete listing.
Postman currently does not support that.
You may use this online tester by Websocket.in: https://www.websocket.in/test-online
To force a reload of the php.ini you should restart apache.
Try sudo service apache2 restart
from the command line.
Or sudo /etc/init.d/apache2 restart
You could try and add an @Controller
annotation on top of your myController Class and
try the following url /<webappname>/my/hello.html
.
This is because org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping
prepends /my to each RequestMapping in the myController class.
I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):
mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"
mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"
POSIX 7 on echo
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html
-e
is not defined and backslashes are implementation defined:
If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.
unless you have an optional XSI extension.
So I recommend that you should use printf
instead, which is well specified:
format operand shall be used as the format string described in XBD File Format Notation [...]
the File Format Notation:
\n <newline> Move the printing position to the start of the next line.
Also keep in mind that Ubuntu 15.10 and most distros implement echo
both as:
help echo
which echo
which can lead to some confusion.
I know this is a late reply, but I've just wanted to address the issue of setting the zoom level myself. goldmine's answer is great but I found it not working sufficiently well in my application.
On closer inspection goldmine states that "longitude lines are spaced apart equally at any point of the map". This is not true, it is in fact latitude lines that are spaced equally from -90 (south pole) to +90 (north pole). Longitude lines are spaced at their widest at the equator, converging to a point at the poles.
The implementation I have adopted is therefore to use the latitude calculation as follows:
@implementation MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate
zoomLevel:(NSUInteger)zoom animated:(BOOL)animated
{
MKCoordinateSpan span = MKCoordinateSpanMake(180 / pow(2, zoom) *
self.frame.size.height / 256, 0);
[self setRegion:MKCoordinateRegionMake(coordinate, span) animated:animated];
}
@end
Hope it helps at this late stage.
df[df.Letters=='C'].Letters.item()
This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.
EDIT:
Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.
I personally always use
from package.subpackage.subsubpackage import module
and then access everything as
module.function
module.modulevar
etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.
Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)
Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like
from package1.subpackage import module
from package2.subpackage import module
in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.
Here are a couple of things to check:
For console.Write/WriteLine
, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine
).
You could use System.Diagnostics.Debug.WriteLine
to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline
if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline
)
random.random()
does exactly that
>>> import random
>>> for i in range(10):
... print(random.random())
...
0.908047338626
0.0199900075962
0.904058545833
0.321508119045
0.657086320195
0.714084413092
0.315924955063
0.696965958019
0.93824013683
0.484207425759
If you want really random numbers, and to cover the range [0, 1]:
>>> import os
>>> int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)
0.7409674234050893
The following code does the trick for me
SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
set.seed
is a base function that it is able to generate (every time you want) together other functions (rnorm
, runif
, sample
) the same random value.
Below an example without set.seed
> set.seed(NULL)
> rnorm(5)
[1] 1.5982677 -2.2572974 2.3057461 0.5935456 0.1143519
> rnorm(5)
[1] 0.15135371 0.20266228 0.95084266 0.09319339 -1.11049182
> set.seed(NULL)
> runif(5)
[1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
> runif(5)
[1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
> set.seed(NULL)
> sample(5)
[1] 5 4 3 1 2
> sample(5)
[1] 2 1 5 4 3
Below an example with set.seed
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
Your for
loop has no loop body:
elif option == 2:
print "please enter a number"
for x in range(x, 1, 1):
elif option == 0:
Actually, the whole if option == 1:
block has indentation problems. elif option == 2:
should be at the same level as the if
statement.
Remove the width:100%;
declarations.
Block elements should take up the whole available width by default.
target_compile_options
solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
in Kotlin I wrote these extensions:
fun MenuItem.setTitleColor(color: Int) {
val hexColor = Integer.toHexString(color).toUpperCase().substring(2)
val html = "<font color='#$hexColor'>$title</font>"
this.title = html.parseAsHtml()
}
@Suppress("DEPRECATION")
fun String.parseAsHtml(): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this)
}
}
and used like this:
menu.findItem(R.id.main_settings).setTitleColor(Color.RED)
I found that if I run CMD as Administrator and run the command, I can install it without a problem. Try it and give me some feedback.
You cannot effectively hide your HTML and JavaScript code, even if you encrypt or minify it.
If the code you're trying to hide is really sensitive, it should either be in a protected area of the site, i.e. an area that you can only access via a username and password, or potentially in a client application that isn't exposed via the web.
If you have to expose the application functionality via a web frontend, you could use Silverlight to write the frontend or bits of the frontend. In the old days you could also use ActiveX.
Have you tried plt.tight_layout()
?
with plt.tight_layout()
without it:
Or: something like this (use add_axes
)
left=[0.1,0.3,0.5,0.7]
width=[0.2,0.2, 0.2, 0.2]
rectLS=[]
for x in left:
for y in left:
rectLS.append([x, y, 0.2, 0.2])
axLS=[]
fig=plt.figure()
axLS.append(fig.add_axes(rectLS[0]))
for i in [1,2,3]:
axLS.append(fig.add_axes(rectLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[4]))
for i in [1,2,3]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[8]))
for i in [5,6,7]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[12]))
for i in [9,10,11]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
If you don't need to share axes, then simply axLS=map(fig.add_axes, rectLS)
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
_x000D_
It didn't work, because QuerySets are not JSON serializable.
1) In case of json.dumps
you have to explicitely convert your QuerySet to JSON serializable objects:
class Model(model.Model):
def as_dict(self):
return {
"id": self.id,
# other stuff
}
And the serialization:
dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')
2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:
serializers.serialize("json", self.get_queryset())
Read more about it here:
I have an Angular4 application, even for me also it was not working in IE11 browser, i have done below changes, now its working correctly. Just add below code in the index.html file
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Just you need to uncomment these below lines from polyfills.ts file
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
These above 2 steps will solve your problem, please let me know if anything will be there. Thanks!!!
If you are trying to send mail from your local enviroment eg. XAMPP or WAMP, this error will occur everytime, go ahead and try the same code on your web hosting or whatever you are using for production.
Also, 2 step authentication from google may be the issue.
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
MinGW would be a direct translation off gcc for windows, or you might want to check out LCC, vanilla c (more or less) with an IDE. Pelles C seems to be based off lcc and has a somewhat nicer IDE, though I haven't used it personally. Of course there is always the Express Edition of MSVC which is free, but that's your call.
On 12 March 2020, a draft has been added by WICG for Text Fragments, and now you can link to text on a page as if you were searching for it by adding the following to the hash
#:~:text=<Text To Link to>
Working example on Chrome Version 81.0.4044.138
:
Click on this link Should reload the page and highlight the link's text
If you use a "text variable" tk.StringVar()
, you can just set()
that.
No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.
import Tkinter as tk
...
entryText = tk.StringVar()
entry = tk.Entry( master, textvariable=entryText )
entryText.set( "Hello World" )
Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:
and finally, implode() to join the array elements into your truncated string..
function truncateString($string, $start, $limit){
$stripped_string =strip_tags($string); // if there are HTML or PHP tags
$string_array =explode(' ',$stripped_string);
$truncated_array = array_splice($string_array,$start,$limit);
$truncated_string=implode(' ',$truncated_array);
return $truncated_string;
}
It's that simple..
I hope this was helpful.
Entering: /usr/bin/gcc worked for me.
use MAX
in your SELECT
to return on value.. EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will more than one value
I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:
"undefined is not a function"
I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.
@MvcHtmlString.Create(
@SquishIt.Framework.Bundle.JavaScript()
.Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
.Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
.Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
.Add("~/Scripts/Libraries/jquery.validate.js")
.Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
... more files
I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.
From "The Java™ Tutorials" on synchronized methods:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
From "The Java™ Tutorials" on synchronized blocks:
Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.
(Emphasis mine)
Suppose you have 2 non-interleaving variables. So you want to access to each one from a different threads at the same time. You need to define the lock not on the object class itself, but on the class Object like below (example from the second Oracle link):
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
Im my case the problem was that I cretead sertificates without entering any data in cli interface. When I regenerated cretificates and enetered all fields: City, State, etc all became fine.
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt
If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.
Using cssnext will turn this:
input:not([type="radio"], [type="checkbox"]) {
/* css here */
}
Into this:
input:not([type="radio"]):not([type="checkbox"]) {
/* css here */
}
You can also use showdialog
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
dim mydialogbox as new aboutbox1
aboutbox1.showdialog()
End Sub
It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:
suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.
var x = [1,2,3];
var y = [1,1,1];
chart.data.datasets[0].data = y;
chart.data.labels = x;
chart.update();
Make a batch file and call the bacth file in Window.open. Here how it works
in html
window.open('file://dotnet/sc/test.bat')
Enjoy..
Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.
Web-servers such as lighthttpd must be configured manually to set the mime type correctly.
Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.
On POSIX based systems you can base64 encode a file with the base64
command.
To create a base64 encoded ico line use the command:
$ base64 favicon.ico --wrap 0
And insert the output into the line:
<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />
Replacing the word HERE
like so:
<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA////AERpOgA5cCcA7vDtAF6jSABllFcAuuCvAK2trQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFjMzMzMzNxARYzMzMzVBEEERYzMzNhERZxRGMzZxQEA2FER3cRSAgTNxgEEREIQBMzFIARERFEEzNhERARFAATMzYREBEAhBMzMzEYEBFEEzMzNhEQQRQDMzMzcRgEAAMzMzNhERgIEzMzMyERgEQDMzMzMRAEgEMzMzMxERAEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon" />
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27
If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in
>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
... shutil.copyfileobj(f, sys.stdout)
also works.
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
Although :pastetoggle
or :paste
and :nopaste
should be working fine (if implemented - they are not always as we can see from the discussion) I highly recomment pasting using the direct approach "+p
or "*p
and reading with "+r
or "*r
:
Vim has acess to ten types of registers (:help registers
) and the questioner is interested in quotestar
and quoteplus
from section
- Selection and drop registers
"*
,"+
and "~Use these registers for storing and retrieving the selected text for the GUI. See
quotestar
andquoteplus
. When the clipboard is not available or not working, the unnamed register is used instead. For Unix systems the clipboard is only available when the +xterm_clipboard feature is present. {not in Vi}Note that there is only a distinction between "* and "+ for X11 systems.
:help x11-selection
further clarifies the difference of *
and +
:
quoteplus quote+
There are three documented X selections: PRIMARY (which is expected to represent the current visual selection - as in Vim's Visual mode), SECONDARY (which is ill-defined) and CLIPBOARD (which is expected to be used for cut, copy and paste operations).
Of these three, Vim uses PRIMARY when reading and writing the "* register (hence when the X11 selections are available, Vim sets a default value for 'clipboard' of "autoselect"), and CLIPBOARD when reading and writing the "+ register. Vim does not access the SECONDARY selection.
Examples: (assuming the default option values)
Select an URL in Visual mode in Vim. Go to your browser and click the middle mouse button in the URL text field. The selected text will be inserted (hopefully!). Note: in Firefox you can set the middlemouse.contentLoadURL preference to true in about:config, then the selected URL will be used when pressing middle mouse button in most places in the window.
Select some text in your browser by dragging with the mouse. Go to Vim and press the middle mouse button: The selected text is inserted.
- Select some text in Vim and do "+y. Go to your browser, select some text in a textfield by dragging with the mouse. Now use the right mouse button and select "Paste" from the popup menu. The selected text is overwritten by the text from Vim. Note that the text in the "+ register remains available when making a Visual selection, which makes other text available in the "* register. That allows overwriting selected text.
To calculate the sum of a column in a DataTable use the DataTable.Compute method.
Example of usage from the linked MSDN article:
DataTable table = dataSet.Tables["YourTableName"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);
Display the result in your Total Amount Label like so:
lblTotalAmount.Text = sumObject.ToString();
Open git view :
1- select your project and choose merge 2- Select remote tracking 3- click ok
Git will merge the remote branch with local repository
4- then push
maybe this is what u want?
<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>
edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....
The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:
@echo off
setlocal enabledelayedexpansion enableextensions
set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:eof
endlocal
Now the :file_name_from_path
function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.
Problem was to select columns of on dataframe after joining with other dataframe.
I tried below and select the columns of salaryDf from the joined dataframe.
Hope this will help
val empDf=spark.read.option("header","true").csv("/data/tech.txt")
val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")
val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and empDf.col("last") === salaryDf.col("last"))
//**below will select the colums of salaryDf only**
val finalDF=joinData.select(salaryDf.columns map salaryDf.col:_*)
//same way we can select the columns of empDf
joinData.select(empDf.columns map empDf.col:_*)
.NET 2.0 does not use lambda expressions. You need to compile to .NET 3.0 to use them.
This is one of the most annoying things about Maven. For me the following happens: If I add a dependency requesting more dependencies and more and more but have a slow connection, it seams to stop while downloading and timing out. While timing out all dependencies not yet fetched are marked with place holders in the .m2 cache and Maven will not (never) pick it up unless I remove the place holder entry from the cache (as other stated) by removing it.
So as far as I see it, Maven or more precise the Eclipse Maven plugin has a bug regarding this. Someone should report this.
if you found an issue when you try to import xgboost (my case it is Windows 10 and anaconda spyder) do the following:
conda install -c anaconda py-xgboost
That's all...Good luck.
On PostgreSQL you can use:
SELECT * FROM table_name WHERE (boolean_column IS NULL OR NOT boolean_column)
That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.
You can use the RedirectView
. Copied from the JavaDoc:
View that redirects to an absolute, context relative, or current request relative URL
Example:
@RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.yahoo.com");
return redirectView;
}
You can also use a ResponseEntity
, e.g.
@RequestMapping("/to-be-redirected")
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
URI yahoo = new URI("http://www.yahoo.com");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(yahoo);
return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}
And of course, return redirect:http://www.yahoo.com
as mentioned by others.
Here is an implementation of Michael's solution for any type of element in std::vector.
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
// Find all subsets
template<typename element>
vector< vector<element> > subsets(const vector<element>& set)
{
// Output
vector< vector<element> > ss;
// If empty set, return set containing empty set
if (set.empty()) {
ss.push_back(set);
return ss;
}
// If only one element, return itself and empty set
if (set.size() == 1) {
vector<element> empty;
ss.push_back(empty);
ss.push_back(set);
return ss;
}
// Otherwise, get all but last element
vector<element> allbutlast;
for (unsigned int i=0;i<(set.size()-1);i++) {
allbutlast.push_back( set[i] );
}
// Get subsets of set formed by excluding the last element of the input set
vector< vector<element> > ssallbutlast = subsets(allbutlast);
// First add these sets to the output
for (unsigned int i=0;i<ssallbutlast.size();i++) {
ss.push_back(ssallbutlast[i]);
}
// Now add to each set in ssallbutlast the last element of the input
for (unsigned int i=0;i<ssallbutlast.size();i++) {
ssallbutlast[i].push_back( set[set.size()-1] );
}
// Add these new sets to the output
for (unsigned int i=0;i<ssallbutlast.size();i++) {
ss.push_back(ssallbutlast[i]);
}
return ss;
}
// Test
int main()
{
vector<char> a;
a.push_back('a');
a.push_back('b');
a.push_back('c');
vector< vector<char> > sa = subsets(a);
for (unsigned int i=0;i<sa.size();i++) {
for (unsigned int j=0;j<sa[i].size();j++) {
cout << sa[i][j];
}
cout << endl;
}
return 0;
}
Output:
(empty line)
a
b
ab
c
ac
bc
abc
The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:
IN | OUT | TOT | LEAF | INT
1 | 1 | 1 | 1 | 0
2 | 1 | 1 | 1 | 0
3 | 2 | 3 | 2 | 1
4 | 3 | 5 | 3 | 2
5 | 5 | 9 | 5 | 4
6 | 8 | 15 | 8 | 7
7 | 13 | 25 | 13 | 12
8 | 21 | 41 | 21 | 20
9 | 34 | 67 | 34 | 33
10 | 55 | 109 | 55 | 54
What immediately leaps out is that the number of leaf nodes is fib(n)
. What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1
. Therefore the total number of nodes is 2 * fib(n) - 1
.
Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n))
.
The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?
link_to
can also produce links with anchors or query strings:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
You can simply use loop of enumeration to get your desired result:
Swift 2:
for (index, element) in elements.enumerate() {
print("\(index): \(element)")
}
Swift 3 & 4:
for (index, element) in elements.enumerated() {
print("\(index): \(element)")
}
Or you can simply go through a for loop to get the same result:
for index in 0..<elements.count {
let element = elements[index]
print("\(index): \(element)")
}
Hope it helps.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
>>> numpy.array([[1, 2], [3, 4]])
array([[1, 2], [3, 4]])
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
In VS 2019, this works with ease:
[Route("api/[controller]/[action]")] //above the controller class
And in the code:
[HttpGet]
[ActionName("GetSample1")]
public Ilist<Sample1> GetSample1()
{
return getSample1();
}
[HttpGet]
[ActionName("GetSample2")]
public Ilist<Sample2> GetSample2()
{
return getSample2();
}
[HttpGet]
[ActionName("GetSample3")]
public Ilist<Sample3> GetSample3()
{
return getSample3();
}
[HttpGet]
[ActionName("GetSample4")]
public Ilist<Sample4> GetSample4()
{
return getSample4();
}
You can have multiple gets like above mentioned.
If you are going to use a listener you will need to add this permission to the manifest as well.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
This was the only thing that worked for me on Armbian:
dmesg | grep -oE 'mac=.*\w+' | cut -b '5-'
When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
One case you check that nginx hold on 80 number port in system by default , check if you have any server like as apache or anything exist on system that block 80 number port thats the problem occurred.
1 .You change port number on nginx by this way,
sudo vim /etc/nginx/sites-available/default
Change 80 to 81 or anything,
sudo nginx -t
sudo service nginx start
sudo service nginx status
Hope that will work
I used ASIHTTPRequest a lot like Jane Sales answer but it is not under development anymore and the author suggests using other libraries like AFNetworking.
Honestly, I think now is the time to start looking elsewhere.
AFNetworking works great, and let you work with blocks a lot (which is a great relief).
Here's an image upload example from their documentation page on github:
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
Here is a super simple way of doing it
row2dict = lambda r: dict(r.items())
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
Pass Data using NSNotificationCenter
You can also pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0.
Swift 2.0 Version
Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)
// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)
// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.0 Version
The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Source pass data using NotificationCentre(swift 3.0) and NSNotificationCenter(swift 2.0)
Intent i = new Intent("com.Android.SubActivity");
startActivity(i);
you might consider using the Relative and Absolute positining.
`.container {
position: relative;
}
.tag {
position: absolute;
}`
I have tested it there, also if you want it to change its position use this as its margin:
top: 20px;
left: 10px;
It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.
First, use git log
to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash
. After you are done, git checkout original_branch
. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.
You can also use the Cookies API and do:
browser.cookies.set({
url: 'example.com',
name: 'HelloWorld',
value: 'HelloWorld',
expirationDate: myDate
}
Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage.
I found a very simple solution that seems to be working :
s3 = boto3.client("s3")
s3.put_object(
Body=open("filename.csv").read(),
Bucket="your-bucket",
Key="your-key"
)
Hope that helps !
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
You have to enter input in either single or double quotes
Ex:'dude' -> correct
dude -> not correct
Like others said, I added this class in my project and set the filter to the EditText Simpler solution without using regex:
public class DecimalDigitsInputFilter implements InputFilter {
int digitsBeforeZero =0;
int digitsAfterZero=0;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
this.digitsBeforeZero=digitsBeforeZero;
this.digitsAfterZero=digitsAfterZero;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if(dest!=null && dest.toString().trim().length()<(digitsBeforeZero+digitsAfterZero)){
String value=dest.toString().trim();
if(value.contains(".") && (value.substring(value.indexOf(".")).length()<(digitsAfterZero+1))){
return ((value.indexOf(".")+1+digitsAfterZero)>dstart)?null:"";
}else if(value.contains(".") && (value.indexOf(".")<dstart)){
return "";
}else if(source!=null && source.equals(".")&& ((value.length()-dstart)>=(digitsAfterZero+1))){
return "";
}
}else{
return "";
}
return null;
}
}
applying filter:
edittext.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
First of all consider using query parameters in prepared statements:
PreparedStatement stm = c.prepareStatement("UPDATE user_table SET name=? WHERE id=?");
stm.setString(1, "the name");
stm.setInt(2, 345);
stm.executeUpdate();
The other thing that can be done is to keep all queries in properties file. For example in a queries.properties file can place the above query:
update_query=UPDATE user_table SET name=? WHERE id=?
Then with the help of a simple utility class:
public class Queries {
private static final String propFileName = "queries.properties";
private static Properties props;
public static Properties getQueries() throws SQLException {
InputStream is =
Queries.class.getResourceAsStream("/" + propFileName);
if (is == null){
throw new SQLException("Unable to load property file: " + propFileName);
}
//singleton
if(props == null){
props = new Properties();
try {
props.load(is);
} catch (IOException e) {
throw new SQLException("Unable to load property file: " + propFileName + "\n" + e.getMessage());
}
}
return props;
}
public static String getQuery(String query) throws SQLException{
return getQueries().getProperty(query);
}
}
you might use your queries as follows:
PreparedStatement stm = c.prepareStatement(Queries.getQuery("update_query"));
This is a rather simple solution, but works well.
Because int is a ValueType then you can use the following code:
if(Age == default(int) || Age == null)
or
if(Age.HasValue && Age != 0) or if (!Age.HasValue || Age == 0)
This code
int a = 5;
printf("%x\n", a);
prints
5
This code
int a = 5;
printf("0x%x\n", a);
prints
0x5
This code
int a = 89778116;
printf("%x\n", a);
prints
559e7c4
If you capitalize the x in the format it capitalizes the hex value:
int a = 89778116;
printf("%X\n", a);
prints
559E7C4
If you want to print pointers you use the p format specifier:
char* str = "foo";
printf("0x%p\n", str);
prints
0x01275744
Check that the socket file exists.
$ ls -l /tmp/.s.PGSQL.5432
srwxrwxrwx 1 you wheel 0 Nov 16 09:22 /tmp/.s.PGSQL.5432
If it doesn't then check your postgresql.conf for unix_socket_directory change.
$ grep unix_socket /usr/local/var/postgres/postgresql.conf
#unix_socket_directory = '' # (change requires restart)
#unix_socket_group = '' # (change requires restart)
#unix_socket_permissions = 0777 # begin with 0 to use octal notation
The answer differs depending on what OS is being considered. In general though:
For TCP, no. You can only have one application listening on the same port at one time. Now if you had 2 network cards, you could have one application listen on the first IP and the second one on the second IP using the same port number.
For UDP (Multicasts), multiple applications can subscribe to the same port.
Edit: Since Linux Kernel 3.9 and later, support for multiple applications listening to the same port was added using the SO_REUSEPORT
option. More information is available at this lwn.net article.
If you want "insert or replace" semantics, use this syntax:
A[key] = value; // <-- insert or replace semantics
It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".
So in your case:
rct3Features[items[0]] = items[1];
I use this as post-build event in Visual Studio:
call "%VS90COMNTOOLS%vsvars32.bat"
regasm $(TargetPath) /tlb
Depending on your Visual Studio version, use these environment variables instead:
VS90COMNTOOLS
VS100COMNTOOLS
VS110COMNTOOLS
VS120COMNTOOLS
VS140COMNTOOLS
VS150COMNTOOLS
I just came across a similar problem. Try
require './st.rb'
This should do the trick.
Simply can be used:
SELECT RIGHT('0' + CAST(MONTH(@Date) AS NVARCHAR(2)), 2)
How I was doing it until now:
php artisan make:model Customer
php artisan make:controller CustomersController --resource
Apparently, there’s a quicker way:
php artisan make:controller CustomersController --model=Customer
Either run basicConfig
with stream=sys.stdout
as the argument prior to setting up any other handlers or logging any messages, or manually add a StreamHandler
that pushes messages to stdout to the root logger (or any other logger you want, for that matter).
For right labels use ax.yaxis.set_label_position("right")
, i.e.:
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()
You can try this:
CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'
This page contains all the cached urls
chrome://cache
Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html
You can execute all the commands returned by the following query :
select 'ALTER TABLE '||substr(c.table_name,1,35)|| ' DISABLE CONSTRAINT '||constraint_name||' ;' from user_constraints c --where c.table_name = 'TABLE_NAME' ;
The hexadecimal value you are looking for is %2B
To get it automatically in PHP run your string through urlencode($stringVal)
. And then run it rhough urldecode($stringVal)
to get it back.
If you want the JavaScript to handle it, use escape( str )
Edit
After @bobince's comment I did more reading and he is correct.
Use encodeURIComponent(str)
and decodeURIComponent(str)
. Escape will not convert the characters, only escape them with \
's
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
Usage:
'{0}-{1}'.format('a','b');
// Result: 'a-b'
select template; iframe controller, ng model update
index.html
angularapp.controller('FieldCtrl', function ($scope, $sce) {
var iframeclass = '';
$scope.loadTemplate = function() {
if ($scope.template.length > 0) {
// add iframe classs
iframeclass = $scope.template.split('.')[0];
iframe.classList.add(iframeclass);
$scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
} else {
iframe.classList.remove(iframeclass);
};
};
});
// custom directive
angularapp.directive('myChange', function() {
return function(scope, element) {
element.bind('input', function() {
// the iframe function
iframe.contentWindow.update({
name: element[0].name,
value: element[0].value
});
});
};
});
iframe.html
window.update = function(data) {
$scope.$apply(function() {
$scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
});
};
Check this link: http://plnkr.co/edit/TGRj2o?p=preview
Here's a good description:
Relationships between two entities may be classified as being either "identifying" or "non-identifying". Identifying relationships exist when the primary key of the parent entity is included in the primary key of the child entity. On the other hand, a non-identifying relationship exists when the primary key of the parent entity is included in the child entity but not as part of the child entity's primary key. In addition, non-identifying relationships may be further classified as being either "mandatory" or "non-mandatory". A mandatory non-identifying relationship exists when the value in the child table cannot be null. On the other hand, a non-mandatory non-identifying relationship exists when the value in the child table can be null.
http://www.sqlteam.com/article/database-design-and-modeling-fundamentals
Here's a simple example of an identifying relationship:
Parent
------
ID (PK)
Name
Child
-----
ID (PK)
ParentID (PK, FK to Parent.ID) -- notice PK
Name
Here's a corresponding non-identifying relationship:
Parent
------
ID (PK)
Name
Child
-----
ID (PK)
ParentID (FK to Parent.ID) -- notice no PK
Name
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
Firstly: The >>>
code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:
>>> 4+5
9
Here we see that the line that starts with >>>
is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.
You never enter the >>>
part into a .py
file.
That takes care of your syntax error.
Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.
They all have benefits and drawbacks.
SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.
Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.
ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.
I'd do
for i in `seq 0 2 10`; do echo $i; done
(though of course seq 0 2 10
will produce the same output on its own).
Note that seq
allows floating-point numbers (e.g., seq .5 .25 3.5
) but bash's brace expansion only allows integers.
If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src
attribute.
$("#myiframe").attr("src", "newwebpage.html");
You need to add following attribute to the link or button where you want add this functionality:
data-dismiss="modal" data-toggle="modal" id="forgotPassword" data-target="#ModalForgotPassword"
A detaile blog: http://sforsuresh.in/bootstrap-modal-window-close-current-open-new-modal/
While trying to solve this for myself, I noticed that it's actually possible to retain the scrolling of the page and focus of the input while disabling number changes by attempting to re-fire the caught event on the parent element of the <input type="number"/>
on which it was caught, simply like this:
e.target.parentElement.dispatchEvent(e);
However, this causes an error in browser console, and is probably not guaranteed to work everywhere (I only tested on Firefox), since it is intentionally invalid code.
Another solution which works nicely at least on Firefox and Chromium is to temporarily make the <input>
element readOnly
, like this:
function handleScroll(e) {
if (e.target.tagName.toLowerCase() === 'input'
&& (e.target.type === 'number')
&& (e.target === document.activeElement)
&& !e.target.readOnly
) {
e.target.readOnly = true;
setTimeout(function(el){ el.readOnly = false; }, 0, e.target);
}
}
document.addEventListener('wheel', function(e){ handleScroll(e); });
One side effect that I've noticed is that it may cause the field to flicker for a split-second if you have different styling for readOnly
fields, but for my case at least, this doesn't seem to be an issue.
Similarly, (as explained in James' answer) instead of modifying the readOnly
property, you can blur()
the field and then focus()
it back, but again, depending on styles in use, some flickering might occur.
Alternatively, as mentioned in other comments here, you can just call preventDefault()
on the event instead. Assuming that you only handle wheel
events on number inputs which are in focus and under the mouse cursor (that's what the three conditions above signify), negative impact on user experience would be close to none.
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private
- Only the current class will have access to the field or method.
protected
- Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public
- Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
You can't have two elements with the same ID.
Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.
Instead, try something like this:
<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>
CSS:
.link {
width: 50%;
float: left;
text-align: center;
}
Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase
, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:
void swapCase(char *name);
or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
Here you go:
DECLARE
BEGIN
dbms_output.enable(NULL); -- Disables the limit of DBMS
-- Your print here !
END;
If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.
This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name
($key) and value
($field) for each field, as iterate over the fields of a row.
Wrapped in <table>
so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
Here's an assertion I wrote in a server for a Hibernate/SQL project. An entity bean had two effectively-boolean properties, called isActive and isDefault. Each could have a value of "Y" or "N" or null, which was treated as "N". We want to make sure the browser client is limited to these three values. So, in my setters for these two properties, I added this assertion:
assert new HashSet<String>(Arrays.asList("Y", "N", null)).contains(value) : value;
Notice the following.
This assertion is for the development phase only. If the client sends a bad value, we will catch that early and fix it, long before we reach production. Assertions are for defects that you can catch early.
This assertion is slow and inefficient. That's okay. Assertions are free to be slow. We don't care because they're development-only tools. This won't slow down the production code because assertions will be disabled. (There's some disagreement on this point, which I'll get to later.) This leads to my next point.
This assertion has no side effects. I could have tested my value against an unmodifiable static final Set, but that set would have stayed around in production, where it would never get used.
This assertion exists to verify the proper operation of the client. So by the time we reach production, we will be sure that the client is operating properly, so we can safely turn the assertion off.
Some people ask this: If the assertion isn't needed in production, why not just take them out when you're done? Because you'll still need them when you start working on the next version.
Some people have argued that you should never use assertions, because you can never be sure that all the bugs are gone, so you need to keep them around even in production. And so there's no point in using the assert statement, since the only advantage to asserts is that you can turn them off. Hence, according to this thinking, you should (almost) never use asserts. I disagree. It's certainly true that if a test belongs in production, you should not use an assert. But this test does not belong in production. This one is for catching a bug that's not likely to ever reach production, so it may safely be turned off when you're done.
BTW, I could have written it like this:
assert value == null || value.equals("Y") || value.equals("N") : value;
This is fine for only three values, but if the number of possible values gets bigger, the HashSet version becomes more convenient. I chose the HashSet version to make my point about efficiency.
In Swift 4, you can take care of this issue using:
let navStyles = UINavigationBar.appearance()
// This will set the color of the text for the back buttons.
navStyles.tintColor = .white
// This will set the background color for navBar
navStyles.barTintColor = .black
The Mozilla Developer Network provides the following explanation:
event = document.createEvent("KeyboardEvent")
using:
event.initKeyEvent (type, bubbles, cancelable, viewArg,
ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
keyCodeArg, charCodeArg)
yourElement.dispatchEvent(event)
I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...
I assume you're asking about combinations in combinatorial sense (that is, order of elements doesn't matter, so [1 2 3]
is the same as [2 1 3]
). The idea is pretty simple then, if you understand induction / recursion: to get all K
-element combinations, you first pick initial element of a combination out of existing set of people, and then you "concatenate" this initial element with all possible combinations of K-1
people produced from elements that succeed the initial element.
As an example, let's say we want to take all combinations of 3 people from a set of 5 people. Then all possible combinations of 3 people can be expressed in terms of all possible combinations of 2 people:
comb({ 1 2 3 4 5 }, 3) =
{ 1, comb({ 2 3 4 5 }, 2) } and
{ 2, comb({ 3 4 5 }, 2) } and
{ 3, comb({ 4 5 }, 2) }
Here's C++ code that implements this idea:
#include <iostream>
#include <vector>
using namespace std;
vector<int> people;
vector<int> combination;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void go(int offset, int k) {
if (k == 0) {
pretty_print(combination);
return;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1);
combination.pop_back();
}
}
int main() {
int n = 5, k = 3;
for (int i = 0; i < n; ++i) { people.push_back(i+1); }
go(0, k);
return 0;
}
And here's output for N = 5, K = 3
:
combination no 1: [ 1 2 3 ]
combination no 2: [ 1 2 4 ]
combination no 3: [ 1 2 5 ]
combination no 4: [ 1 3 4 ]
combination no 5: [ 1 3 5 ]
combination no 6: [ 1 4 5 ]
combination no 7: [ 2 3 4 ]
combination no 8: [ 2 3 5 ]
combination no 9: [ 2 4 5 ]
combination no 10: [ 3 4 5 ]
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array
onto the end of your current array
. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
@Martin Devillers solution works fine. For completeness, providing the steps below:
src/main/resource
In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.
<wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
<wsdlLocation>/mydir/my.wsdl</wsdlLocation>
Then in your java code(with no-arg constructor):
MyPort myPort = new MyPortService().getMyPort();
Here is the full code generation part in pom file, with fluent api in generated code.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>wsdl-to-java-generator</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<keep>true</keep>
<wsdlDirectory>src/main/resources/package</wsdlDirectory>
<wsdlLocation>/package/my.wsdl</wsdlLocation>
<sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
<packageName>full.package.here</packageName>
</configuration>
</execution>
</executions>
Try marginTop
in place of margin-top
, eg:
$("#ActionBox").css("marginTop", foo);
Here is your dataframe:
import pandas as pd
df = pd.DataFrame({
'A': ['a.1', 'a.2', 'a.3'],
'B': ['b.1', 'b.2', 'b.3'],
'C': ['c.1', 'c.2', 'c.3']})
Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.
It says:
A DataFrame can be enlarged on either axis via .loc.
So what you need to do is simply one of these two:
df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']
I was facing same problem below is the solution that worked for me
First Go to Android SDK Manager then
select Tools then,
select Options
then check the box "Force https://... sources to be fetched using http://..."
hope it will help you also.
None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:
using System;
using System.Collections.Generic;
namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
void fail()
{
(null as string).Trim();
}
void bareThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw;
}
}
void rethrow()
{
try
{
fail();
}
catch (Exception e)
{
throw e;
}
}
void innerThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw new Exception("outer", e);
}
}
var cases = new Dictionary<string, Action>()
{
{ "Bare Throw:", bareThrow },
{ "Rethrow", rethrow },
{ "Inner Throw", innerThrow }
};
foreach (var c in cases)
{
Console.WriteLine(c.Key);
Console.WriteLine(new string('-', 40));
try
{
c.Value();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
Which generates the following output:
Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
--- End of inner exception stack trace ---
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).
The output of the re-throw case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e
(line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.
The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).
Edit: As per the Mr Me comment on this answer, it looks like compression is now available for JPG/WebP formats ( see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL ).
As far as I know, you cannot compress images using canvas, instead, you can resize it. Using canvas.toDataURL will not let you choose the compression ratio to use. You can take a look at canimage that does exactly what you want : https://github.com/nfroidure/CanImage/blob/master/chrome/canimage/content/canimage.js
In fact, it's often sufficient to just resize the image to decrease it's size but if you want to go further, you'll have to use newly introduced method file.readAsArrayBuffer to get a buffer containing the image data.
Then, just use a DataView to read it's content according to the image format specification (http://en.wikipedia.org/wiki/JPEG or http://en.wikipedia.org/wiki/Portable_Network_Graphics).
It'll be hard to deal with image data compression, but it is worse a try. On the other hand, you can try to delete the PNG headers or the JPEG exif data to make your image smaller, it should be easier to do so.
You'll have to create another DataWiew on another buffer and fill it with the filtered image content. Then, you'll just have to encode you're image content to DataURI using window.btoa.
Let me know if you implement something similar, will be interesting to go through the code.
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
Take a look at autoexpect
(decent tutorial HERE). It's about as quick-and-dirty as you can get without resorting to trickery.
If you want to switch the whole tab to fullscreen (just like F11 keypress) document.documentElement
is the element you are looking for:
function go_full_screen(){
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
Add 'center-block' to image as class - no additional css needed
<img src="images/default.jpg" class="center-block img-responsive"/>
Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely
and up:
# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely
# Options
$option1 = New-ScheduledJobOption –StartIfIdle
$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"
Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
The CLI's webpack config can now be ejected. Check Anton Nikiforov's answer.
You can hack the config template in angular-cli/addon/ng2/models
. There's no official way to modify the webpack config as of now.
There's a closed "wont-fix" issue on github about this: https://github.com/angular/angular-cli/issues/1656
Just to make sure you are not confusing the tid (thread id) and the pid (process id):
DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);
Performance-wise bash outperforms python in the process startup time.
Here are some measurements from my core i7 laptop running Linux Mint:
Starting process Startup time
empty /bin/sh script 1.7 ms
empty /bin/bash script 2.8 ms
empty python script 11.1 ms
python script with a few libs* 110 ms
*Python loaded libs are: os, os.path, json, time, requests, threading, subprocess
This shows a huge difference however bash execution time degrades quickly if it has to do anything sensible since it usually must call external processes.
If you care about performance use bash only for:
Add "\"
before double quote to escape it, instead of \
#! /bin/csh -f
set dbtable = balabala
set dbload = "load data local infile "\""'gfpoint.csv'"\"" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"\""' LINES TERMINATED BY "\""'\n'"\"" IGNORE 1 LINES"
echo $dbload
# load data local infile "'gfpoint.csv'" into table balabala FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "''" IGNORE 1 LINES
i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database
database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
$table is the name of the table in which you want to store the data..
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code
I had the same problem. If you are checking out any github project, then instead of using git clone, use git lfs clone, as sometimes, some large files are not properly cloned by using git only. Also, make sure your bitcode is disabled.
Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.
STORED
generated columns are introduced with Postgres 12. Trivial example:
CREATE TABLE tbl (
int1 int
, int2 int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);
db<>fiddle here
VIRTUAL
generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .
Related:
Until then, you can emulate VIRTUAL
generated columns with a function using attribute notation (tbl.col
) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:
The expression (looking like a column) is not included in a SELECT * FROM tbl
, though. You always have to list it explicitly.
Can also be supported with a matching expression index - provided the function is IMMUTABLE
. Like:
CREATE FUNCTION col(tbl) ... AS ... -- your computed expression here
CREATE INDEX ON tbl(col(tbl));
Alternatively, you can implement similar functionality with a VIEW
, optionally coupled with expression indexes. Then SELECT *
can include the generated column.
"Persisted" (STORED
) computed columns can be implemented with triggers in a functionally identical way.
Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.
I was stuck with this approx a day i just rename filename "Filename" with capital letter and rename the controller class "Classname". and it solved the problem.
**class Myclass extends CI_Controller{}
save file: Myclass.php**
application/config/config.php
$config['base_url'] = '';
You can simply do a replace in your string like
Str.Replace(@"\\",@"\");
// Swift 2
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
let orientation: UIInterfaceOrientationMask =
[UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
return orientation
}
You have to use this code:
<android.support.v7.widget.AppCompatRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radiobutton1"
app:buttonTint="@color/black" />
Using app:buttonTint
instead of android:buttonTint
and also android.support.v7.widget.AppCompatRadioButton
instead of Radiobutton
!
1. Performance:
Assume your where clause is like this:
WHERE NAME='JON'
If the NAME column is of any type other than nvarchar or nchar, then you should not specify the N prefix. However, if the NAME column is of type nvarchar or nchar, then if you do not specify the N prefix, then 'JON' is treated as non-unicode. This means the data type of NAME column and string 'JON' are different and so SQL Server implicitly converts one operand’s type to the other. If the SQL Server converts the literal’s type to the column’s type then there is no issue, but if it does the other way then performance will get hurt because the column's index (if available) wont be used.
2. Character set:
If the column is of type nvarchar or nchar, then always use the prefix N while specifying the character string in the WHERE criteria/UPDATE/INSERT clause. If you do not do this and one of the characters in your string is unicode (like international characters - example - a) then it will fail or suffer data corruption.
Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent()
. Example:
list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());
If you want to remove the routes cache on your server, remove this file:
bootstrap/cache/routes.php
And if you want to update it just run php artisan route:cache
and upload the bootstrap/cache/routes.php
to your server.
Eclipse needs to see a main method in one of your project's source files in order to determine what kind of project it is so that it can offer the proper run options:
public static void main(String[] args)
Without that method signature (or with a malformed version of that method signature), the Run As menu item will not present any run options.
The combination of find
and ls
works well for
The solution:
find . -name "my-pattern" -print0 |
xargs -r -0 ls -1 -t |
head -1
Let's break it down:
With find
we can match all interesting files like this:
find . -name "my-pattern" ...
then using -print0
we can pass all filenames safely to the ls
like this:
find . -name "my-pattern" -print0 | xargs -r -0 ls -1 -t
additional find
search parameters and patterns can be added here
find . -name "my-pattern" ... -print0 | xargs -r -0 ls -1 -t
ls -t
will sort files by modification time (newest first) and print it one at a line. You can use -c
to sort by creation time. Note: this will break with filenames containing newlines.
Finally head -1
gets us the first file in the sorted list.
Note: xargs
use system limits to the size of the argument list. If this size exceeds, xargs
will call ls
multiple times. This will break the sorting and probably also the final output. Run
xargs --show-limits
to check the limits on you system.
Note 2: use find . -maxdepth 1 -name "my-pattern" -print0
if you don't want to search files through subfolders.
Note 3: As pointed out by @starfry - -r
argument for xargs
is preventing the call of ls -1 -t
, if no files were matched by the find
. Thank you for the suggesion.
Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:
class Super {
static whoami() {
return "Super";
}
lognameA() {
console.log(Super.whoami());
}
lognameB() {
console.log(this.constructor.whoami());
}
}
class Sub extends Super {
static whoami() {
return "Sub";
}
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub
Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor
instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.
This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self
.
If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.
As aditional information on @Quentin answer, and as he rightly says,
background
CSS property itself, is a shorthand for:
background-color
background-image
background-repeat
background-attachment
background-position
That's mean, you can group all styles in one, like:
background: red url(../img.jpg) 0 0 no-repeat fixed;
This would be (in this example):
background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none;
and all the others to the initial
state (as they are not being declared).
So, background:none;
is:
background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
Now, when you define only the color (in your case transparent
) then you are basically saying:
background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
I repeat, as @Quentin rightly says the default
transparent
and none
values in this case are the same, so in your example and for your original question, No, there's no difference between them.
But!.. if you say background:none
Vs background:red
then yes... there's a big diference, as I say, the first would set all properties to none/default
and the second one, will only change the color
and remains the rest in his default
state.
Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.
default
)Initial value the concatenation of the initial values of its longhand properties:
background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent
background
descriptions hereUpd2: Clarify better the background:none;
specification.
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
If you want to write unit per meter (m^-1)
, use $m^{-1}$)
, which means -1
inbetween {}
Example:
plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )
This error is actually the result of you not including bootstrap's javascript before calling the modal
function. Modal is defined in bootstrap.js not jQuery. It's also important to note that bootstrap actually needs jQuery to define the modal
function, so it's vital that you include jQuery before including bootstrap's javascript. To avoid the error just be sure to include jQuery then bootstrap's javascript before you call the modal
function. I usually do the following in my header tag:
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/path/to/bootstrap/js/bootstrap.min.js"></script>
</header>
def my_string = "some string"
println "here: " + my_string
Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.
Examples from Apache use this:
CloseableHttpClient httpclient = HttpClients.createDefault();
The class org.apache.http.impl.client.HttpClients
is there since version 4.3.
The code for HttpClients.createDefault()
is the same as the accepted answer in here.
ansible your_server_name -i custom_inventory_file_name -m -a "uptime"
The default module is command module, hence command
keyword is not required.
If you need to issue any command with elevated privileges use -b
at the end of the same command.
ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b
you can do like this @item.Date.Value.Tostring("dd-MMM-yy");
$ git remote remove <name>
ie.
$ git remote remove upstream
that should do the trick
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
You need to use either
$(command-here)
or
`command-here`
#!/bin/bash
VAR1="$1"
VAR2="$2"
MOREF="$(sudo run command against "$VAR1" | grep name | cut -c7-)"
echo "$MOREF"
You can't pass an anonymous type to a non generic function, unless the parameter type is object
.
public void LogEmployees (object obj)
{
var list = obj as IEnumerable();
if (list == null)
return;
foreach (var item in list)
{
}
}
Anonymous types are intended for short term usage within a method.
From MSDN - Anonymous Types:
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing.
(emphasis mine)
Update
You can use generics to achieve what you want:
public void LogEmployees<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
}
}
Whether you're using the maven eclipse plugin or m2eclipse, Eclipse's project configuration is derived from the POM, so you need to configure the maven compiler plugin for 1.6 (it defaults to 1.4).
Add the following to your project's pom.xml
, save, then go to your Eclipse project and select Properties > Maven > Update Project Configuration:
<project>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I created a method just for that. I use it any time I need to manually update a ListView
. Hopefully this gives you an idea of how to implement your own
public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{
if(ListVw != null)
{
final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();
//You'll have to create this method in your adapter class. It's a simple setter.
adapter.SetList(SomeObjects);
adapter.notifyDataSetChanged();
}
}
I'm using an adapter that inherites from BaseAdapter
. Should work for any other type of adapter.
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
It seems as though this is not easily possible: The Arch Linux Wiki lists no way to do this on the console (while easily possible on the virtual terminal).
You could use tmux scrolling:
Ctrl-b then [ then you can use your normal navigation keys to scroll around (eg. Up Arrow or PgDn). Press q to quit scroll mode.
Alternatively you can press Ctrl-b PgUp to go directly into copy mode and scroll one page up (which is what it sounds like you will want most of the time)
If you are sending HTML email then use <BR> (or <BR />, or </BR>) as stated.
If you are sending a plain text email then use %0D%0A
\r = %0D (Ctrl+M = carriage return)
\n = %0A (Ctrl+A = line feed)
If you have an email link in your email,
EG
<A HREF="mailto?To=...&Body=Line 1%250D%250ALine 2">Send email</A>
Then use %250D%250A
%25 = %
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
Try this :
return new ContentResult() {
StatusCode = 404,
Content = "Not found"
};
i have experienced the same problem, and after reading this post i have double checked the JAVA_HOME
definition in .bash_profile
. It is actually:
export JAVA_HOME=$(which java)
that, exactly as Anony-Mousse is explaining, is the executable. Changing it to:
export=/Library/Java/Home
fixes the problem, tho is still interesting to understand why it's valued in that way in the profile file.
The string is surrounded by double quotes. Yes, that's not a valid character in a path.
You should probably tackle it at the source, but you can strip them out with:
path = path.Replace("\"", "");
i think, simply camera not initialize in first frame. Try to save image after 10 frames.
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
Go to Run type services.msc
. Check whether MySQL
services is running or not. If not, start it manually.
Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay
. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.
The key excerpt to look at is:
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)
learning_rate = tf.train.exponential_decay(
0.01, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
train_size, # Decay step.
0.95, # Decay rate.
staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
0.9).minimize(loss,
global_step=batch)
Note the global_step=batch
parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.
You can try with GhostScript like in this post:
How to print PDF on default network printer using GhostScript (gswin32c.exe) shell command
I am used to Chrome's color
so the blue color in Chrome for link is #007bff
You can try/catch PDOException
s (your configs could differ but the important part is the try/catch):
try {
$dbh = new PDO(
DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE
]
);
} catch ( PDOException $e ) {
echo 'ERROR!';
print_r( $e );
}
The print_r( $e );
line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'
.
I think you'll have to import the project via the file->import wizard:
http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse
It's not the last step, but it will start you on your way.
I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).
Here's what I use:
NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
(times 1000 for milliseconds, otherwise, take that out)
If You're using it all the time, it might be nice to declare a macro
#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]
Then Call it like this:
NSString * timestamp = TimeStamp;
Or as a method:
- (NSString *) timeStamp {
return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}
As TimeInterval
- (NSTimeInterval) timeStamp {
return [[NSDate date] timeIntervalSince1970] * 1000;
}
NOTE:
The 1000 is to convert the timestamp to milliseconds. You can remove this if you prefer your timeInterval in seconds.
Swift
If you'd like a global variable in Swift, you could use this:
var Timestamp: String {
return "\(NSDate().timeIntervalSince1970 * 1000)"
}
Then, you can call it
println("Timestamp: \(Timestamp)")
Again, the *1000
is for miliseconds, if you'd prefer, you can remove that. If you want to keep it as an NSTimeInterval
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
Declare these outside of the context of any class and they'll be accessible anywhere.