If you are using Turbolinks With Rails this is my solution:
This is the CoffeeScript
$(window).on 'page:fetch', ->
$('body').append("<div class='modal'></div>")
$('body').addClass("loading")
$(window).on 'page:change', ->
$('body').removeClass("loading")
This is the SASS CSS based on the first excellent answer from Jonathan Sampson
# loader.css.scss
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, 0.4)
asset-url('ajax-loader.gif', image)
50% 50%
no-repeat;
}
body.loading {
overflow: hidden;
}
body.loading .modal {
display: block;
}
You can just read from a file, jsonifying
each line as you go:
tweets = []
for line in open('tweets.json', 'r'):
tweets.append(json.loads(line))
This avoids storing intermediate python objects. As long as your write one full tweet per append()
call, this should work.
You may also want to add
table td { border:0; }
the above is equivalent to setting cellpadding="0"
it gets rid of the padding automatically added to cells by browsers which may depend on doctype and/or any CSS used to reset default browser styles
The trick is that you need to create an environment/workspace for Python. This solution should work for Python 2.7 but at the time of writing keras can run on python 3.5, especially if you have the latest anaconda installed (this took me awhile to figure out so I'll outline the steps I took to install KERAS in python 3.5):
Create environment/workspace for Python 3.5
C:\conda create --name neuralnets python=3.5
C:\activate neuralnets
Install everything (notice the neuralnets workspace in parenthesis on each line). Accept any dependencies each of those steps wants to install:
(neuralnets) C:\conda install theano
(neuralnets) C:\conda install mingw libpython
(neuralnets) C:\pip install tensorflow
(neuralnets) C:\pip install keras
Test it out:
(neuralnets) C:\python -c "from keras import backend; print(backend._BACKEND)"
Just remember, if you want to work in the workspace you always have to do:
C:\activate neuralnets
so you can launch Jupyter for example (assuming you also have Jupyter installed in this environment/workspace) as:
C:\activate neuralnets
(neuralnets) jupyter notebook
You can read more about managing and creating conda environments/workspaces at the follwing URL: https://conda.io/docs/using/envs.html
This is defined in PEP8 here:
Global Variable Names
(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.
Modules that are designed for use via
from M import *
should use the__all__
mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").
PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.
Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:
.g-recaptcha-outer{
text-align: center;
border-radius: 2px;
background: #f9f9f9;
border-style: solid;
border-color: #37474f;
border-width: 1px;
border-bottom-width: 2px;
}
.g-recaptcha-inner{
width: 154px;
height: 82px;
overflow: hidden;
margin: 0 auto;
}
.g-recaptcha{
position:relative;
left: -2px;
top: -1px;
}
<div class="g-recaptcha-outer">
<div class="g-recaptcha-inner">
<div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
</div>
</div>
An easily broken way to do this is :
<?php
// Send the headers
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
// echo some dynamically generated content here
/*
<track>
<path>song_path</path>
<title>track_number - track_title</title>
</track>
*/
echo '</xml>';
?>
save it as .php
Try this code
SELECT REPLACE([Column], char(9), '') From [dbo.Table]
char(9) is the TAB character
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
using
class httplib.HTTPSConnection
http://docs.python.org/library/httplib.html#httplib.HTTPSConnection
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
not a good way but kind of quick fix, take a bool to check if in whole list there is any duplicate entry.
bool containsKey;
string newKey;
public void addKey(string newKey)
{
foreach (string key in MyKeys)
{
if (key == newKey)
{
containsKey = true;
}
}
if (!containsKey)
{
MyKeys.add(newKey);
}
else
{
containsKey = false;
}
}
First create dir /var/run/mysqld
with command:
mkdir -p /var/run/mysqld
then add rigths to the dir
chown mysql:mysql /var/run/mysqld
after this try
mysql -u root
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
You can Use this for Curl:
function fakeip()
{
return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );
}
function getdata($url,$args=false)
{
global $session;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip()));
if($args)
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then To Read Json:
$result=getdata("https://example.com");
Then :
///Deocde Json
$data = json_decode($result,true);
///Count
$total=count($data);
$Str='<h1>Total : '.$total.'';
echo $Str;
//You Can Also Make In Table:
foreach ($data as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
}
You Can Also Use This:
echo '<p>Name : '.$data['result']['name'].'</p>
<img src="'.$data['result']['pic'].'"><br>';
Hope this helped.
This is a class I use to create Message Digest hashes
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Sha1Hex {
public String makeSHA1Hash(String input)
throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
byte[] buffer = input.getBytes("UTF-8");
md.update(buffer);
byte[] digest = md.digest();
String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr += Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return hexStr;
}
}
Try deleting the .jenkins folder from your system which is located ate the below path. C:\Users\"Your PC Name".jenkins
Now download a fresh and a stable version of .war file from official website of jenkins. For eg. 2.1 and follow the steps to install.
There should be no single quotes here . Single quotes are for string literals: 'A'
'some value'
.
Either use double quotes to preserve the upper case spelling of "A":
CREATE TABLE "A" ...
Or don't use quotes at all:
CREATE TABLE A ...
which is identical to
CREATE TABLE a ...
because all unquoted identifiers are folded to lower case automatically in PostgreSQL.
You could avoid problems with the index name completely by using simpler syntax:
CREATE TABLE csd_relationship (
csd_relationship_id serial PRIMARY KEY,
type_id integer NOT NULL,
object_id integer NOT NULL
);
Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.
You should never apply bindings more than once to a view. In 2.2, the behaviour was undefined, but still unsupported. In 2.3, it now correctly shows an error. When using knockout, the goal is to apply bindings once to your view(s) on the page, then use changes to observables on your viewmodel to change the appearance and behaviour of your view(s) on your page.
Rails 4 (other Rails 4 answers have problems):
def change
change_column_null(:users, :admin, false, <put a default value here> )
# change_column(:users, :admin, :string, :default => "")
end
Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null
does exactly that. See documentation for more details.
Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.
And the jquery version:
$('input').attr('required', true)
$('input').attr('required', false)
I know it's beyond the question, but maybe someone will find this helpful :)
Set specific tab index as active:
$(this).tabs({ active: # }); /* Where # is the tab index. The index count starts at 0 */
Set last tab as active
$(this).tabs({ active: -1 });
Set specific tab by ID:
$(this).tabs({ active: $('a[href="#tab-101"]').parent().index() });
The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.
If you don't like the version with the anonymous type for some specific reason, you should explain that reason.
If you want to do something other than what you originally asked for, please give an example of what you really want to do.
EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.
Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where
clause (after a second from
clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.
Select in :
Microsoft SQL Server (SqlClient)
(localdb)\MSSQLLocalDB
Use Windows Authentication
Press Refresh button to get the database name :)
Call the code with two float
values, the code works in any range.
float rand_FloatRange(float a, float b)
{
return ((b - a) * ((float)rand() / RAND_MAX)) + a;
}
You can also use let data = String(decoding: myStr, as: UTF8.self)
here is a resource about converting data to string
$('#checkbox').click(function(){ $('#submit').attr('disabled', !$(this).attr('checked')); });
It's the destructor. This method is called when the instance of your class is destroyed:
Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;
I had this problem just now and managed to figure out what it was. Was referencing a colour in my values that was causing problems. So defined it manually instead of using one from the dropdown suggestions.Then it worked!
You can now do this with Lambda@Edge to rewrite the paths
Here is a working lambda@Edge function:
'use strict';
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event that is sent to Lambda@Edge
var request = event.Records[0].cf.request;
// Extract the URI from the request
var olduri = request.uri;
// Match any '/' that occurs at the end of a URI. Replace it with a default index
var newuri = olduri.replace(/\/$/, '\/index.html');
// Log the URI as received by CloudFront and the new URI to be used to fetch from origin
console.log("Old URI: " + olduri);
console.log("New URI: " + newuri);
// Replace the received URI with the URI that includes the index page
request.uri = newuri;
return callback(null, request);
};
In your cloudfront behaviors, you'll edit them to add a call to that lambda function on "Viewer Request"
Try: Controls("Check Box 1") = True
Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain()
.
If it says Subsystem Windows
your entry point should be WinMain(), i.e.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
your code here ...
}
Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.
It does not even get to the point being loaded and run.
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
Using WifiManager
you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
Use re.escape
>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com
Repeating it here:
re.escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
As of Python 3.7 re.escape()
was changed to escape only characters which are meaningful to regex operations.
Instead of
css=#container
use
css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)
Update:
It seems there's a new API to check just that. See another answer in this page: https://stackoverflow.com/a/36653034/435605
Original post:
Use errorCode.equals("NoSuchKey")
try {
AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
String bucketName = getBucketName();
s3.createBucket(bucketName);
S3Object object = s3.getObject(bucketName, getKey());
} catch (AmazonServiceException e) {
String errorCode = e.getErrorCode();
if (!errorCode.equals("NoSuchKey")) {
throw e;
}
Logger.getLogger(getClass()).debug("No such key!!!", e);
}
Note about the exception: I know exceptions should not be used for flow control. The problem is that Amazon didn't provide any api to check this flow - just documentation about the exception.
As James Selvakumar already said, grep -a
does the trick. -a or --text forces Grep to handle the inputstream as text.
See Manpage http://unixhelp.ed.ac.uk/CGI/man-cgi?grep
try
cat test.log | grep -a somestring
I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i)
but to return x[length(x) - i + 1]
and not the whole tail.
Following commentaries I benchmarked two solutions:
accessRevTail <- function(x, n) {
tail(x,n)[1]
}
accessRevLen <- function(x, n) {
x[length(x) - n + 1]
}
microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
expr min lq mean median uq max neval
accessRevLen(1:100, 87) 1.860 2.3775 2.84976 2.803 3.2740 6.755 100
accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833 100
So it appears in this case that even for small vectors, tail
is very slow comparing to direct access
If source file not found xcopy returns error code 4 also.
Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.
This solution will work an any Document, not just a PlainDocument.
This is a more current solution than the one accepted.
Easiest solution:
kill $(lsof -ti:3000,3001,8080)
For single port:
kill $(lsof -ti:3000)
#3000 is the port to be freed
Kill multiple ports with single line command:
kill $(lsof -ti:3000,3001)
#here multiple ports 3000 and 3001 are the ports to be freed
lsof -ti:3000
82500 (Process ID)
lsof -ti:3001
82499
lsof -ti:3001,3000
82499 82500
kill $(lsof -ti:3001,3000)
Terminates both 82499 and 82500 processes in a single command.
For using this in package.json
scripts:
"scripts": { "start": "kill $(lsof -ti:3000,3001) && npm start" }
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
From the Documentation
As with components, you can add as many directive property bindings as you need by stringing them along in the template.
Add an input property to
HighlightDirective
calleddefaultColor
:@Input() defaultColor: string;
Markup
<p [myHighlight]="color" defaultColor="violet"> Highlight me too! </p>
Angular knows that the
defaultColor
binding belongs to theHighlightDirective
because you made it public with the@Input
decorator.Either way, the
@Input
decorator tells Angular that this property is public and available for binding by a parent component. Without@Input
, Angular refuses to bind to the property.
For your example
With many parameters
Add properties into the Directive
class with @Input()
decorator
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('first') f;
@Input('second') s;
...
}
And in the template pass bound properties to your li
element
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[first]='YourParameterHere'
[second]='YourParameterHere'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
Here on the li
element we have a directive with name selectable
. In the selectable
we have two @Input()
's, f
with name first
and s
with name second
. We have applied these two on the li
properties with name [first]
and [second]
. And our directive will find these properties on that li
element, which are set for him with @Input()
decorator. So selectable
, [first]
and [second]
will be bound to every directive on li
, which has property with these names.
With single parameter
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('params') params;
...
}
Markup
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
(selectedOption) = 'onOptionSelection($event)'>
{{opt.option}}
</li>
I have use below code to encode the special character by specifying encode format.
String text = "This is an example é";
byte[] byteText = text.getBytes(Charset.forName("UTF-8"));
//To get original string from byte.
String originalString= new String(byteText , "UTF-8");
You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""
In Oracle, a ‘like’ with no wildcards will return the same result as an ‘equals’, but could require additional processing. According to Tom Kyte, Oracle will treat a ‘like’ with no wildcards as an ‘equals’ when using literals, but not when using bind variables.
You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a
.
To remove go to the subdirectory and rm .git -rf
.
You can use the string.Join
method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...)
.
edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.
Profiling code (of course run in release without debug symbols):
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
string r;
int iter = 10000;
string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };
sw.Restart();
for (int i = 0; i < iter; i++)
r = Program.StringJoin(",", values);
sw.Stop();
Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < iter; i++)
r = Program.StringBuilderAppend(",", values);
sw.Stop();
Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
Console.ReadLine();
}
static string StringJoin(string seperator, params string[] values)
{
return string.Join(seperator, values);
}
static string StringBuilderAppend(string seperator, params string[] values)
{
StringBuilder builder = new StringBuilder();
builder.Append(values[0]);
for (int i = 1; i < values.Length; i++)
{
builder.Append(seperator);
builder.Append(values[i]);
}
return builder.ToString();
}
}
string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.
As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch
instead of []
. For fetch
not to throw an exception when the key is not found, pass it a default value.
puts "ok" if hash.fetch('key', nil) == 'X'
Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .
You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:
Try:
scala> val list = for(i <- 1 to 10) yield i
list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
You probably don't even need to convert to a list in most cases :)
The indexed seq will have everything you need:
That is, you can now work on that IndexedSeq:
scala> list.foldLeft(0)(_+_)
res0: Int = 55
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.
Use html instead of append:
$.get("banner.html", function(data){
$(this).children("div:first").html(data);
});
Why not simply check for dict.keys.contains(key)
?
Checking for dict[key] != nil
will not work in cases where the value is nil.
As with a dictionary [String: String?]
for example.
From the jinja docs section HTML Escaping:
When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.
Example:
<div class="info">
{{data.email_content|safe}}
</div>
Try something like:
Add to html:
<link id="shortcutIcon" rel="shortcut icon" type="image/x-icon">
<link id="icon" rel="icon" type="image/x-icon">
Add minified script after tag:
<script type="text/javascript">
(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));
</script>
where
Before test clear history: (ctr + shfit + del)
If you only need to know which one is bigger, you can also compare them directly:
var SpecialToDate = '31/01/2014'; // DD/MM/YYYY
var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
alert('date is today or in future');
} else {
alert('date is in the past');
}
Hope this helps!
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
<select ng-model="option" ng-options="o for o in options">
$scope.option will be equal to 'var1' after change, even you see value="0" in generated html
if you come across this error when you try running PyTorch related libraries you may have to consider installing PyTorch with CPU only version i.e. if you don't have Nvidia GPU in your system.
Pytorch with CUDA worked in Nvidia installed systems but not in others.
You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.
simply add to your data structure ( mItems ) , and then notify your adapter about dataset change
private void addItem(String item) {
mItems.add(item);
mAdapter.notifyDataSetChanged();
}
addItem("New Item");
Im extracting my comment to this answer:
ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'
It bases on @CollinAnderson answer which didn't work in my case.
Select Preferences -> Workspace Settings and add the following code, If you have Hot reload enabled, then the changes reflect immediately in the browser
{
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js.map": true,
"**/*.js": {"when": "$(basename).ts"}
},
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000
}
I agree with everything that is said already, just trying to put some other words on it.
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called".
Typical use is of course events. All the OnEventX delegate to the methods the user defines.
Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.
From iOS 6.0 and above, toggling torch flash on/off,
- (void) toggleFlash {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setFlashMode:(device.flashActive) ? AVCaptureFlashModeOff : AVCaptureFlashModeOn];
[device setTorchMode:(device.torchActive) ? AVCaptureTorchModeOff : AVCaptureTorchModeOn];
[device unlockForConfiguration];
}
}
P.S. This approach is only suggestible if you don't have on/off function. Remember there's one more option Auto
. i.e. AVCaptureFlashModeAuto
and AVCaptureTorchModeAuto
. To support auto mode as well, you've keep track of current mode and based on that change mode of flash & torch.
If you want to combine this with *args you have to keep *args and **kwargs at the end of the definition.
So:
def method(foo, bar=None, *args, **kwargs):
do_something_with(foo, bar)
some_other_function(*args, **kwargs)
Disable Nvidia's nView Desktop Manager and the problem should resolve.
I was trying to implement pandas append functionality in pyspark and what I created a custom function where we can concat 2 or more data frame even they are having different no. of columns only condition is if dataframes have identical name then their datatype should be same/match.
I have written a custom function to merge 2 dataframes.
def append_dfs(df1,df2):
list1 = df1.columns
list2 = df2.columns
for col in list2:
if(col not in list1):
df1 = df1.withColumn(col, F.lit(None))
for col in list1:
if(col not in list2):
df2 = df2.withColumn(col, F.lit(None))
return df1.unionByName(df2)
concate 2 dataframes
final_df = append_dfs(df1,df2)
final_df = append_dfs(append_dfs(df1,df2),df3)
result=append_dfs(df1,df2)
Hope this will useful.
You'll have to do this in two steps:
If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:
mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile
You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ...
.
Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:
<dependencies>
...
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
...
</dependencies>
For those who may concern. Based on Sevastyan's answer, should you want to make it horizontal scroll.
Simply change all getBottom()
to getRight()
and getTop()
to getLeft()
To fit image in fullscreen try this:
background-repeat: round;
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
You could simply do the following.
Let's say you have the JavaScript file named myscript.js
in your root folder. Add the reference to your javascript source file in your head tag of your html file.
<script src="~/myscript.js"></script>
JS file: (myscript.js
)
function awesomeClick(){
alert('awesome click triggered');
}
HTML
<button type="button" id="jstrigger" onclick="javascript:awesomeClick();">Submit</button>
I believe you want to set the Content
property. This has more information on what is available to a label.
Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.
I have actually found the proper solution and posted it under almost the same question here. For more details head there.
Solution:
# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo
No one mentioned this, but in conjunction to the other responses, you can also get the apk file from your bin directory to your phone or tablet by putting it on a web site and just downloading it.
Your device will complain about installing it after you download it. Your device will advise you or a risk of installing programs from unknown sources and give you the option to bypass the advice.
Your question is very specific. You don't have to pull it from your emulator, just grab the apk file from the bin folder in your project and place it on your real device.
Most people are giving you valuable information for the next step (signing and publishing your apk), you are not required to do that step to get it on your real device.
Downloading it to your real device is a simple method.
The trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent.
But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs. Conventionally, a trailing slash (/) at the end of a URL meant that the URL was a folder or directory.
A URL without a trailing slash at the end used to mean that the URL was a file.
Try this query:
SELECT *
FROM table
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
Try
$("#link1").text()
to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
<html>
<style>
.selectBox{
color:White;
}
.optionBox{
color:black;
}
</style>
<body>
<select class = "selectBox">
<option class = "optionBox">One</option>
<option class = "optionBox">Two</option>
<option class = "optionBox">Three</option>
</select>
this works for me every time try this.
echo "<font color='blue'>".$myvariable."</font>";
since font is not supported in html5 you can do this
echo "<p class="variablecolor">".$myvariable."</p>";
then in css do
.variablecolor{
color: blue;}
If you want to do it with multiline/multiple command/s then you can do this:
output=$( bash <<EOF
#multiline/multiple command/s
EOF
)
Or:
output=$(
#multiline/multiple command/s
)
Example:
#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"
Output:
first
second
third
For your information, the python equivalent is:
imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )
%(letter) denotes the format type of the replacement text. %s specifies a string, %d an integer, and %c a char.
You haven't reserved enough space in your vector object to hold the contents of your set.
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
In Python 3.4 pathlib was introduced:
>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')
It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.
For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.
We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext
.
In a standalone application, you can specify that as below
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");
Context ctx = new InitialContext(env);
But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext
as below
System.getProperty(Context.PROVIDER_URL);
and
these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work
InitialContext ctx = new InitialContext();
UPDATED for Swift 4: (credit to Marco Weber)
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.shared.openURL(requestUrl as URL)
}
OR go with more of swift style using guard
:
guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
return
}
UIApplication.shared.openURL(requestUrl as URL)
Swift 3:
You can check NSURL as optional implicitly by:
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.sharedApplication().openURL(requestUrl)
}
You can also use the following trick:
y.x = "some custom property"//gives typescript error
y["x"] = "some custom property"//no errors
Note, that to access x
and dont get a typescript error again you need to write it like that y["x"]
, not y.x
. So from this perspective the other options are better.
A recursive function is a function that calls itself
If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.
What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.
function fact($n) {
if ($n === 0) { // our base case
return 1;
}
else {
return $n * fact($n-1); // <--calling itself.
}
}
In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.
Although I cannot compete with the directory example, I hope this helps somewhat.
It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,
Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):
To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:
int SizeTToInt(size_t data)
{
if (data > std::numeric_limits<int>::max())
throw std::exception("Invalid cast.");
return std::static_cast<int>(data);
}
If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):
template<class Target, class Source>
Target NarrowCast(Source v)
{
auto r = static_cast<Target>(v);
if (static_cast<Source>(r) != v)
throw RuntimeError("Narrow cast failed.");
return r;
}
I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);
where
constexpr size_t IntegerRepresentableBoundary()
{
static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
return size_t{2} << (std::numeric_limits<double>::digits - 1);
}
That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.
Let's say you have a shiny Foo class. Well you have 3 options:
1) You want to use the method (or attribute) of a class inside the definition of that class:
class Foo(object):
attribute1 = 1 # class attribute (those don't use 'self' in declaration)
def __init__(self):
self.attribute2 = 2 # instance attribute (those are accessible via first
# parameter of the method, usually called 'self'
# which will contain nothing but the instance itself)
def set_attribute3(self, value):
self.attribute3 = value
def sum_1and2(self):
return self.attribute1 + self.attribute2
2) You want to use the method (or attribute) of a class outside the definition of that class
def get_legendary_attribute1():
return Foo.attribute1
def get_legendary_attribute2():
return Foo.attribute2
def get_legendary_attribute1_from(cls):
return cls.attribute1
get_legendary_attribute1() # >>> 1
get_legendary_attribute2() # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo) # >>> 1
3) You want to use the method (or attribute) of an instantiated class:
f = Foo()
f.attribute1 # >>> 1
f.attribute2 # >>> 2
f.attribute3 # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3 # >>> 3
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
You can also try this, after injecting $window service.
$window.location.reload();
No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars.
There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take []
as an example. Whenever there is an [
there must be a matching ]
, which is simple enough for a regex "\[.*\]"
.
What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets.
This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count.
I ended up writing "Regular Expression Limitations" about this.
Not directly. But you can use extensions such as LESS to help you achieve the same.
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
if you want to compute differences between two known dates, use total_seconds
like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0
#note that seconds doesn't give you what you want:
(b-a).seconds
0
Is numeric can be achieved via many ways, but i use my way
public bool IsNumeric(string value)
{
bool isNumeric = true;
char[] digits = "0123456789".ToCharArray();
char[] letters = value.ToCharArray();
for (int k = 0; k < letters.Length; k++)
{
for (int i = 0; i < digits.Length; i++)
{
if (letters[k] != digits[i])
{
isNumeric = false;
break;
}
}
}
return isNumeric;
}
Here is what worked for me. Javascript has this.
<script type="text/javascript">
var deptname = '';
</script>
C# Code behind has this - it could be put on the master page so it reset var on ever page change.
String csname1 = "LoadScript";
Type cstype = p.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = p.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = funct;
cs.RegisterStartupScript(cstype, csname1, "deptname = 'accounting'", true);
}
else
{
String cstext = funct;
cs.RegisterClientScriptBlock(cstype, csname1, "deptname ='accounting'",true);
}
Add this code to a button click to confirm deptname changed.
alert(deptname);
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
I do this quite often on results returned from a query..
e.g.
// $MyQueryResult is an array of results from a query
foreach ($MyQueryResult as $key=>$value)
{
${$key}=$value;
}
Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']
Yep, it's probably lazy, but I've never had any problems.
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
viewport
meta tag on mobile browser,
The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
I tried @Mr. Stark answer. It didn't work. It failed to install the drive. I have Samsung S8 plus. I enabled the debugging mode on device then installed Android USB Driver for Windows from Samsung site, it works.
You are using the wrong format tokens when parsing your input. You should use ddd
for an abbreviation of the name of day of the week, DD
for day of the month, MMM
for an abbreviation of the month's name, YYYY
for the year, hh
for the 1-12
hour, mm
for minutes and A
for AM/PM
. See moment(String, String)
docs.
Here is a working live sample:
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {
new = xx.value;
alert(new); }}
To insert/append to a dictionary
{"0": {"travelkey":"value", "travelkey2":"value"},"1":{"travelkey":"value","travelkey2":"value"}}
travel_dict={} #initialize dicitionary
travel_key=0 #initialize counter
if travel_key not in travel_dict: #for avoiding keyerror 0
travel_dict[travel_key] = {}
travel_temp={val['key']:'no flexible'}
travel_dict[travel_key].update(travel_temp) # Updates if val['key'] exists, else adds val['key']
travel_key=travel_key+1
I inspired myself from @maxisam's answer and created my own sort function and I'd though I'd share it (cuz I'm bored).
Situation
I want to filter through an array of cars. The selected properties to filter are name, year, price and km. The property price and km are numbers (hence the use of .toString
). I also want to control for uppercase letters (hence .toLowerCase
). Also I want to be able to split up my filter query into different words (e.g. given the filter 2006 Acura, it finds matches 2006 with the year and Acura with the name).
Function I pass to filter
var attrs = [car.name.toLowerCase(), car.year, car.price.toString(), car.km.toString()],
filters = $scope.tableOpts.filter.toLowerCase().split(' '),
isStringInArray = function (string, array){
for (var j=0;j<array.length;j++){
if (array[j].indexOf(string)!==-1){return true;}
}
return false;
};
for (var i=0;i<filters.length;i++){
if (!isStringInArray(filters[i], attrs)){return false;}
}
return true;
};
I believe this has been answered in some sections already, just test with gmail for your "MAIL_HOST" instead and don't forget to clear cache. Setup like below: Firstly, you need to setup 2 step verification here google security. An App Password link will appear and you can get your App Password to insert into below "MAIL_PASSWORD". More info on getting App Password here
MAIL_DRIVER=smtp
[email protected]
MAIL_FROM_NAME=DomainName
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=YOUR_GMAIL_CREATED_APP_PASSWORD
MAIL_ENCRYPTION=tls
Clear cache with:
php artisan config:cache
With oracle 10.2g:
select level, sequence.NEXTVAL
from dual
connect by level <= (select max(pk) from tbl);
will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.
isset()
function does not check if a variable is defined.It seems you've specifically stated that you're not looking for isset()
in the question. I don't know why there are so many answers stating that isset()
is the way to go, or why the accepted answer states that as well.
It's important to realize in programming that null is something. I don't know why it was decided that isset()
would return false if the value is null.
To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars()
. There is no equivalent to JavaScript's undefined (which is what was shown in the question, no jQuery being used there).
In the following example it will work the same way as JavaScript's undefined check.
$isset = isset($variable);
var_dump($isset); // false
But in this example, it won't work like JavaScript's undefined check.
$variable = null;
$isset = isset($variable);
var_dump($isset); // false
$variable
is being defined as null, but the isset()
call still fails.
Using get_defined_vars()
will return an associative array with keys as variable names and values as the variable values. We still can't use isset(get_defined_vars()['variable'])
here because the key could exist and the value still be null, so we have to use array_key_exists('variable', get_defined_vars())
.
$variable = null;
$isset = array_key_exists('variable', get_defined_vars());
var_dump($isset); // true
$isset = array_key_exists('otherVariable', get_defined_vars());
var_dump($isset); // false
However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my personal belief as to why the core PHP developers left isset()
to return false when something is null.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
the problem is blade, try this
<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>
You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
//o_O\\ (Poker Face) i know its late
just add beloww css style
<style type="text/css">
/* Vertical Tabs ----------------------------------*/
.ui-tabs-vertical { width: 55em; }
.ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
.ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
.ui-tabs-vertical .ui-tabs-nav li a { display:block; }
.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
.ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}
</style>
UPDATED ! http://jqueryui.com/tabs/#vertical
It seems as of now, the only solution is still to install SublimeREPL.
To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:
To enable it, go to Preferences->Key Bindings - User, and copy this in there:
[
{"keys":["ctrl+r"] ,
"caption": "SublimeREPL: Python - RUN current file",
"command": "run_existing_window_command",
"args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
},
]
Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.
And for completeness (primarily educational), it is possible without using the len()
function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.
def count(list):
item_count = 0
for item in list[:]:
item_count += 1
return item_count
count([1,2,3,4,5])
(The colon in list[:]
is implicit and is therefore also optional.)
The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.
Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:
class MyList(object):
def __init__(self):
self._data = []
self.length = 0 # length tracker that takes up memory but makes length op O(1) time
# the implicit iterator in a list class
def __iter__(self):
for elem in self._data:
yield elem
def add(self, elem):
self._data.append(elem)
self.length += 1
def remove(self, elem):
self._data.remove(elem)
self.length -= 1
mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2
// Define appendVal by extending JQuery_x000D_
$.fn.appendVal = function( TextToAppend ) {_x000D_
return $(this).val(_x000D_
$(this).val() + TextToAppend_x000D_
);_x000D_
};_x000D_
//______________________________________________x000D_
_x000D_
// And that's how to use it:_x000D_
$('#SomeID')_x000D_
.appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
id = "SomeID"_x000D_
value = "ValueText"_x000D_
type = "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
</form>
_x000D_
Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val()
supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.
However the point for now is:
When working with form data use .val().
When dealing with the mostly read only data in between the tag use .text() or .append() to append text.
You can also try this
LinkedListNode pointer = head;
LinkedListNode prev = null, curr = null;
/* Pointer variable loops through the LL */
while(pointer != null)
{
/* Proceed the pointer variable. Before that, store the current pointer. */
curr = pointer; //
pointer = pointer.next;
/* Reverse the link */
curr.next = prev;
/* Current becomes previous for the next iteration */
prev = curr;
}
System.out.println(prev.printForward());
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
Consider also using SETX
- it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET
:
::setting variable for the current user
if not defined My_Var (
set "My_Var=My_Value"
setx My_Var My_Value
)
::setting machine defined variable
if not defined Global_Var (
set "Global_Var=Global_Value"
SetX Global_Var Global_Value /m
)
You can also edit directly the registry values:
User Variables: HKEY_CURRENT_USER\Environment
System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
Which will allow to avoid some restrictions of SET and SETX like the variables containing =
in their names.
By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);
It helps avoid having to write code like this:
[if ($this->uri->segment(3) === FALSE)
{
$product_id = 0;
}
else
{
$product_id = $this->uri->segment(3);
}]
CAUTION: ONLY FOR WINDOWS
I came across this problem today and all the answers mentioned here helped me, but I personally had to dig a lot to solve it. So let me help all others by putting out the solution to it in a very simple form:
Download the executable 64 bit (32-bit if your computer is of 32 bit) exe from here.
(Name of the file would be tesseract-ocr-w64-setup-v5.0.0.20190526 (alpha))
Install it. Let it install itself in the default C directory.
Now go to your Environment variable (Reach there by just searching it in the start menu or Go to Control Panel > System > Advanced System Settings > Environment Variables
)
a) Select PATH and then Edit it. Click on NEW and add the path where it is installed (Usually C:\Program Files\Tesseract-OCR\
)
Now you will not get the error!
You should explore SQL Server\Memory Manager performance counters.
For correlations you can just use the corr function (statistics toolbox)
corr(A_1(:), A_2(:))
Note that you can also just use
corr(A_1, A_2)
But the linear indexing guarantees that your vectors don't need to be transposed.
The accepted answer calls the draw
function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:
datatable.clear().rows.add(newData).draw();
Since the project is on a shared drive as the original poster have indicated. VS.NET needs to trust network location before it will load and run your test assemblies. Have a read of this blog post.
To allow VS.NET to load things of a network share one needs to add them (shares) to trusted locations. To add a location to a full trust list run (obviously amend as required for you environment):
caspol -m -ag 1.2 -url file:///H:/* FullTrust
To verify or list existing trusted locations run:
caspol -lg
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
Check if you mixed tabs and spaces, that is a frequent source of indentation errors.
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'}, function(response) {
console.log(response);
});//
The command line flags -N
or --LINE-NUMBERS
causes a line number to be displayed at the beginning of each line in the display.
You can also toggle line numbers without quitting less
by typing -N<return>
. It it possible to toggle any of less
's command line options in this way.
E.g. by naming the fields like
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
(which is also possible when adding elements via javascript)
The corresponding php script might look like
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);
<form role="form">
<div class="form-group">
<div class="col-xs-2">
<label for="ex1">col-xs-2</label>
<input class="form-control" id="ex1" type="text">
</div>
<div class="col-xs-3">
<label for="ex2">col-xs-3</label>
<input class="form-control" id="ex2" type="text">
</div>
<div class="col-xs-4">
<label for="ex3">col-xs-4</label>
<input class="form-control" id="ex3" type="text">
</div>
</div>
</form>
Cross-browser rotate for any element. Works in IE7 and IE8. In IE7 it looks like not working in JSFiddle but in my project worked also in IE7
var elementToRotate = $('#rotateMe');
var degreeOfRotation = 33;
var deg = degreeOfRotation;
var deg2radians = Math.PI * 2 / 360;
var rad = deg * deg2radians ;
var costheta = Math.cos(rad);
var sintheta = Math.sin(rad);
var m11 = costheta;
var m12 = -sintheta;
var m21 = sintheta;
var m22 = costheta;
var matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
Edit 13/09/13 15:00 Wrapped in a nice and easy, chainable, jquery plugin.
Example of use
$.fn.rotateElement = function(angle) {
var elementToRotate = this,
deg = angle,
deg2radians = Math.PI * 2 / 360,
rad = deg * deg2radians ,
costheta = Math.cos(rad),
sintheta = Math.sin(rad),
m11 = costheta,
m12 = -sintheta,
m21 = sintheta,
m22 = costheta,
matrixValues = 'M11=' + m11 + ', M12='+ m12 +', M21='+ m21 +', M22='+ m22;
elementToRotate.css('-webkit-transform','rotate('+deg+'deg)')
.css('-moz-transform','rotate('+deg+'deg)')
.css('-ms-transform','rotate('+deg+'deg)')
.css('transform','rotate('+deg+'deg)')
.css('filter', 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')')
.css('-ms-filter', 'progid:DXImageTransform.Microsoft.Matrix(SizingMethod=\'auto expand\','+matrixValues+')');
return elementToRotate;
}
$element.rotateElement(15);
JSFiddle: http://jsfiddle.net/RgX86/175/
try this, this works for me, I forgot where I found it, somewhere in stack overflow, i'm not here to explained it why it doesn't work, but this is the answer :).
final ListView AturIsiPulsaDataIsiPulsa = (ListView) findViewById(R.id.listAturIsiPulsaDataIsiPulsa);
AturIsiPulsaDataIsiPulsa.setOnTouchListener(new ListView.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
int action = event.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
AturIsiPulsaDataIsiPulsa.setClickable(true);
AturIsiPulsaDataIsiPulsa.setAdapter(AturIsiPulsaDataIsiPulsaAdapter);
EDIT !, I finally found out where I got the code. here ! : ListView inside ScrollView is not scrolling on Android
layout inflation
View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
You can get these data from RouteData of a ViewContext
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]
I have got this error because my app was in a folder that have an Arabic name and I solve it with just changing the Arabic folder name to an English one and it works fine.
So make sure that all the path of your app is written in English.
Proximity Sensor Dial
*#*#7378423#*#*
1) Service Tests - (If present)
2) Proximity Switch
3) Test on sensor (Next to logo(top) of mobile)
4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery
OR
4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.
Technically, Its not any software solution, but hardware solution will work.
Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0
. It makes more sense to say Version.1_0
since there is only one 1_0 Version.
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<fork>true</fork>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
var b bytes.Buffer
b.ReadFrom(r)
// b.String()
perldoc -q installed
claims that cpan -l
will do the trick, however it's not working for me. The other option:
cpan -a
does spit out a nice list of installed packages and has the nice side effect of writing them to a file.
Try this, it will work for sure.
When writing Rails migrations to convert a string column to an integer you'd usually say:
change_column :table_name, :column_name, :integer
However, PostgreSQL will complain:
PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer
HINT: Specify a USING expression to perform the conversion.
The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
You can use Location as mentioned here.
Here's my code if the link opened on new tab
navBack() {
let cur_path = this.location.path();
this.location.back();
if (cur_path === this.location.path())
this.router.navigate(['/default-route']);
}
Required imports
import { Router } from '@angular/router';
import { Location } from '@angular/common';
It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS
version and any Simulator. You will have to use device for testing camera purpose.
in my case i have https url but fetch return Network Request Failed error so i just stringify the body and it s working fun
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'
})
});
_x000D_
You can't close a current window or any window or page that is opened using '_self' But you can do this
var customWindow = window.open('', '_blank', '');
customWindow.close();
This is how I did it, in my code
...
global $wpdb;
$query = "INSERT INTO... VALUES(...)" ;
$wpdb->query(
$wpdb->prepare($query)
);
return $wpdb->insert_id;
...
You may want to have a look at the code here. Although it doesn't answer your question directly you could adapt the generic class types that are used to map between data classes and business objects.
Also by using generic you run the conversion process as quickly as possible.
Greetings if i get you right you need a JavaScript function that doing it
function report(v) {
//To Do
switch(v) {
case "daily":
//Do something
break;
case "monthly":
//Do somthing
break;
}
}
Regards
git will show changes in commits that affect the index, such as git rm
. It does not store a log of all git commands you execute.
However, a large number of git commands affect the index in some way, such as creating a new branch. These changes will show up in the commit history, which you can view with git log
.
However, there are destructive changes that git can't track, such as git reset
.
So, to answer your question, git does not store an absolute history of git
commands you've executed in a repository. However, it is often possible to interpolate what command you've executed via the commit history.
I think this would work
moment().weekday(); //if today is thursday it will return 4
If your local repository is somehow mucked up for release jars as opposed to snapshots (-U
and --update-snapshots
only update snapshots), you can purge the local repo using the following:
mvn dependency:purge-local-repository
You probably then want to clean and install again:
mvn dependency:purge-local-repository clean install
Lots more info available at https://maven.apache.org/plugins/maven-dependency-plugin/examples/purging-local-repository.html
You can treat C strings like pointers. So when you declare:
char str[10];
str can be used as a pointer. So if you want to copy just a portion of the string you can use:
char str1[24] = "This is a simple string.";
char str2[6];
strncpy(str1 + 10, str2,6);
This will copy 6 characters from the str1 array into str2 starting at the 11th element.
At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)
Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.
Found a quick fix in the MAMP forums.
Basically it seems MAMP is only allowing 2 versions of PHP to show up. Quick fix, rename the folders you're not bothered about using, for me this meant adding an "X" to my /Applications/MAMP/bin/php/php5.4.10_X folder. Now 5.2.17 and 5.3.20 show up in the mamp prefs.
Done!
Edit - if the PHP version you require isn't in the PHP folder, you can download the version you require from http://www.mamp.info/en/downloads/
Edit - MAMP don't seem to provide links to the alternative PHP versions on the download page any more. Use WayBackMachine https://web.archive.org/web/20180131074715/http://www.mamp.info/en/downloads/
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Hello world"];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}
This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:]
before being able to schedule and present UILocalNotifications, do not forget this.
Try this
$.cookie('_cookieName', null, { path: '/' });
The { path: '/' } do the job for you
If you need a random string rather than a pseudo random one, you should use os.urandom
as the source
from os import urandom
from itertools import islice, imap, repeat
import string
def rand_string(length=5):
chars = set(string.ascii_uppercase + string.digits)
char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)
return ''.join(islice(char_gen, None, length))
All you have to do is set the selection style on the UITableViewCell
instance using either:
Objective-C:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
or
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
Swift 2:
cell.selectionStyle = UITableViewCellSelectionStyle.None
Swift 3 and 4.x:
cell.selectionStyle = .none
Further, make sure you either don't implement -tableView:didSelectRowAtIndexPath:
in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.
More info here and here
The line before needs to end with a ;
because in SQL DISABLE
is not a keyword. For example:
BEGIN
;
DISABLE TRIGGER ...
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
Handle the ClientSizeChanged event
for the panel, making the
label fill the space:
private void Panel2_ClientSizeChanged(object sender, EventArgs e)
{
label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
}
Set Auto-Size
for the label to true
Dock
for the label to Fill
In Visual Studio 2015 From the top menu
Edit -> Advanced -> View White Space
or CTRL + E, S
window.opener
refers to the window that called window.open( ... )
to open the window from which it's calledwindow.parent
refers to the parent of a window in a <frame>
or <iframe>
window.top
refers to the top-most window from a window nested in one or more layers of <iframe>
sub-windowsThose will be null
(or maybe undefined
) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
I had the same issue and the following fixed my issue:
This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool
function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.
The short version is that you cannot use variable-width patterns in lookbehinds using Python's re
module. There is no way to change this:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
When dealing with large streams, like a file sized over 4GB - you don't want to load the file into memory (as a Byte[]
) because not only is it very slow, but also may cause a crash as even in 64-bit processes a Byte[]
cannot exceed 2GB (or 4GB with gcAllowVeryLargeObjects
).
Fortunately there's a neat helper in .NET called ToBase64Transform
which processes a stream in chunks. For some reason Microsoft put it in System.Security.Cryptography
and it implements ICryptoTransform
(for use with CryptoStream
), but disregard that ("a rose by any other name...") just because you aren't performing any cryprographic tasks.
You use it with CryptoStream
like so:
using System.Security.Cryptography;
using System.IO;
//
using( FileStream inputFile = new FileStream( @"C:\VeryLargeFile.bin", FileMode.Open, FileAccess.Read, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) ) // When using `useAsync: true` you get better performance with buffers much larger than the default 4096 bytes.
using( CryptoStream base64Stream = new CryptoStream( inputFile, new ToBase64Transform(), CryptoStreamMode.Read ) )
using( FileStream outputFile = new FileStream( @"C:\VeryLargeBase64File.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1024 * 1024, useAsync: true ) )
{
await base64Stream.CopyToAsync( outputFile ).ConfigureAwait(false);
}
I would return a character char
instead of a string.
public static char getChar(int i) {
return i<0 || i>25 ? '?' : (char)('A' + i);
}
Note: when the character decoder doesn't recognise a character it returns ?
I would use 'A'
or 'a'
instead of looking up ASCII codes.
I had the same problem when I wrote two upstreams in NGINX conf
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
server 127.0.0.1:9000;
}
...
fastcgi_pass php_upstream;
but in /etc/php/7.3/fpm/pool.d/www.conf
I listened the socket only
listen = /var/run/php/my.site.sock
So I need just socket, no any 127.0.0.1:9000
, and I just removed IP+port upstream
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
}
This could be rewritten without an upstream
fastcgi_pass unix:/var/run/php/my.site.sock;
C99 introduced _Bool
as intrinsic pure boolean type. No #include
s needed:
int main(void)
{
_Bool b = 1;
b = 0;
}
On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.
Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?
If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.
In Sourcetree:
Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.
/^[a-zA-Z]+$/
Off the top of my head.
Edit:
Or if you don't like the weird looking literal syntax you can do it like this
new RegExp("^[a-zA-Z]+$");
Here is example code what I did for an asynchronous method
@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void importDataFromFile(@RequestParam("file") MultipartFile file)
{
accountingSystemHandler.importData(file, assignChargeCodes);
}
You do not need to return any thing from your method all you need to use this annotation so that your method should return OK in every case
@ResponseStatus(value = HttpStatus.OK)
This works for me pretty fine,
git checkout origin/branchname
if you're already in branch then it's better to do pull or rebase
git pull
or
git -c core.quotepath=false fetch origin --progress --prune
Later you can simply use
git commit --amend -m "Your message here"
or if you like to open text-editor then use
git commit --amend
I will prefer using text-editor if you have many comments. You can set your preferred text-editor with command
git config --global core.editor your_preffered_editor_here
Anyway, when your are done changing the commit message, save it and exit
and then run
git push --force
And you're done