You can put two figures inside one figure environment. For example:
\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}
Each caption will generate a separate figure number.
First, what happens when T0 is not None
? I would test that, then I would adjust the values I pass to plt.subplot()
; maybe try values 131, 132, and 133, or values that depend whether or not T0
exists.
Second, after plt.show()
is called, a new figure is created. To deal with this, you can
Call plt.savefig('tessstttyyy.png', dpi=100)
before you call plt.show()
Save the figure before you show()
by calling plt.gcf()
for "get current figure", then you can call savefig()
on this Figure
object at any time.
For example:
fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)
In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.
However, numbering starts at 1
, so:
x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)
z = np.sin(x)
plt.figure(2)
plt.plot(x, z)
w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)
Also, if you have multiple axes on a figure, such as subplots, use the axes(h)
command where h
is the handle of the desired axes object to focus on that axes.
(don't have comment privileges yet, sorry for new answer!)
I was having an issue with the x-label overlapping a subplot title; this worked for me:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].scatter(...)
ax[1].scatter(...)
plt.tight_layout()
.
.
.
plt.show()
reference:
To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using
pip install pillow
Once Pillow is installed, the standard Matplotlib commands
import matplotlib.pyplot as plt
plt.plot([1, 2])
plt.savefig('image.jpg')
will save the figure into a JPEG file and will not generate a ValueError any more.
Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.
While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.
Example: you have five figures on your desktop from a previous script you ran and you use
figure(1);
plot(...)
figure(2);
plot(...)
You just plotted over the figures on your desktop. However the code
figure;
plot(...)
figure;
plot(...)
just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.
You can use gridspec
and figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:
hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');
This will do exactly as manually saving the figure.
source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C
Just clear the plots and try executing the code again...It worked for me
These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".
Alternative form for add_subplot(111)
is add_subplot(1, 1, 1)
.
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
The easiest way is:
onClick= 'location.href="/controller/action/"+paramterValue'
This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)
PATH_SRC="/home/celvas/Documents/Imp_Task/"
PATH_DST="/home/celvas/Downloads/zeeshan/"
cd $PATH_SRC
TODAY=$(date -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)
for f in `ls`;
do
# echo "File -> $f"
MOD_DATE=$(stat -c %y "$f")
MOD_DATE=${MOD_DATE% *}
# echo MOD_DATE: $MOD_DATE
MOD_DATE1=$(date -d "$MOD_DATE" +%s)
# echo MOD_DATE: $MOD_DATE
DIFF_IN_DATE=$[ $MOD_DATE1 - $TODAY ]
DIFF_IN_DATE1=$[ $MOD_DATE1 - $TODAY_TIME ]
#echo DIFF: $DIFF_IN_DATE
#echo DIFF1: $DIFF_IN_DATE1
if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
then
echo File lies in Next Hour = $f
echo MOD_DATE: $MOD_DATE
#mv $PATH_SRC/$f $PATH_DST/$f
fi
done
For example you want files having modification date before the given date only, you may change 120
to 0
in $DIFF_IN_DATE
parameter discarding the conditions of $DIFF_IN_DATE1
parameter.
Similarly if you want files having modification date 1 hour before and after given date,
just replace 120
by 3600
in if CONDITION
.
Since ID is auto increment, you can also specify ID=NULL as,
LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;
There are two additional ways to do it apart from the two methods mentioned in @PradeepJain's answer.
I would suggest not to use this approach and to fall back to this only as a last resort if you are not using [(ngModel)]
directive and also not using data binding via [value]
. Read this for more info.
app.component.html
<div>
<input type="text" #searchInput placeholder="Search...">
<button (click)="clearSearchInput()">Clear</button>
</div>
app.component.ts
export class App {
@ViewChild('searchInput') searchInput: ElementRef;
clearSearchInput(){
this.searchInput.nativeElement.value = '';
}
}
app.component.html
<form [formGroup]="form">
<div *ngIf="first.invalid"> Name is too short. </div>
<input formControlName="first" placeholder="First name">
<input formControlName="last" placeholder="Last name">
<button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
<button (click)="clearInputMethod1()">Clear Input Method 1</button>
<button (click)="clearInputMethod2()">Clear Input Method 2</button>
app.component.ts
export class AppComponent {
form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew'),
});
get first(): any { return this.form.get('first'); }
get last(): any { return this.form.get('last'); }
clearInputMethod1() { this.first.reset(); this.last.reset(); }
clearInputMethod2() { this.form.setValue({first: '', last: ''}); }
setValue() { this.form.setValue({first: 'Nancy', last: 'Drew'}); }
}
Try it out on stackblitz Clearing input in a FormGroup
kennytm's links are dead and he doesn't provide an example so here's how you do substrings:
=MID(text, start_num, char_num)
Let's say cell A1
is Hello
.
=MID(A1, 2, 3)
Would return
ell
Because it says to start at character 2, e
, and to return 3 characters.
If you're using Ubuntu 16.04.
You need to find the composer config files in my case is :
~/.config/composer
or in other cases ~/.composer/
you can see the dir after this command composer global require "laravel/installer"
after Laravel Installed you can find your laravel in ~/.config/composer/vendor/laravel/installer/
.
and you will find the Laravel shortcut command in here : ~/.config/composer/vendor/bin/
set your .bashrc using nano ~/.bashrc
and export your composer config file :
export PATH="$PATH:$HOME/.config/composer/vendor/bin"
or you can use allias. but above solution is recommended.
alias laravel='~/.config/composer/vendor/laravel/installer/laravel'
Now refresh your bashrc using source ~/.bashrc
and then laravel is ready!!
above steps works with me in Ubuntu 16.04
In my case, I added my component to declarations and entryComponents and got the same errors. I also needed to add MatDialogModule to imports.
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
You can run this in powershell:
[System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile
Which outputs this for .net 4:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
Note however that this might change depending on whether .net is running as 32 or 64 bit which will result in \Framework\
or \Framework64\
respectively.
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
A couple ways this can be done:
This will make it a square
ul
{
list-style-type: square;
}
This will make it green
li
{
color: #0F0;
}
This will prevent the text from being green
li p
{
color: #000;
}
However that will require that all text within lists be in paragraphs so that the color is not overridden.
A better way is to make an image of a green square and use:
ul
{
list-style: url(green-square.png);
}
To be able to pass the select
, I just set it back to :
$('#selectID').prop('disabled',false);
or
$('#selectID').attr('disabled',false);
when passing the request.
Rename filename by searching the last character of name. For example,
Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt
Option Explicit
Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
ForceConsole()
arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)
WScript.StdOut.WriteLine "This is a test script."
Dim result
result = InstrRev(arg1, arg2, -1)
If result > 0 then
newFilename = Mid(arg1, 1, result - 1)
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile arg1, newFilename
WScript.StdOut.WriteLine newFilename
End If
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
I was getting this error when trying to run my test web page directly from "file:///C:/webtests/myfile.htm". To fix it, I didn't have to make any changes to my App Settings. Instead, I just had to host my HTML file on an actual server and then hit it like: "http://localhost/myfile.htm".
Hope that helps someone.
simple answer for Angular 8.*
constructor(private route:ActivatedRoute) {
console.log(route);
}
This won't directly solve your problem as you want to switch on your own user-defined types, but for the benefit of others who only want to switch on built-in types, you can use the TypeCode enumeration:
switch (Type.GetTypeCode(node.GetType()))
{
case TypeCode.Decimal:
// Handle Decimal
break;
case TypeCode.Int32:
// Handle Int32
break;
...
}
Now in 2020 Selenium 4 supports authenticating using Basic and Digest auth . Its using the CDP and currently only supports chromium-derived browsers
Example :
Java Example :
Webdriver driver = new ChromeDriver();
((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));
driver.get("http://sitewithauth");
Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894
help(input)
shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:
input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.
You could reproduce it using an empty file:
$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
You could use /dev/null
or nul
(Windows) as an empty file for reading. os.devnull
shows the name that is used by your OS:
$ python3 -c "import os; print(os.devnull)"
/dev/null
Note: input()
happily accepts input from a file/pipe. You don't need stdin
to be connected to the terminal:
$ echo abc | python3 -c "print(input()[::-1])"
cba
Either handle EOFError
in your code:
try:
reply = input('Enter text')
except EOFError:
break
Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file
Readonly will allow the user to copy text from it. Disabled will not.
app.config
<client>
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="LisansSoap"
contract="Lisans.LisansSoap"
name="LisansSoap" />
</client>
program
Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
"http://webservis.uzmanevi.com/Lisans/Lisans.asmx");
MessageBox.Show(test.LisansKontrol("","",""));
Use
txtdate.Text = DateTime.Today.ToString("dd-MM-yyyy");
I got the same error with a class like the following StockPickBean
. Called from this code:
List<StockPickBean> beansListcatMap.getValue();
beansList.sort(StockPickBean.Comparators.VALUE);
public class StockPickBean implements Comparable<StockPickBean> {
private double value;
public double getValue() { return value; }
public void setValue(double value) { this.value = value; }
@Override
public int compareTo(StockPickBean view) {
return Comparators.VALUE.compare(this,view); //return
Comparators.SYMBOL.compare(this,view);
}
public static class Comparators {
public static Comparator<StockPickBean> VALUE = (val1, val2) ->
(int)
(val1.value - val2.value);
}
}
After getting the same error:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
I changed this line:
public static Comparator<StockPickBean> VALUE = (val1, val2) -> (int)
(val1.value - val2.value);
to:
public static Comparator<StockPickBean> VALUE = (StockPickBean spb1,
StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);
That fixes the error.
Sorry, not enough rep to add a comment, but from zmbq's answer:
Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.
is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:
bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;
Since this is the de facto answer when dealing with quotes in bash
, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.
The bash
shell supports two ways do arithmetic operation, one defined by the built-in let
command and the $((..))
operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.
It is important to understand that the arithmetic expression used with let
undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.
See this example when using let
let 'foo = 2 + 1'
echo $foo
3
Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of
bar=1
let 'foo = $bar + 1'
would fail miserably, as the $bar
under single quotes would not expand and needs to be double-quoted as
let 'foo = '"$bar"' + 1'
This should be one of the reasons, the $((..))
should always be considered over using let
. Because inside it, the contents aren't subject to word-splitting. The previous example using let
can be simply written as
(( bar=1, foo = bar + 1 ))
$((..))
without single quotesThough the $((..))
can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.
printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2
May be in some special cases of using the $((..))
operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl
statement to pass a counter every time a request is made, do
curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'
Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++))
is passed to requestCounter
field.
I faced the same issue. Mongo DB repository was identified by Spring boot, but it was not creating Bean for a repository interface that extended the mongo repository.
The issue in my case was incorrect version specification in maven pom for "spring + mango". I have changed the artifact's group id and it all worked like magic. no annotations needed as spring boot took care of everything.
During my problem resolution, I was all over web searching for solutions and realized that this problem is actually project configuration related, anyone facing this issue should first check their project setup and enable debug from spring to get more details on failure and pay close attention to where exactly in the process, the creation has failed.
When the table is very large, it's better to delete table itself with drop table TableName
and recreate it, if one has create table query; rather than deleting records one by one, using delete from
statement because that can be time consuming.
(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:
$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();
Oh, also: count()
instead if exists
but this could be something used after get
.
Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
Addition:
When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()
[1])
In this case, use an additional cast to binary:
SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;
Otherwise, the SELECT
statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.
You can do this using generic SQL with group by
:
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
tbl_Media M
ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;
Or with a correlated subquery:
SELECT C.Content_ID, C.Contt_Title,
(SELECT M.Media_Id
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
ORDER BY M.MEDIA_ID DESC
LIMIT 1
) as Media_Id
FROM tbl_Contents C
ORDER BY C.Content_DatePublished ASC;
Of course, the syntax for limit 1
varies between databases. Could be top
. Or rownum = 1
. Or fetch first 1 rows
. Or something like that.
pimvdb's answer implemented in python:
def DecodedCharArrayFromByteStreamIn(stringStreamIn):
#turn string values into opererable numeric byte values
byteArray = [ord(character) for character in stringStreamIn]
datalength = byteArray[1] & 127
indexFirstMask = 2
if datalength == 126:
indexFirstMask = 4
elif datalength == 127:
indexFirstMask = 10
masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
indexFirstDataByte = indexFirstMask + 4
decodedChars = []
i = indexFirstDataByte
j = 0
while i < len(byteArray):
decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
i += 1
j += 1
return decodedChars
An Example of usage:
fromclient = '\x81\x8c\xff\xb8\xbd\xbd\xb7\xdd\xd1\xd1\x90\x98\xea\xd2\x8d\xd4\xd9\x9c'
# this looks like "?ŒOÇ¿¢gÓ ç\Ð=«ož" in unicode, received by server
print DecodedCharArrayFromByteStreamIn(fromclient)
# ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
you can load the new content in an iframe to avoid css inheritance.
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
If you're working with prices, I'm sure you can safely assume nothing will cost more than 1 trillion dollars.
I'd use:
[Range(0.0, 1000000000000)]
Or if you really need it, just paste in the value of Decimal.MaxValue
(without the commas): 79,228,162,514,264,337,593,543,950,335
Either one of these will work well if you're not from Zimbabwe.
You can always use
header('Location: https://www.domain.com/cart_save/');
to redirect to the save URL.
But I would recommend to do it by .htaccess and the Apache rewrite rules.
You can add atom beauty package for formatting text in atom..
file --> setting --> Install
then you type atom-beautify in search area.
then click Package button.. select atom beuty and install it.
next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents
This worked for me Android Studio 4.0.1:
Close Android Studio.
Navigate to C:\Users[Username].AndroidStudio4.0\config\options
Locate recentProjects.xml and open it.
Scroll down the page you will notice: <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" />
Change $USER_HOME$/AndroidStudioProjects to your desired location: /home/USER/AndroidStudioProjects/
Reopen Android studio.
Use hamcrest Matcher containsString()
// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
got: "some other name"
You can optional add an even more detail error message.
// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
got: "some other name"
Posted my answer to a duplicate question here
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD
If you want to undo an earlier change permanently, use Revert to this revision instead.
-- from TSVN help doc
If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.
Create the src folder in the project.
I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side. Again if it has has enough space on the right side, it will show right side. it is a loop...
$(document).ready(function () {
$('body, html').css('overflow', 'hidden');
var screenWidth = $(window).width();
$('body, html').css('overflow', 'visible');
if (screenWidth > 767) {
$(".dropdown-submenu").hover(function () {
var dropdownPosition = $(this).offset().left + $(this).width() + $(this).find('ul').width();
var newPosition = $(this).offset().left - $(this).find('ul').width();
var windowPosition = $(window).width();
var oldPosition = $(this).offset().left + $(this).width();
//document.title = dropdownPosition;
if (dropdownPosition > windowPosition) {
$(this).find('ul').offset({ "left": newPosition });
} else {
$(this).find('ul').offset({ "left": oldPosition });
}
});
}
});
This worked for me:
<video src="file.mp4" controls style="max-width:100%; height:auto"></video>
I had the same issue, running Netbeans 8.0 on Windows, and JRE 1.7.
I just installed JRE 1.8 from https://www.java.com/fr/download/ (note that it's called Version 8
but it's version 1.8 when you install it), and it fixed it.
1.Download and install: Microsoft Office Developer Tools
2.Add references from:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
If you are using variables, you can use
first_var="Hello"
second_var="How are you"
If you want to concat both string and write it to file, then use below
echo "${first_var} - ${second_var}" > ./file_name.txt
Your file_name.txt content will be "Hello - How are you"
I recommend you exit the Python interpreter with Ctrl-D. This is the old ASCII code for end-of-file or end-of-transmission.
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
Mockito [3.4.0] can mock static methods!
Replace mockito-core
dependency with mockito-inline:3.4.0
.
Class with static method:
class Buddy {
static String name() {
return "John";
}
}
Use new method Mockito.mockStatic()
:
@Test
void lookMomICanMockStaticMethods() {
assertThat(Buddy.name()).isEqualTo("John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(Buddy::name).thenReturn("Rafael");
assertThat(Buddy.name()).isEqualTo("Rafael");
}
assertThat(Buddy.name()).isEqualTo("John");
}
Mockito replaces the static method within the try
block only.
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
Run this command in project root directory.
1>. List of iPhone devices for found the connected Real Devices and Simulator. same as like adb devices command for android.
xcrun instruments -s devices
2>. Select device using this command which you want to run your app
Using Device Name
react-native run-ios --device "Kool's iPhone"
Using UDID
react-native run-ios --device --udid 0412e2c2******51699
wait and watch to run your app in specific devices - K00L ;)
ES6 - I am including an example, which was helpful for me:
In a "short if statement" you can pass empty function like this:
isReady ? ()=>{} : onClick
This seems to be the shortest approach.
()=>{}
Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId
to create common id so that I can inner join them:
Insert Into #TempResult
select CountA, CountB, CountC from
(
select Count(A_Id) as CountA, 1 as commonId from tableA
where ....
and ...
and ...
) as tempA
inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
where ...
and ...
and ...
) as tempB
on tempA.commonId = tempB.commonId
inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and ...
) as tempC
on tmepB.commonId = tempC.commonId
--view insert result
select * from #TempResult
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
]4
The line
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
would do the same as
when(someObject.doSomething(Matchers.any())).thenReturn(true);
So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.
And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.
so simple try this
<div dir="ltr" style="text-align: left;" trbidi="on">_x000D_
<!-- begin snippet: js hide: false console: true babel: null -->
_x000D_
Setting Tomcat to listen to port 80 is WRONG , for development the 8080 is a good port to use. For production use, just set up an apache that shall forward your requests to your tomcat. Here is a how to.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.
The file .bash_profile
is only executed by login shells. You may need to put it in ~/.bashrc
, or simply logout and login again.
A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field
L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.
Just to add additional solution with Reduce
which probably is slower than do.call
but probebly better than apply
because it will avoid the matrix
conversion. Also, instead a for
loop we could just use setdiff
in order to remove unwanted columns
cols <- c('b','c','d')
data$x <- Reduce(function(...) paste(..., sep = "-"), data[cols])
data[setdiff(names(data), cols)]
# a x
# 1 1 a-d-g
# 2 2 b-e-h
# 3 3 c-f-i
Alternatively we could update data
in place using the data.table
package (assuming fresh data)
library(data.table)
setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD[, mget(cols)])]
data[, (cols) := NULL]
data
# a x
# 1: 1 a-d-g
# 2: 2 b-e-h
# 3: 3 c-f-i
Another option is to use .SDcols
instead of mget
as in
setDT(data)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols]
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
Lame answer but: Remember to make sure no proxy is set in a ~/.curlrc
file (...).
Avoid using C-Style casts.
C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.
I attended a coursera course, there was lesson in which, we were taught about design recipe.
Below docstring format I found preety useful.
def area(base, height): '''(number, number ) -> number #**TypeContract** Return the area of a tring with dimensions base #**Description** and height >>>area(10,5) #**Example ** 25.0 >>area(2.5,3) 3.75 ''' return (base * height) /2
I think if docstrings are written in this way, it might help a lot to developers.
Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI
In version 3 of the Maps API you can simply set the scrollwheel
option to false within the MapOptions properties:
options = $.extend({
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}, options);
If you were using version 2 of the Maps API you would have had to use the disableScrollWheelZoom() API call as follows:
map.disableScrollWheelZoom();
The scrollwheel
zooming is enabled by default in version 3 of the Maps API, but in version 2 it is disabled unless explicitly enabled with the enableScrollWheelZoom()
API call.
You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.
Capture photo from camera + pick image from gallery and set it into the background of layout or imageview. Here is sample code.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class Post_activity extends Activity
{
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView openCameraOrGalleryBtn,cancelBtn;
LinearLayout backGroundImageLinearLayout;
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
overridePendingTransition(R.anim.slide_up,0);
setContentView(R.layout.post_activity);
backGroundImageLinearLayout=(LinearLayout)findViewById(R.id.background_image_linear_layout);
cancelBtn=(ImageView)findViewById(R.id.cancel_icon);
openCameraOrGalleryBtn=(ImageView)findViewById(R.id.camera_icon);
openCameraOrGalleryBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
overridePendingTransition(R.anim.slide_down,0);
finish();
}
});
}
public void selectImage()
{
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Post_activity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
}
}
public void onBackPressed() {
super.onBackPressed();
//overridePendingTransition(R.anim.slide_down,0);
}
}
Add these permission in Androidmenifest.xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<select>
<option disabled selected>select your beverage</option>
<option >Tea</option>
<option>coffee</option>
<option>soda</option>
</select>
@Before
(JUnit4) -> @BeforeEach
(JUnit5) - method is called before every test
@After
(JUnit4) -> @AfterEach
(JUnit5) - method is called after every test
@BeforeClass
(JUnit4) -> @BeforeAll
(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...
@AfterClass
(JUnit4) -> @AfterAll
(JUnit5) - static method is called after executing all tests in this class.
I have done for
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
You can create a util method that converts any collection to a java list
public static List<?> convertObjectToList(Object obj) {
List<?> list = new ArrayList<>();
if (obj.getClass().isArray()) {
list = Arrays.asList((Object[])obj);
} else if (obj instanceof Collection) {
list = new ArrayList<>((Collection<?>)obj);
}
return list;
}
you can also mix with this validation below:
public static boolean isCollection(Object obj) {
return obj.getClass().isArray() || obj instanceof Collection;
}
The behavior of host objects <object>
is due to ECMA262 implementation dependent and set attribute by setAttribute()
method may fail.
I see two solutions:
soft: element.data = "http://www.google.com";
hard: remove object from DOM tree and create new one with changed data attribute.
After I have downloaded the binary from apache site I, have placed the extracted folder in /Library
So now the location of the settings.xml file is in:
/Library/apache_maven_3.6.3/conf
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
faster way (without pyspark.sql.functions
)
df.filter((df.d<5)&((df.col1 != df.col3) |
(df.col2 != df.col4) &
(df.col1 ==df.col3)))\
.show()
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use below command:
git cherry-pick A C F J
Web Workers provide an utils URL for url parsing.
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName
is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
Is there any problem?
There are several issues:
CString
is a template specialization of CStringT. Depending on the BaseType describing the character type, there are two concrete specializations: CStringA
(using char
) and CStringW
(using wchar_t
).wchar_t
on Windows is ubiquitously used to store UTF-16 encoded code units, using char
is ambiguous. The latter commonly stores ANSI encoded characters, but can also store ASCII, UTF-8, or even binary data.CString
(which is controlled through the _UNICODE
preprocessor symbol), making the question ambiguous. We also don't know the desired character encoding of std::string
.To address these issues, I'm going to assume that wchar_t
will store UTF-16 encoded code units, and char
will hold UTF-8 octet sequences. That's the only reasonable choice you can make to ensure that source and destination strings retain the same information, without limiting the solution to a subset of the source or destination domains.
The following implementations convert between CStringA
/CStringW
and std::wstring
/std::string
mapping from UTF-8 to UTF-16 and vice versa:
#include <string>
#include <atlconv.h>
std::string to_utf8(CStringW const& src_utf16)
{
return { CW2A(src_utf16.GetString(), CP_UTF8).m_psz };
}
std::wstring to_utf16(CStringA const& src_utf8)
{
return { CA2W(src_utf8.GetString(), CP_UTF8).m_psz };
}
The remaining two functions construct C++ string objects from MFC strings, leaving the encoding unchanged. Note that while the previous functions cannot cope with embedded NUL characters, these functions are immune to that.
#include <string>
#include <atlconv.h>
std::string to_std_string(CStringA const& src)
{
return { src.GetString(), src.GetString() + src.GetLength() };
}
std::wstring to_std_wstring(CStringW const& src)
{
return { src.GetString(), src.GetString() + src.GetLength() };
}
If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32
You can use this query for checking database connection in laravel:
$pdo = DB::connection()->getPdo();
if($pdo)
{
echo "Connected successfully to database ".DB::connection()->getDatabaseName();
} else {
echo "You are not connected to database";
}
For more information you can checkout this page https://laravel.com/docs/5.0/database.
To change the end address property edit your wsdl file
<wsdl:definitions.......
<wsdl:service name="serviceMethodName">
<wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
<soap:address location="http://service_end_point_adress"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
If your access remotely you can do it
for bson:
mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people "/home/${USER}/people.bson"
for bson compressed in .gz (gzip) format:
mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people --gzip --dir "/home/${USER}/people.bson.gz"
List.stream().mapToDouble(a->a).average()
First,Remove files from local repository.
git rm -r File-Name
or, remove files only from local repository but from filesystem
git rm --cached File-Name
Secondly, Commit changes into local repository.
git commit -m "unwanted files or some inline comments"
Finally, update/push local changes into remote repository.
git push
I set the PHPRC variable and uncommented zend_extension=php_opcache.dll
in php.ini
and all works well.
I use moment along with new Date to handle cases of undefined
data values:
const date = moment(new Date("2016-10-19"));
because of: moment(undefined).isValid() == true
where as the better way: moment(new Date(undefined)).isValid() == false
@media screen and (max-width : 760px)
(for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
http://www.minixml.org is also pretty good. Small and just ANSI C.
Do not include bin in your JAVA_HOME env variable
The current best way to do this is to use df.to_string()
:
with open(writePath, 'a') as f:
f.write(
df.to_string(header = False, index = False)
)
Will output the following
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
This method also lets you easily choose which columns to print with the columns
attribute, lets you keep the column, index labels if you wish, and has other attributes for spacing ect.
If it really is a List<string>
you don't need LINQ, just use:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
If you are looking for the item itself, try:
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
Another implementation, which could work with nullable selector keys, and for the collection of reference type returns null if no suitable elements found. This could be helpful then processing database results for example.
public static class IEnumerableExtensions
{
/// <summary>
/// Returns the element with the maximum value of a selector function.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <param name="source">An IEnumerable collection values to determine the element with the maximum value of.</param>
/// <param name="keySelector">A function to extract the key for each element.</param>
/// <exception cref="System.ArgumentNullException">source or keySelector is null.</exception>
/// <exception cref="System.InvalidOperationException">source contains no elements.</exception>
/// <returns>The element in source with the maximum value of a selector function.</returns>
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => MaxOrMinBy(source, keySelector, 1);
/// <summary>
/// Returns the element with the minimum value of a selector function.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
/// <param name="source">An IEnumerable collection values to determine the element with the minimum value of.</param>
/// <param name="keySelector">A function to extract the key for each element.</param>
/// <exception cref="System.ArgumentNullException">source or keySelector is null.</exception>
/// <exception cref="System.InvalidOperationException">source contains no elements.</exception>
/// <returns>The element in source with the minimum value of a selector function.</returns>
public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => MaxOrMinBy(source, keySelector, -1);
private static TSource MaxOrMinBy<TSource, TKey>
(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, int sign)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
Comparer<TKey> comparer = Comparer<TKey>.Default;
TKey value = default(TKey);
TSource result = default(TSource);
bool hasValue = false;
foreach (TSource element in source)
{
TKey x = keySelector(element);
if (x != null)
{
if (!hasValue)
{
value = x;
result = element;
hasValue = true;
}
else if (sign * comparer.Compare(x, value) > 0)
{
value = x;
result = element;
}
}
}
if ((result != null) && !hasValue)
throw new InvalidOperationException("The source sequence is empty");
return result;
}
}
Example:
public class A
{
public int? a;
public A(int? a) { this.a = a; }
}
var b = a.MinBy(x => x.a);
var c = a.MaxBy(x => x.a);
I found the solution at: Passing data to a bootstrap modal
So simply use:
$(e.relatedTarget).data('book-id');
with 'book-id
' is a attribute of modal with pre-fix 'data-
'
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
static final String path = "src/resources/log4j.properties";
public static void main(String[] args) {
PropertyConfigurator.configure(path);
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);
I fixed this issue like that:
rm -fr ~/Library/Caches/CocoaPods && \
gem update --system && \
gem update && \
gem cleanup && \
pod setup
Reference: http://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/
Actually, you can use the <!--...--> format with multi-lines or tags:
<!--
...
...
...
-->
In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.
For \d use \p{N} (numbers)
For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)
Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.
I wanted to have two separate instances of Chrome running, each using its own profile. I wanted to be able to start them from Spotlight, as is my habit for starting Mac apps. In other words, I needed two regular Mac applications, regChrome
for normal browsing and altChrome
to use the special profile, to be easily started by keying ?-space to bring up Spotlight, then 'reg' or 'alt', then Enter.
I suppose the brute-force way to accomplish the above goal would be to make two copies of the Google Chrome application bundle under the respective names. But that's ugly and complicates updating.
What I ended up with was two AppleScript applications containing two commands each. Here is the one for altChrome
:
do shell script "cd /Applications/Google\\ Chrome.app/Contents/Resources/; rm app.icns; ln /Users/garbuck/local/chromeLaunchers/Chrome-swirl.icns app.icns"
do shell script "/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --user-data-dir=/Users/garbuck/altChrome >/dev/null 2>&1 &"
The second line starts Chrome with the alternate profile (the --user-data-dir
parameter).
The first line is an unsuccessful attempt to give the two applications distinct icons. Initially, it appears to work fine. However, sooner or later, Chrome rereads its icon file and gets the one corresponding to whichever of the two apps was started last, resulting in two running applications with the same icon. But I haven't bothered to try to fix it — I keep the two browsers on separate desktops, and navigating between them hasn't been a problem.
dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.
Using Blade
I created the file resources/views/includes/confirmation_modal.blade.php
:
<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>{{ $headerText }}</h4>
</div>
<div class="modal-body">
{{ $bodyText }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form action="" method="POST" style="display:inline">
{{ method_field($verb) }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirmation-modal').on('show.bs.modal', function(e) {
href = $(e.relatedTarget).data('href');
// change href of button to corresponding target
$(this).find('form').attr('action', href);
});
</script>
Now, using it is straight-forward:
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
Not much changed here and the modal can be included like this:
@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])
Just by putting the verb in there, it uses it. This way, CSRF is also utilized.
Helped me, maybe it helps someone else.
Use Date.Now
instead of DateTime.Now
@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:
javascripts.php:
<?php
//sets the content type to javascript
header('Content-type: text/javascript');
// includes all js files of the directory
foreach(glob("packages/*.js") as $file) {
readfile($file);
}
?>
index.php:
<script type="text/javascript" src="javascripts.php"></script>
That's it!
Have fun! :)
You can use the built-in function:
SUSER_ID ( [ 'myUsername' ] )
via
IF [value] IS NULL [statement]
like:
IF SUSER_ID (N'myUsername') IS NULL
CREATE LOGIN [myUsername] WITH PASSWORD=N'myPassword',
DEFAULT_LANGUAGE=[us_english],
CHECK_EXPIRATION=OFF,
CHECK_POLICY=OFF
GO
https://technet.microsoft.com/en-us/library/ms176042(v=sql.110).aspx
I dont know what is the exact reason but I solved the problem running:
app/console cache:clear --env=prod
If you want the file from a particular commit (any branch) , say 06f8251f
git checkout 06f8251f path_to_file
for example , in windows:
git checkout 06f8251f C:\A\B\C\D\file.h
As mentioned in many sites, there are various reasons for this. For me it was due to the length of Source and Destination (Path length). I tried xcopy in the command prompt and I was unable to type the complete source and path (after some characters it wont allow you to type). I then reduced the path length and was able to run. Hope this helps.
COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);
as described in the manual.
just enter the following command on command prompt after launching the app:
adb shell dumpsys window windows | find "mCurrentFocus"
if executing the command on linux terminal replace find by grep
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
Go to Start-> All Programs -> Accessories right click on Command Prompt click on Run as administrator
In the command prompt using CD command Go to MySQL bin folder and run the below command
mysqldump --user root --password=root --all-databases>dumps.sql
it will create dumps.sql file in the bin folder itself.
This should do it, removing characters from the left by one or however many needed.
lEFT(columnX,LEN(columnX) - 1) AS NewColumnName
My error was that the file was too large (dotnet core seems to have a limit @~25Mb). Setting
solved the problem for me.
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I was able to solve this issue by adding a file extension '.js'. I was using Intellij and created a js file, but it did not have the file extension. When I did a refractor rename and changed my component from 'List' to 'List.js' react native then knew how to resolve it.
Accepted answer doesn't work for me, but this does. Ensure script in the location (c:\temp_ below on each remote server. servers.txt contains a list of IP addresses (one per line).
psexec @servers.txt -u <username> cmd /c "powershell -noninteractive -file C:\temp\script.ps1"
It seems that there is no official solution for this problem, but there is a workaround posted here https://github.com/savoirfairelinux/python-docx/commit/afd9fef6b2636c196761e5ed34eb05908e582649
just update this file "...\site-packages\docx\oxml_init_.py"
# add
import re
import sys
# add
def remove_hyperlink_tags(xml):
if (sys.version_info > (3, 0)):
xml = xml.decode('utf-8')
xml = xml.replace('</w:hyperlink>', '')
xml = re.sub('<w:hyperlink[^>]*>', '', xml)
if (sys.version_info > (3, 0)):
xml = xml.encode('utf-8')
return xml
# update
def parse_xml(xml):
"""
Return root lxml element obtained by parsing XML character string in
*xml*, which can be either a Python 2.x string or unicode. The custom
parser is used, so custom element classes are produced for elements in
*xml* that have them.
"""
root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
return root_element
and of course don't forget to mention in the documentation that use are changing the official library
Removing outline
will harm accessibility of a website.Therefore i just leave that there but make it invisible.
a {
outline: transparent;
}
This jsfiddle works fine for me.
$(document).delegate(':file', 'change', function() {
console.log(this);
});
Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods
This is how I've done it.
HTML markup showing a label and button control is as follows.
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label>
<asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" />
</div>
</form>
</body>
JavaScript function is here.
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
Code behind to trigger the JavaScript function is here.
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
There's no such standard equivalent. Some IDEs - Intellij, for instance, or Eclipse - can fold depending on the code types involved (constructors, imports etc.), but there's nothing quite like #region
.
When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.
However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.
Tomcat itself has size limit for each port, and this is defined in conf\server.xml
. This is controlled by maxPostSize
attribute of each Connector
(port). If this attribute does not exist, which it is by default, there is no limit on the request size.
To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="209715200" />
After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.
To set limit through java annotation
@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
To set limit through web.xml
<web-app>
...
<servlet>
...
<multipart-config>
<file-size-threshold>0</file-size-threshold>
<max-file-size>209715200</max-file-size>
<max-request-size>209715200</max-request-size>
</multipart-config>
...
</servlet>
...
</web-app>
Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml
configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml
and follow the above guide to change the size limit and finally restart tomcat.
You should also make sure that the ports WAMP uses aren't already in use.
That can be done by typing the following command into the command prompt:
netstat –o
You must take the whole directory where java is installed, in my case:
export JAVA_HOME=/usr/java/jdk1.8.0_31
None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:
$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.
The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.
As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.
Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".
You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.
In Your disk drive:\xampp\apache\conf\extra\httpd-vhosts.conf exists an example and you could edit it with your configuration:
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
##ServerName dummy-host.example.com
##ServerAlias www.dummy-host.example.com
##ErrorLog "logs/dummy-host.example.com-error.log"
##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>
It would be like this, as example and don't forget to add VirtualHost for localhost itself to have posibility run phpmyadmin and other project at the same time on the port 80, as example I will show with store.local project:
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/xampp/htdocs/store.local/public"
ServerName www.store.local
ServerAlias store.local
<Directory C:/xampp/htdocs/store.local>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
then as mentioned above you must add in: C:\windows\system32\drivers\hosts to the bottom of the file
127.0.0.1 store.local
127.0.0.1 www.store.local
restart Apache and try in the browser:
store.local or www.store.local
maybe at the first time you must to add like this:
http://store.local or http://www.store.local
to use other ports, you must add follows, before your VirtualHost:
Listen 8081 or another which you prefer
then just use the port for your VirtualHost like this:
<VirtualHost *:8081>
ServerAdmin [email protected]
DocumentRoot "c:/xampp/htdocs/store.local/public"
ServerName store.local
ServerAlias www.store.local
<Directory C:/xampp/htdocs/store.local>
AllowOverride All
Require all granted
</Directory>
then restart Apache and try in the browser
store.local:8081 or www.store.local:8081
and only project for which you add the port will running on this port, for example other projects and phpmyadmin will be still running on port 80
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
The ActionBar
. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener
interface gives you a FragmentTransaction
as an input argument to the onTabSelected
method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
The FragmentManager
handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
You can use the cool ViewPager
with a FragmentPagerAdapter
to create swipe interfaces. The FragmentPagerAdapter
code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock
and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar
, with tabs, overflow, split action bar, viewpager etc.
Bonus 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity()
with data on it. The intent is passed on to all fragments of the activity you launch.
In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.
node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require()
is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require()
.
require()
is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require()
.
There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require()
that work similarly (though not identically).
But, you won't be running a web server in your browser as that is not something the browser has the capability to do.
You may be interested in browserify which lets you use node-style modules in a browser using require()
statements.
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});
So on a button click it will get string from edittext and store in listitem. you can change this to your needs.
I had the same issue. I came up with a simple solution. Use fragment .replace
instead of fragment .add
. Replacing fragment doing the same thing as adding fragment and then removing it manually.
getFragmentManager().beginTransaction().replace(fragment).commit();
instead of
getFragmentManager().beginTransaction().add(fragment).commit();
As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.
Some times it just happens due to installation of Wamp or changing of password options of root user. One can use privilages-->root (user) and then set password option to NO to run the things without any password OR set the password and use it in the application.
here is the solution for similar problem which i was facing while extracting name from user profile facebook json object
$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name ;
With LocationManager you can getLastKnownLocation() after you getBestProvider(). This gives you a Location object, which has the methods getAccuracy() in meters and getTime() in UTC milliseconds
Does this give you enough info?
Or perhaps you could iterate over the LocationProviders and find out if each one meetsCriteria( ACCURACY_COARSE )
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<div class="View"><?php include 'Small.php'; ?></div>
<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
$.ajaxSetup({ cache: true });
});
</script>
What you are saying is in conflict with what it says in the MSDN library at this location:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
I don't see any mention of the SP1 feature you mention.
I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".
return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".
I cleaned up mido's post and then cleaned up the function that they found. This will either return false
or an array
. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array
.
function ip_local()
{
var ip = false;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;
if (window.RTCPeerConnection)
{
ip = [];
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(event)
{
if (event && event.candidate && event.candidate.candidate)
{
var s = event.candidate.candidate.split('\n');
ip.push(s[0].split(' ')[4]);
}
}
}
return ip;
}
Additionally please keep in mind folks that this isn't something old-new like CSS border-radius
though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.
Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:
interface A
use Bar;
interface A
{
public function foo(Bar $b);
}
Class B
class B implements A
{
public function foo(Bar $b);
}
If you have forgotten to include the use
statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.
Sometimes if it is a new server you need to configure or install ASP.NET feature on IIS for it to be able to read your web.config file.
In my case this was the reason.
These numbers come from the IEEE-754 standard, which defines the standard representation of floating point numbers. Wikipedia article at the link explains how to arrive at these ranges knowing the number of bits used for the signs, mantissa, and the exponent.
std::string
is not Plain Old Data(POD), and its raw size is not the most relevant thing ever. For example, if you pass in a string which is above the length of SSO and allocated on the heap, I would expect the copy constructor to not copy the SSO storage.
The reason this is recommended is because inval
is constructed from the argument expression, and thus is always moved or copied as appropriate- there is no performance loss, assuming that you need ownership of the argument. If you don't, a const
reference could still be the better way to go.
seeing as autocomplete=off is deprecated, I suggest a more recent solution.
Set your password field to a normal text field, and mask your input with "discs" using CSS. the code should look like this:
<input type="text" class="myPassword" />
input .myPassword{
text-security:disc;
-webkit-text-security:disc;
-mox-text-security:disc;
}
Please note that this may not work propely on firefox browsers, and an additional walkaround is needed. Read more about it here :https://stackoverflow.com/a/49304708/5477548.
The solution was taken from this link, but to comply with SO "no-hotlinks" i summarized it here.
You can use stristr()
or strpos()
. Both return false if nothing is found.
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDb.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE_FRIDGE_ITEM = "create table FridgeItem(id integer primary key autoincrement,f_id text not null,food_item text not null,quantity text not null,measurement text not null,expiration_date text not null,current_date text not null,flag text not null,location text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_FRIDGE_ITEM);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS FridgeItem");
onCreate(database);
}
}
public class CommentsDataSource {
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public String stringArray[];
public final static String FOOD_TABLE = "FridgeItem"; // name of table
public final static String FOOD_ITEMS_DETAILS = "FoodDetails"; // name of table
public final static String P_ID = "id"; // pid
public final static String FOOD_ID = "f_id"; // id value for food item
public final static String FOOD_NAME = "food_item"; // name of food
public final static String FOOD_QUANTITY = "quantity"; // quantity of food item
public final static String FOOD_MEASUREMENT = "measurement"; // measurement of food item
public final static String FOOD_EXPIRATION = "expiration_date"; // expiration date of food item
public final static String FOOD_CURRENTDATE = "current_date"; // date of food item added
public final static String FLAG = "flag";
public final static String LOCATION = "location";
/**
*
* @param context
*/
public CommentsDataSource(Context context) {
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long insertFoodItem(String id, String name,String quantity, String measurement, String currrentDate,String expiration,String flag,String location) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
values.put(FLAG, flag);
values.put(LOCATION, location);
return database.insert(FOOD_TABLE, null, values);
}
public long insertFoodItemsDetails(String id, String name,String quantity, String measurement, String currrentDate,String expiration) {
ContentValues values = new ContentValues();
values.put(FOOD_ID, id);
values.put(FOOD_NAME, name);
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_MEASUREMENT, measurement);
values.put(FOOD_CURRENTDATE, currrentDate);
values.put(FOOD_EXPIRATION, expiration);
return database.insert(FOOD_ITEMS_DETAILS, null, values);
}
public Cursor selectRecords(String id) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, P_ID+"=?", new String[]{id}, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllName() {
String[] cols = new String[] { FOOD_NAME};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
public Cursor selectAllRecords(String loc) {
String[] cols = new String[] { FOOD_ID, FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION,FLAG,LOCATION,P_ID};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, LOCATION+"=?", new String[]{loc}, null, null, null, null);
int size=mCursor.getCount();
stringArray = new String[size];
int i=0;
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(1);
stringArray[i]=name;
String quant=mCursor.getString(2);
String measure=mCursor.getString(3);
String expir=mCursor.getString(4);
String id=mCursor.getString(7);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
fooditem.setid(id);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
i++;
}
}
return mCursor; // iterate to get each value.
}
public Cursor selectExpDate() {
String[] cols = new String[] {FOOD_NAME, FOOD_QUANTITY, FOOD_MEASUREMENT, FOOD_EXPIRATION};
Cursor mCursor = database.query(true, FOOD_TABLE, cols, null, null, null, null, FOOD_EXPIRATION, null);
int size=mCursor.getCount();
stringArray = new String[size];
if (mCursor != null) {
mCursor.moveToFirst();
FoodInfo.arrayList.clear();
while (!mCursor.isAfterLast()) {
String name=mCursor.getString(0);
String quant=mCursor.getString(1);
String measure=mCursor.getString(2);
String expir=mCursor.getString(3);
FoodInfo fooditem=new FoodInfo();
fooditem.setName(name);
fooditem.setQuantity(quant);
fooditem.setMesure(measure);
fooditem.setExpirationDate(expir);
FoodInfo.arrayList.add(fooditem);
mCursor.moveToNext();
}
}
return mCursor; // iterate to get each value.
}
public int UpdateFoodItem(String id, String quantity, String expiration){
ContentValues values=new ContentValues();
values.put(FOOD_QUANTITY, quantity);
values.put(FOOD_EXPIRATION, expiration);
return database.update(FOOD_TABLE, values, P_ID+"=?", new String[]{id});
}
public void deleteComment(String id) {
System.out.println("Comment deleted with id: " + id);
database.delete(FOOD_TABLE, P_ID+"=?", new String[]{id});
}
}
How's this for a one-liner?
List<string> result = new List<string>(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));
With this regex it doesn't matter if the last chunk is less than four characters, because it only ever looks at the characters behind it.
I'm sure this isn't the most efficient solution, but I just had to toss it out there.
The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.
I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.
=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))
This is the most simple method to generate unique random values in a range or from an array.
In this example, I will be using a predefined array but you can adapt this method to generate random numbers as well. First, we will create a sample array to retrieve our data from.
ArrayList<Integer> sampleList = new ArrayList<>();
sampleList.add(1);
sampleList.add(2);
sampleList.add(3);
sampleList.add(4);
sampleList.add(5);
sampleList.add(6);
sampleList.add(7);
sampleList.add(8);
Now from the sampleList
we will produce five random numbers that are unique.
int n;
randomList = new ArrayList<>();
for(int i=0;i<5;i++){
Random random = new Random();
n=random.nextInt(8); //Generate a random index between 0-7
if(!randomList.contains(sampleList.get(n)))
randomList.add(sampleList.get(n));
else
i--; //reiterating the step
}
This is conceptually very simple. If the random value generated already exists then we will reiterate the step. This will continue until all the values generated are unique.
If you found this answer useful then you can vote it up as it is much simple in concept as compared to the other answers.
Invoke-WebRequest can download HTTP, HTTPS, and FTP links.
$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password
# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing
Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.
If your class extends JFrame then use this.setTitle(newTitle.getText());
If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());
Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
newTitle;
and:
public void createOptions()
{
options = new JPanel();
options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
// myTitle = new JTextField("My Title...");
// myTitle.setBounds(80, 40, 225, 20);
// myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
and:
private void New_Name()
{
this.setTitle(newTitle.getText());
}
There is also array_pad. You can use it like this:
$data = array_pad($data,$number_of_items,0);
For initializing with zeros the $number_of_items positions of the array $data.
I solved this by clearing the jboss-x.y.z/server[config]/tmp and jboss-x.y.z/server/[config]/work directories.
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
You can use the parameter -f
(or --file
) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml
This runs maven "as if" it were in /path/to
for the working directory.
his example will tell you how to pass input value to parent on submit button.
First define eventBus as new Vue.
//main.js
import Vue from 'vue';
export const eventBus = new Vue();
Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
resetSegmentbtn: function(InputValue) {
eventBus.$emit("resetAllSegment", InputValue);
}
}
//Receiver Page
import { eventBus } from "../main";
created() {
eventBus.$on("resetAllSegment", data => {
console.log(data);//fetching data
});
}
You could simply use Runtime.exec()
I think, Maatkit utilits helps for you! You can use mk-table-sync. Please see this link: http://www.maatkit.org/doc/mk-table-sync.html
The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.
For example,
i >>= 2
produces the same result as
i = i >> 2
Main point you are looking for is:
.tag-remove::before {
content: 'x'; // here is your X(cross) sign.
color: #fff;
font-weight: 300;
font-family: Arial, sans-serif;
}
FYI, you can make a close button by yourself very easily:
#mdiv {_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
background-color: red;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.mdiv {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
margin-left: 12px;_x000D_
background-color: black;_x000D_
transform: rotate(45deg);_x000D_
Z-index: 1;_x000D_
}_x000D_
_x000D_
.md {_x000D_
height: 25px;_x000D_
width: 2px;_x000D_
background-color: black;_x000D_
transform: rotate(90deg);_x000D_
Z-index: 2;_x000D_
}
_x000D_
<div id="mdiv">_x000D_
<div class="mdiv">_x000D_
<div class="md"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Another possible solution with JS
function onSelect(e) {
if (e.files.length > 5) {
alert("Only 5 files accepted.");
e.preventDefault();
}
}
Of course, the accepted answer of Arrays.equal( byte[] first, byte[] second ) is correct. I like to work at a lower level, but I was unable to find a low level efficient function to perform equality test ranges. I had to whip up my own, if anyone needs it:
public static boolean ArraysAreEquals(
byte[] first,
int firstOffset,
int firstLength,
byte[] second,
int secondOffset,
int secondLength
) {
if( firstLength != secondLength ) {
return false;
}
for( int index = 0; index < firstLength; ++index ) {
if( first[firstOffset+index] != second[secondOffset+index]) {
return false;
}
}
return true;
}
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash
:
git reset HEAD^
to convert the entire cherry-picked commit into unstaged working changes.git stash save --patch
: interactively select unwanted material to stash.git commit
git stash drop
. Tip: if you give the stash of unwanted changes a name: git stash save --patch junk
then if you forget to do (6) now, later you will recognize the stash for what it is.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.
The second way if you're looking for a lighter approach is to have a .env file locally then run:
export $(cat .env)
This will work:
let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
I would like to add some precisions about using Proguard with Android Studio and gradle, since I had lots of problems to remove log lines from the final binary.
In order to make assumenosideeffects
in Proguard works, there is a prerequisite.
In your gradle file, you have to specify the usage of the proguard-android-optimize.txt
as default file.
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
// With the file below, it does not work!
//proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
Actually, in the default proguard-android.txt
file, optimization is disabled with the two flags:
-dontoptimize
-dontpreverify
The proguard-android-optimize.txt
file does not add those lines, so now assumenosideeffects
can work.
Then, personnally, I use SLF4J, all the more when I develop some libraries that are distributed to others. The advantage is that by default there is no output. And if the integrator wants some log outputs, he can uses Logback for Android and activate the logs, so logs can be redirected to a file or to LogCat.
If I really need to strip the logs from the final library, I then add to my Proguard file (after having enabled the proguard-android-optimize.txt
file of course):
-assumenosideeffects class * implements org.slf4j.Logger {
public *** trace(...);
public *** debug(...);
public *** info(...);
public *** warn(...);
public *** error(...);
}
To summarize, JSX doesn't support comments, either html-like or js-like:
<div>
/* This will be rendered as text */
// as well as this
<!-- While this will cause compilation failure -->
</div>
and the only way to add comments "in" JSX is actually to escape into JS and comment in there:
<div>
{/* This won't be rendered */}
{// just be sure that your closing bracket is out of comment
}
</div>
if you don't want to make some nonsense like
<div style={{display:'none'}}>
actually, there are other stupid ways to add "comments"
but cluttering your DOM is not a good idea
</div>
Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.
var form = $("<form/>",
{ action:'/myaction' }
);
form.append(
$("<input>",
{ type:'text',
placeholder:'Keywords',
name:'keyword',
style:'width:65%' }
)
);
form.append(
$("<input>",
{ type:'submit',
value:'Search',
style:'width:30%' }
)
);
$("#someDivId").append(form);
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
You can use readelf
to explore the ELF headers. readelf -d
will list the direct dependencies as NEEDED
sections.
$ readelf -d elfbin
Dynamic section at offset 0xe30 contains 22 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libssl.so.1.0.0]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000000c (INIT) 0x400520
0x000000000000000d (FINI) 0x400758
...
A new (but yet not released) tool is Mget. It has already many options known from Wget and comes with a library that allows you to easily embed (recursive) downloading into your own application.
To answer your question:
mget --num-threads=4 [url]
UPDATE
Mget is now developed as Wget2 with many bugs fixed and more features (e.g. HTTP/2 support).
--num-threads
is now --max-threads
.
For all smartphones and large screens use this format of media query
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}
/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
In Visual Studio 2019, You can open Command/PowerShell window from Tools > Command Line >
If you want an integrated terminal, try
BuiltinCmd: https://marketplace.visualstudio.com/items?itemName=lkytal.BuiltinCmd
You can also try WhackWhackTerminal (does not support VS 2019 by this date).
https://marketplace.visualstudio.com/items?itemName=dos-cafe.WhackWhackTerminal
Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI()
and ContentResolver.openInputStream()
allow you to access the contents of a file without knowing its real path.
1.First run your Application 2.Go to Tool-->Android-->Android Device Monitor
(1)
ArrayList<Object> list = new ArrayList <>();`
list.add("ddd");
list.add(2);
list.add(11122.33);
System.out.println(list);
(2)
ArrayList arraylist = new ArrayList();
arraylist.add(5);
arraylist.add("saman");
arraylist.add(4.3);
System.out.println(arraylist);
Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
Not looking for rep--I just researched this question myself and thought I'd share.
Here is my attempt.
List<object> list = new List<object> { new { Id = 10, Name = "Testing1" }, new {Id =2, Name ="Testing2" }};
I came up with this when I wrote something similar for making a Anonymous List for a custom type.
Percent encoding. Replace the hash with %23
.
Try this. You can just use built-in ThresholdFilter
and LevelFilter
. No need to create your own filters programmically. In this example WARN and ERROR levels are logged to System.err and rest to System.out:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny ERROR level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
</filter>
<!-- deny WARN level -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>DENY</onMatch>
</filter>
<target>System.out</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
<!-- deny all events with a level below WARN, that is INFO, DEBUG and TRACE -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<target>System.err</target>
<immediateFlush>true</immediateFlush>
<encoder>
<charset>utf-8</charset>
<pattern>${msg_pattern}</pattern>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="stderr"/>
</root>
<root level="TRACE">
<appender-ref ref="stdout"/>
</root>
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);
Deployment descriptor file "web.xml" : Through the proper use of the deployment descriptor file, web.xml, you can control many aspects of the Web application behavior, from preloading servlets, to restricting resource access, to controlling session time-outs.
web.xml : is used to control many facets of a Web application. Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on.
I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.
When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?
In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.
So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.
And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.
GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.
One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.
git diff > git-dif-file.diff
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
I got this error when my service declaration was inside a non-invoked function (IIFE). The last line below did NOT have the extra () to run and define the service.
(function() {
"use strict";
angular.module("reviewService", [])
.service("reviewService", reviewService);
function reviewService($http, $q, $log) {
//
}
}());
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown