I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
edit: This does not answer the question the OP meant to ask, leaving it here in case people find it useful somehow.
We use the multiplication rule of probability, combined with infinitessimals. This results in 2 lines of code to achieve your desired result:
longitude: f = uniform([0,2pi))
azimuth: ? = -arcsin(1 - 2*uniform([0,1]))
(defined in the following coordinate system:)
Your language typically has a uniform random number primitive. For example in python you can use random.random()
to return a number in the range [0,1)
. You can multiply this number by k to get a random number in the range [0,k)
. Thus in python, uniform([0,2pi))
would mean random.random()*2*math.pi
.
Proof
Now we can't assign ? uniformly, otherwise we'd get clumping at the poles. We wish to assign probabilities proportional to the surface area of the spherical wedge (the ? in this diagram is actually f):
An angular displacement df at the equator will result in a displacement of df*r. What will that displacement be at an arbitrary azimuth ?? Well, the radius from the z-axis is r*sin(?)
, so the arclength of that "latitude" intersecting the wedge is df * r*sin(?)
. Thus we calculate the cumulative distribution of the area to sample from it, by integrating the area of the slice from the south pole to the north pole.
(where stuff=df*r
)
We will now attempt to get the inverse of the CDF to sample from it: http://en.wikipedia.org/wiki/Inverse_transform_sampling
First we normalize by dividing our almost-CDF by its maximum value. This has the side-effect of cancelling out the df and r.
azimuthalCDF: cumProb = (sin(?)+1)/2 from -pi/2 to pi/2
inverseCDF: ? = -sin^(-1)(1 - 2*cumProb)
Thus:
let x by a random float in range [0,1]
? = -arcsin(1-2*x)
To make nano
work as you want it to, try:
export LANG="UTF-8"
Or get a newer version of nano
via MacPorts
:
# cf. http://www.macports.org/install.php
port info nano
port variants nano
sudo port install nano +utf8 +color +no_wrap
With respect to ssh & UTF-8 issues comment out SendEnv LANG LC_*
in /etc/ssh_config
.
See: Terminal in OS X Lion: can't write åäö on remote machine
Changing PHP version from 5.6 to 5.5 Fixed it.
You have to go to control panel > CGI Script and change PHP version there.
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
The meaning of remotes/origin/test
is that you have a branch called test
in the remote server origin
. So the command would be
git push origin --delete test
The answer is in this line of the output of readelf -a
in the original question
[Requesting program interpreter: /lib/ld-linux.so.2]
I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.
git reset HEAD
Should do it. If you don't have any uncommitted changes that you care about, then
git reset --hard HEAD
should forcibly reset everything to your last commit. If you do have uncommitted changes, but the first command doesn't work, then save your uncommitted changes with git stash
:
git stash
git reset --hard HEAD
git stash pop
In a query you can just do something like:
SELECT ColumnA * ColumnB FROM table
or
SELECT ColumnA - ColumnB FROM table
You can also create computed columns in your table where you can permanently use your formula.
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var fulldate = new Date(year + 1, month, day);
var toDate = fulldate.toISOString().slice(0, 10);
$("#txtToDate").val(toDate);
output : 2020-01-02
You need to create your own custom button template to have full control over the appearance in all states. Here's a tutorial.
For someone who is going to show Force Update Alert based on version number I have a following Idea. This may be used when comparing the versions between Android Current App version and firebase remote config version. This is not exactly the answer for the question asked but this will help someone definitely.
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
static String firebaseVersion = "2.1.3"; // or 2.1
static String appVersion = "2.1.4";
static List<String> firebaseVersionArray;
static List<String> appVersionArray;
static boolean isNeedToShowAlert = false;
public static void main (String[]args)
{
System.out.println ("Hello World");
firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split ("\\.")));
appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split ("\\.")));
if(appVersionArray.size() < firebaseVersionArray.size()) {
appVersionArray.add("0");
}
if(firebaseVersionArray.size() < appVersionArray.size()) {
firebaseVersionArray.add("0");
}
isNeedToShowAlert = needToShowAlert(); //Returns false
System.out.println (isNeedToShowAlert);
}
static boolean needToShowAlert() {
boolean result = false;
for(int i = 0 ; i < appVersionArray.size() ; i++) {
if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {
continue;
} else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){
result = false;
break;
} else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {
result = true;
break;
}
}
return result;
}
}
You can run this code by copy pasting in https://www.onlinegdb.com/online_java_compiler
This allows to show time in input field but hides time picker button, which is second li element in accordion
.bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2){
display: none;
}
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.
Even in 2009, it seems too many had a very limited idea of what designing for the WORLDWIDE web involved. In 2015, unless designing for a specific country, a blacklist is the only way to accommodate the vast number of characters that may be valid.
The characters to blacklist then need to be chosen according what is illegal for the purpose for which the data is required.
However, sometimes it pays to break down the requirements, and handle each separately. Here look-ahead is your friend. These are sections bounded by (?=)
for positive, and (?!)
for negative, and effectively become AND blocks, because when the block is processed, if not failed, the regex processor will begin at the start of the text with the next block. Effectively, each look-ahead block will be preceded by the ^
, and if its pattern is greedy, include up to the $
. Even the ancient VB6/VBA (Office) 5.5 regex engine supports look-ahead.
So, to build up a full regular expression, start with the look-ahead blocks, then add the blacklisted character block before the final $
.
For example, to limit the total numbers of characters, say between 3 and 15 inclusive, start with the positive look-ahead block (?=^.{3,15}$)
. Note that this needed its own ^
and $
to ensure that it covered all the text.
Now, while you might want to allow _ and -, you may not want to start or end with them, so add the two negative look-ahead blocks, (?!^[_-].+)
for starts, and (?!.+[_-]$)
for ends.
If you don't want multiple _
and -
, add a negative look-ahead block of (?!.*[_-]{2,})
. This will also exclude _-
and -_
sequences.
If there are no more look-ahead blocks, then add the blacklist block before the $
, such as [^<>[\]{\}|\\\/^~%# :;,$%?\0-\cZ]+
, where the \0-\cZ
excludes null and control characters, including NL (\n
) and CR (\r
). The final +
ensures that all the text is greedily included.
Within the Unicode domain, there may well be other code-points or blocks that need to be excluded as well, but certainly a lot less than all the blocks that would have to be included in a whitelist.
The whole regex of all of the above would then be
(?=^.{3,15}$)(?!^[_-].+)(?!.+[_-]$)(?!.*[_-]{2,})[^<>[\]{}|\\\/^~%# :;,$%?\0-\cZ]+$
which you can check out live on https://regex101.com/, for pcre (php), javascript and python regex engines. I don't know where the java regex fits in those, but you may need to modify the regex to cater for its idiosyncrasies.
If you want to include spaces, but not _
, just swap them every where in the regex.
The most useful application for this technique is for the pattern
attribute for HTML input
fields, where a single expression is required, returning a false for failure, thus making the field invalid, allowing input:invalid
css to highlight it, and stopping the form being submitted.
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
A simple alternative is to use numpy's concatenate but it converts the contents to float:
import numpy as np
print np.concatenate([[1,2],[3],[5,89],[],[6]])
# array([ 1., 2., 3., 5., 89., 6.])
print list(np.concatenate([[1,2],[3],[5,89],[],[6]]))
# [ 1., 2., 3., 5., 89., 6.]
Came across this article from 2012. It takes into account variables that may or may not be just plain URLs.
The author of the article, David Müeller, provides this function that he says, "...could be worth wile [sic]," along with some examples of filter_var
and its shortcomings.
/**
* Modified version of `filter_var`.
*
* @param mixed $url Could be a URL or possibly much more.
* @return bool
*/
function validate_url( $url ) {
$url = trim( $url );
return (
( strpos( $url, 'http://' ) === 0 || strpos( $url, 'https://' ) === 0 ) &&
filter_var(
$url,
FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED || FILTER_FLAG_HOST_REQUIRED
) !== false
);
}
First zip or gzip the folders:
Use the following command:
zip -r NameYouWantForZipFile.zip foldertozip/
or
tar -pvczf BackUpDirectory.tar.gz /path/to/directory
for gzip compression use SCP:
scp [email protected]:~/serverpath/public_html ~/Desktop
adding HTTP headers using urllib2:
from the docs:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()
$_SERVER["PHP_SELF"];
will give you the current filename and its path, but basename(__FILE__)
should give you the filename that it is called from.
So
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
should do it.
It is indeed possible to change a div
elements' width in jQuery:
$("#div").css("width", "300px");
However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:
#div {
width: 75%;
/* You can also specify min/max widths */
min-width: 300px;
max-width: 960px;
}
This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.
I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.
private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
{
List<string> returnValue = new List<string>();
try
{
int index = userPrincipalName.IndexOf("@");
string originatingServer = userPrincipalName.Remove(0, index + 1);
string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
SearchResultCollection properties = objSearcher.FindAll();
ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
foreach (string resProperty in resPropertyCollection)
{
returnValue.Add(resProperty);
}
}
catch (Exception ex)
{
returnValue.Add(ex.Message);
throw;
}
return returnValue;
}
In Mongoose: from the document:
To remove a document from a subdocument array we may pass an object with a matching _id.
contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works
See Leonid Beschastny's answer for the correct answer.
Sub AddColor()
For Each cell In Selection
R = Round(cell.Value)
G = Round(cell.Offset(0, 1).Value)
B = Round(cell.Offset(0, 2).Value)
Cells(cell.Row, 1).Resize(1, 4).Interior.Color = RGB(R, G, B)
Next cell
End Sub
Assuming that there are 3 columns R, G and B (in this order). Select first column ie R. press alt+F11 and run the above code. We have to select the first column (containing R or red values) and run the code every time we change the values to reflect the changes.
I hope this simpler code helps !
you can try quoting it which will keep the link as text. see the code blocks section: https://get.slack.help/hc/en-us/articles/202288908-Format-your-messages#code-blocks
The following code works to prevent column breaks inside elements:
-webkit-column-break-inside: avoid;
-moz-column-break-inside: avoid;
-o-column-break-inside: avoid;
-ms-column-break-inside: avoid;
column-break-inside: avoid;
Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover
state of the main element.
For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...
The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.
Here is an example:
#container {_x000D_
width: 200px;_x000D_
height: 30px;_x000D_
border: 1px solid var(--c);_x000D_
--c:red;_x000D_
}_x000D_
#container:hover {_x000D_
--c:blue;_x000D_
}_x000D_
#container > div {_x000D_
width: 30px;_x000D_
height: 100%;_x000D_
background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
<div>_x000D_
</div>_x000D_
</div>
_x000D_
Why this can be better than using specific selector combined with hover?
I can provide at least 2 reasons that make this method a good one to consider:
border
, linear-gradient
, background-color
, box-shadow
etc. This will avoid us reseting all these properties on hover.Here is a more complex example:
.container {_x000D_
--c:red;_x000D_
width:400px;_x000D_
display:flex;_x000D_
border:1px solid var(--c);_x000D_
justify-content:space-between;_x000D_
padding:5px;_x000D_
background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
width:30%;_x000D_
background:var(--c);_x000D_
box-shadow:0px 0px 5px var(--c);_x000D_
position:relative;_x000D_
}_x000D_
.box:before {_x000D_
content:"A";_x000D_
display:block;_x000D_
width:15px;_x000D_
margin:0 auto;_x000D_
height:100%;_x000D_
color:var(--c);_x000D_
background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
--c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
As we can see above, we only need one CSS declaration in order to change many properties of different elements.
Try this :
$obj = @{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
Custom String Values for Enum
from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
this is one
this is two
import {MatButtonModule} from '@angular/material/button';
Report Manager has been around for quite a few years. It's written in Delphi (at least it was originally) and has components that can be used in Delphi, but is usable via ActiveX or dll from just about any language. Now has a native .NET library too. Has a nifty report-serving webserver you can set up too. The designer gui looks and feels a little rough around the edges but it works. http://reportman.sourceforge.net/
Go to
if it doesnt work this can help you:
https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html
use the command "mysql -u root -p" in the bin folder path. and give the MY SQL password which you have set earlier.
Try the code below and.....
1 - change the name of the MENU as in my sample the menuitem was called 'Form7ToolStripMenuItem_Click'
2 - make SURE to paste it into an MDIFORM and not just a basic FORM
Then let me know if the CHILD form still shows OUTSIDE the parent form
Private Sub Form7ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Form7ToolStripMenuItem.Click
Dim NewForm As System.Windows.Forms.Form
NewForm = New System.Windows.Forms.Form
'USE THE NEXT LINE - to add an existing CUSTOM form you already have
'NewForm = Form7
NewForm.Width = 400
NewForm.Height = 250
NewForm.MdiParent = Me
NewForm.Text = "CAPTION"
NewForm.Show()
DockChildForm(NewForm, "left") 'dock left
'DockChildForm(NewForm, "right") 'dock right
'DockChildForm(NewForm, "top") 'dock top
'DockChildForm(NewForm, "bottom") 'doc bottom
'DockChildForm(NewForm, "full") 'fill the client area (maximise the child INSIDE the parent)
'DockChildForm(NewForm, "Anything-Else") 'center the form
End Sub
Private Sub DockChildForm(ByRef Form2Dock As Form, ByVal Position As String)
Dim XYpoint As Point
Select Case Position
Case "left"
Form2Dock.Dock = DockStyle.Left
Case "top"
Form2Dock.Dock = DockStyle.Top
Case "right"
Form2Dock.Dock = DockStyle.Right
Case "bottom"
Form2Dock.Dock = DockStyle.Bottom
Case "full"
Form2Dock.Dock = DockStyle.Fill
Case Else
XYpoint = New Point
XYpoint.X = ((Me.ClientSize.Width - Form2Dock.Width) / 2)
XYpoint.Y = ((Me.ClientSize.Height - Form2Dock.Height) / 2)
Form2Dock.Location = XYpoint
End Select
End Sub
As Davide Gualano has been told. This one
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
use GET method for sending the request, and this one
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})
use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.
For example: url length limits the amount of sending data in GET method.
You can also just change the build variant to Debug and you should be good to go
you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...
app.directive('numericOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//clear beginning 0
if(transformedInput == 0){
modelCtrl.$setViewValue(null);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
In some distributives(CentOS/OpenSuSe,...) will work only if you set JAVA_HOME in the /etc/environment.
I don't have a mysql database to test on at the moment, but have you tried specifying what to delete prior to the from clause? For example:
DELETE p, pa FROM `pets` p,
`pets_activities` pa
WHERE p.`order` > :order
AND p.`pet_id` = :pet_id
AND pa.`id` = p.`pet_id`
I think the syntax you used is limited to newer versions of mysql.
This answer is a much cleaner way to do it using new syntax.
Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl
, this can set the width based on the segment's title string.
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.height
}
func sizeOfString(usingFont font: UIFont) -> CGSize {
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}
}
usage:
// Set width of segmentedControl
let starString = "??"
let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
segmentedController.setWidth(starWidth, forSegmentAt: 3)
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.
For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.
$person = "Rasmus Lerdorf";
$found = false;
foreach($organization as $oKey=>$department)
{
foreach($department as $dKey=>$group)
{
foreach($group as $gKey=>$employee)
{
if ($employee['fullname'] == $person)
{
$found = true;
break 3;
}
} // group
} // department
} // organization
Under Xcode 4.5.2, you can find the .app file in this way:
I solved it easily via running these codes:
npm uninstall mongodb --save
npm install [email protected] --save
Happy Coding!
The shortest way (will print "not same" because String comparison is case sensitive):
def compareString = {
it == "india" ? "same" : "not same"
}
compareString("India")
Use PerfMon to collect data and DebugDiag to analyse.
Found this link while searching for similar issue.
Two good examples are regarding how you manage templates and use progressive enhancements with it. You just need a few lightweight pieces of JavaScript code to make it work perfectly.
I strongly recommend that you watch and read these articles:
Pick up any language and try to remember how you would manage your HTML file templates and what you had to do to update a single CSS class name in your DOM structure (for instance, a user clicked on a menu item and you want that marked as "selected" and update the content of the page).
With Node.js it is as simple as doing it in client-side JavaScript code. Get your DOM node and apply your CSS class to that. Get your DOM node and innerHTML your content (you will need some additional JavaScript code to do this. Read the article to know more).
Another good example, is that you can make your web page compatible both with JavaScript turned on or off with the same piece of code. Imagine you have a date selection made in JavaScript that would allow your users to pick up any date using a calendar. You can write (or use) the same piece of JavaScript code to make it work with your JavaScript turned ON or OFF.
Make sure to enable the use of shortcodes in text widgets.
// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );
// and then you can use it in any PHP file:
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>
Check the documentation for more.
add an attribute to the EditText like android:imeOptions="actionSearch"
this is the best way to do the function
and the imeOptions also have some other values like "go" ?"next"?"done" etc.
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.
#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl <-- perl script
#!/usr/bin/php <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.
Most scripting languages tend to interpret a line starting with #
as comment and will ignore the following !/usr/bin/whatever
portion, which might otherwise cause a syntax error in the interpreted language.
This is easiest implement.
function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen($url, 'rb');
if ($file) {
$newf = fopen($newfname, 'wb');
if ($newf) {
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
If you're not careful and you're trying to disable something in your app manifest make sure you don't disable the app...
<application
android:allowBackup="false"
android:enabled="true"
...
I accidentally set enabled
to "false" instead of allowBackup
. Wasted 2 hours searching for a solution.
One minor difference is what they convert of undefined
or null
,
Number() Or Number(null) // returns 0
while
parseInt() Or parseInt(null) // returns NaN
//$sql - sql statement
//$em - entity manager
$em->getConnection()->exec( $sql );
As of version 2.10.1, here is the path -
C:\Users\usersam\AppData\Local\Programs\Git\cmd\git.exe
There is a single quote in $submitsubject
or $submit_message
Why is this a problem?
The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.
Imagine if someone submitted '); DROP TABLE private_messages;
in submit message.
Your SQL Command would be:
INSERT INTO private_messages (to_id, from_id, time_sent, subject, message)
VALUES('sender_id', 'id', now(),'subjet','');
DROP TABLE private_messages;
Instead you need to properly sanitize your values.
AT A MINIMUM you must run each value through mysql_real_escape_string()
but you should really be using prepared statements.
If you were using mysql_real_escape_string()
your code would look like this:
if($_POST['submit_message']){
if($_POST['form_subject']==""){
$submit_subject="(no subject)";
}else{
$submit_subject=mysql_real_escape_string($_POST['form_subject']);
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);
Here is a great article on prepared statements and PDO.
There are a few ways to do this, as mentioned above, but in my experience the best way to manipulate an XHR request and resend is to use chrome dev tools to copy the request as cURL request (right click on the request in the network tab) and to simply import into the Postman app (giant import button in the top left).
adb shell ip addr > ippdetails.txt This will get all list of ip's assigned to devices.
You can resize image with this piece of code
var maxWidth = 600;
$("img").each(function () {
var imageWidth = $(this).width();
var imageHeight = $(this).height();
if (imageWidth > maxWidth) {
var percentdiff = (imageWidth - maxWidth) / imageWidth * 100;
$(this).width(maxWidth);
$(this).height(imageHeight - (imageHeight * percentdiff / 100));
}
});
While some of those code-snippets are short and working, they aren't trivial to follow and understand.
As i am not a fan of "copy-paste" from stack-overflow, i would like developers to understand the code they are push into they software, hope you'll find the below useful.
DEMO: Resizing images with JS and HTML Canvas Demo fiddler.
You may find 3 different methods to do this resize, that will help you understand how the code is working and why.
https://jsfiddle.net/1b68eLdr/93089/
Full code of both demo, and TypeScript method that you may want to use in your code, can be found in the GitHub project.
https://github.com/eyalc4/ts-image-resizer
This is the final code:
export class ImageTools {
base64ResizedImage: string = null;
constructor() {
}
ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
let img = new Image();
img.src = base64image;
img.onload = () => {
// Check if the image require resize at all
if(img.height <= height && img.width <= width) {
this.base64ResizedImage = base64image;
// TODO: Call method to do something with the resize image
}
else {
// Make sure the width and height preserve the original aspect ratio and adjust if needed
if(img.height > img.width) {
width = Math.floor(height * (img.width / img.height));
}
else {
height = Math.floor(width * (img.height / img.width));
}
let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
let resizingCanvasContext = resizingCanvas.getContext("2d");
// Start with original image size
resizingCanvas.width = img.width;
resizingCanvas.height = img.height;
// Draw the original image on the (temp) resizing canvas
resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);
let curImageDimensions = {
width: Math.floor(img.width),
height: Math.floor(img.height)
};
let halfImageDimensions = {
width: null,
height: null
};
// Quickly reduce the dize by 50% each time in few iterations until the size is less then
// 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
// created with direct reduction of very big image to small image
while (curImageDimensions.width * 0.5 > width) {
// Reduce the resizing canvas by half and refresh the image
halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);
resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
0, 0, halfImageDimensions.width, halfImageDimensions.height);
curImageDimensions.width = halfImageDimensions.width;
curImageDimensions.height = halfImageDimensions.height;
}
// Now do final resize for the resizingCanvas to meet the dimension requirments
// directly to the output canvas, that will output the final image
let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
let outputCanvasContext = outputCanvas.getContext("2d");
outputCanvas.width = width;
outputCanvas.height = height;
outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
0, 0, width, height);
// output the canvas pixels as an image. params: format, quality
this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);
// TODO: Call method to do something with the resize image
}
};
}}
Try:
document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";
Here is how you can scale it easily.
This works in 2.x with the Simulator and the iPhone.
UIImage *thumbnail = [originalImage _imageScaledToSize:CGSizeMake(40.0, 40.0) interpolationQuality:1];
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
INSERT INTO prices (group, id, price)
SELECT 7, articleId, 1.50 FROM article WHERE name LIKE 'ABC%'
select a.user from (select user from users order by user) a where rownum = 1
will perform the best, another option is:
select a.user
from (
select user,
row_number() over (order by user) user_rank,
row_number() over (partition by dept order by user) user_dept_rank
from users
) a
where a.user_rank = 1 or user_dept_rank = 2
in scenarios where you want different subsets, but I guess you could also use RANK()
But, I also like row_number()
over(...)
since no grouping is required.
You can permanently set up your bash output to show your git-branch name. It is very handy when you work with different branches, no need to type $ git status
all the time.
Github repo git-aware-prompt
.
Open your terminal (ctrl-alt-t) and enter the commands
mkdir ~/.bash
cd ~/.bash
git clone git://github.com/jimeh/git-aware-prompt.git
Edit your .bashrc with sudo nano ~/.bashrc
command (for Ubuntu) and add the following to the top:
export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"
Then paste the code
export PS1="\${debian_chroot:+(\$debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[$txtcyn\]\$git_branch\[$txtred\]\$git_dirty\[$txtrst\]\$ "
at the end of the same file you pasted the installation code into earlier. This will give you the colorized output:
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
getClass().getResource()
uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.
When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:
When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource()
or getResourceAsStream()
.
If it doesn't work from the command line, it's thus because the file is not in the classpath.
Note that you should NOT do
FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));
to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use
getClass().getResourceAsStream("Test.properties")
And finally, as the documentation indicates,
Foo.class.getResourceAsStream("Test.properties")
will load a Test.properties file located in the same package as the class Foo.
Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")
will load a Test.properties file located in the package com.foo.bar
.
Please open your Visual Studio as administrator:
In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.
You cannot open and read a directory, use the isFile()
and isDirectory()
methods to distinguish between files and folders. You can get the contents of folders using the list()
and listFiles()
methods (for filenames and File
s respectively) you can also specify a filter that selects a subset of files listed.
Above correct answer is very old it needs something new so Here is answer
As in last update we have androidx support so first include dependency in your app level build.gradle file
implementation 'com.google.android.gms:play-services-location:17.0.0'
then add in your manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
don't forget to take user consent for these permissions if you are releasing
now here is code just use it
protected void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
Toast.makeText(MainActivity.this, "Gps already open",
Toast.LENGTH_LONG).show();
Log.d("location settings",locationSettingsResponse.toString());
}
});
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_CHECK_SETTINGS){
if(resultCode==RESULT_OK){
Toast.makeText(this, "Gps opened", Toast.LENGTH_SHORT).show();
//if user allows to open gps
Log.d("result ok",data.toString());
}else if(resultCode==RESULT_CANCELED){
Toast.makeText(this, "refused to open gps",
Toast.LENGTH_SHORT).show();
// in case user back press or refuses to open gps
Log.d("result cancelled",data.toString());
}
}
}
if something goes wrong please ping me
In Debian Linux wget can be configured to use a proxy both via environment variables and via wgetrc. In both cases the variable names to be used for HTTP and HTTPS connections are
http_proxy=hostname_or_IP:portNumber
https_proxy=hostname_or_IP:portNumber
Note that the file /etc/wgetrc takes precedence over the environment variables, hence if your system has a proxy configured there and you try to use the environment variables, they would seem to have no effect!
Since fields
or fns
are cell arrays, you have to index with curly brackets {}
in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields
directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end
I put commit .gitignore, which is a courtesy to other who may build my project that the following files are derived and should be ignored.
I usually do a hybrid. I like to make makefile generate the .gitignore file since the makefile will know all the files associated with the project -derived or otherwise. Then have a top level project .gitignore that you check in, which would ignore the generated .gitignore files created by the makefile for the various sub directories.
So in my project, I might have a bin sub directory with all the built executables. Then, I'll have my makefile generate a .gitignore for that bin directory. And in the top directory .gitignore that lists bin/.gitignore. The top one is the one I check in.
@RequestParam
annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:
request:
GET: http://someserver.org/path?name=John&surname=Smith
endpoint code:
public User getUser(@RequestParam(value = "name") String name,
@RequestParam(value = "surname") String surname){
...
}
So basically, while @RequestBody
maps entire user request (even for POST) to a String variable, @RequestParam
does so with one (or more - but it is more complicated) request param to your method argument.
If I understand correctly you want then
of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.
Updated code would look something like this:
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
return new Promise(function(resolve, reject) {
axios(config).then(
function (response) {
resolve(response.data)
}
).catch(
function (error) {
console.log('Show error notification!')
}
)
});
}
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)
UNION ALL
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 10)
You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:
function ssnValidator(control: FormControl): {[key: string]: any} {
const value: string = control.value || '';
const valid = value.match(/^\d{9}$/);
return valid ? null : {ssn: true};
}
Take a look at a sample app here:
godbolt is a very useful tool, they list only has C++ compilers but you can use -x c
flag in order to get it treat the code as C. It will then generate an assembly listing for your code side by side and you can use the Colourise
option to generate colored bars to visually indicate which source code maps to the generated assembly. For example the following code:
#include <stdio.h>
void func()
{
printf( "hello world\n" ) ;
}
using the following command line:
-x c -std=c99 -O3
and Colourise
would generate the following:
Check this answer may it will help and I used in my project.
function replaceAll(searchString, replaceString, str) {
return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test test test test test test test test "
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
You can use datetime.strftime to extract the day, the month, the year...
Example :
from datetime import datetime
d = datetime.today()
# Retrieves the day and the year
print d.strftime("%d-%Y")
Output (for today):
29-2011
If you just want to retrieve the day, you can use day attribute like :
from datetime import datetime
d = datetime.today()
# Retrieves the day
print d.day
Ouput (for today):
29
In visual studio for .Net 4.0 framework,
System.Runtime.Serialization
. using System.Runtime.Serialization
. And the error will not be shown. for large numbers that display with scientific notation set format to just '#'
Finally i found the solution after spending two days...
Follow these steps:
This really worked to me.
Try this and happy coding!!!
I wasn't able to find any that handled my particular situation, which was removing urls in the middle of tweets that also have whitespaces in the middle of urls so I made my own:
(https?:\/\/)(\s)*(www\.)?(\s)*((\w|\s)+\.)*([\w\-\s]+\/)*([\w\-]+)((\?)?[\w\s]*=\s*[\w\%&]*)*
here's an explanation:
(https?:\/\/)
matches http:// or https://
(\s)*
optional whitespaces
(www\.)?
optionally matches www.
(\s)*
optionally matches whitespaces
((\w|\s)+\.)*
matches 0 or more of one or more word characters followed by a period
([\w\-\s]+\/)*
matches 0 or more of one or more words(or a dash or a space) followed by '\'
([\w\-]+)
any remaining path at the end of the url followed by an optional ending
((\?)?[\w\s]*=\s*[\w\%&]*)*
matches ending query params (even with white spaces,etc)
test this out here:https://regex101.com/r/NmVGOo/8
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
Everyone
to the user list.This is something to do with user permissions. Giving proper grants will solve this issue.
Step [1]: Open terminal and run this command
$ mysql -uroot -p
Output [1]: This should give you mysql prompt shown below
Step [2]:
mysql> CREATE USER 'parsa'@'localhost' IDENTIFIED BY 'your_password';
mysql> grant all privileges on *.* to 'parsa'@'localhost';
Syntax:
mysql> grant all privileges on `database_name`.`table_name` to 'user_name'@'hostname';
Note:
- hostname can be IP address, localhost, 127.0.0.1
- In
database_name
/table_name
, * means all databases- In
hostname
, to specify all hosts use '%'
Step [3]: Get out of current mysql prompt by either entering quit
/ exit
command or press Ctrl+D
.
Step [4]: Login to your new user
$ mysql -uparsa -pyour_password
Step [5]: Create the database
mysql> create database `database_name`;
If you try set a value in datetime-local
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21
If you have your arguments in an array, you might be interested by the call_user_func_array
function.
If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array
.
Elements of that array you pass will then be received by your function as distinct parameters.
For instance, if you have this function :
function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}
You can pack your parameters into an array, like this :
$params = array(
10,
'glop',
'test',
);
And, then, call the function :
call_user_func_array('test', $params);
This code will the output :
int 3
array
0 => int 10
1 => string 'glop' (length=4)
2 => string 'test' (length=4)
ie, 3 parameters ; exactly like iof the function was called this way :
test(10, 'glop', 'test');
You're using an Array
like an "associative array", which does not exist in JavaScript. Use an Object
({}
) instead.
If you are going to continue with an array, realize that toString()
will join all the numbered properties together separated by a comma. (the same as .join(",")
).
Properties like a
and b
will not come up using this method because they are not in the numeric indexes. (ie. the "body" of the array)
In JavaScript, Array inherits from Object
, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString()
, .join()
, etc. Your other properties are still there and very much accessible. :)
Read Mozilla's documentation for more information about Arrays.
var aa = [];
// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";
// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";
aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")
One point no one has touched on is the fact that the h1 attribute should be specific to every page and using the site logo will effectively replicate the H1 on every page of the site.
I like to use a z index hidden h1 for each page as the best SEO h1 is often not the best for sales or aesthetic value.
If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:
use strict;
use warnings;
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;
print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;
Output:
0 => 3
1 => 1
2 => 2
3 => 3
4 => 1
To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:
my @zeroes = (0) x 5; # (0,0,0,0,0)
my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
# This works because in scalar context
# an array evaluates to its size.
Add this to your dependencies in build.gradle
:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
...
The latest version can be found here
Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project
Take a look at your libraries folder, the library you just added should be in there.
Since there's no language listed, I'll answer this in Swift. We highly recommend using Firebase Storage and the Firebase Realtime Database together to accomplish lists of downloads:
Shared:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()
Upload:
let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
}
Download:
let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
})
})
For more information, see Zero to App: Develop with Firebase, and it's associated source code, for a practical example of how to do this.
If you don't need to support IE7, the following is a great, concise hack:
JSON.parse(JSON.stringify(new Date()))
ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go
Let's start by the following example:
Now we have 3 options to merge changes of feature branch into master branch:
Merge commits
Will keep all commits history of the feature branch and move them into the master branch
Will add extra dummy commit.
Rebase and merge
Will append all commits history of the feature branch in the front of the master branch
Will NOT add extra dummy commit.
Squash and merge
Will group all feature branch commits into one commit then append it in the front of the master branch
Will add extra dummy commit.
You can find below how the master branch will look after each one of them.
In all cases:
We can safely DELETE the feature branch.
I also faced the same issue, now it is resolved. If you are facing issues with pure components or classes, make sure that you are using .js extension instead of .jsx.
check this, its guaranteed and easy !
$("#inputField").attr("readonly","readonly");
$("#inputField").click(function () {
$(this).removeAttr("readonly");
$(this).focus();
});
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.
class name - User is accepted but user is not.
May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
use this:
$(document).on('show.bs.modal','#myModal', function () {
alert('hi');
})
It's quite simple.
All you need to do is:
Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement
switch(value)
{
case 1:
case 2:
return true;
default:
return false
}
Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover
(which will allow the image to extend out from the sides) or contain
(which does not allow the image to extend out at all), just set the CSS like so:
body {
background-image: url(img.jpg);
background-position: center top;
background-size: 100% auto;
}
This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.
EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.
Hopefully soon you'll be able to use the new srcset attribute on the img
element. If you want to use img
elements now, the currently accepted answer is probably best.
However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height
to 0 and set the padding-bottom
to a percentage of the element's own width, like so:
.foo {
height: 0;
padding: 0; /* remove any pre-existing padding, just in case */
padding-bottom: 75%; /* for a 4:3 aspect ratio */
background-image: url(foo.png);
background-position: center center;
background-size: 100%;
background-repeat: no-repeat;
}
In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.
This has been working for me:
If you try uploading the new file as a war file, with tomcat still running, it will attempt to expand it before it is all there. It will fail. Having failed, it will not try again. Thus, uploading a www file, then renaming it, allows the whole war file to be present before tomcat notices it.
Hint, don't forget to check that the war file's owner is tomcat (Use chown)
The </script>
inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).
To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):
<script type="text/javascript">
<!--
if (jQuery === undefined) {
document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
}
// -->
</script>
...but to be honest, using document.write
is not something I would consider best practice. Why not manipulating the DOM directly?
<script type="text/javascript">
<!--
if (jQuery === undefined) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
document.body.appendChild(script);
}
// -->
</script>
Library - Any set of classes or components that can be used as the client deems fit to accomplish a certain task.
Framework - mandates certain guidelines for you to "plug-in" into something bigger than you. You merely provide the pieces specific to your application/requirements in a published-required manner, so that 'the framwework can make your life easy'
I'm using this code for my sites
server {
listen 80;
listen 443;
server_name .domain.com;
return 301 $scheme://newdomain.com$request_uri;
}
Though you can have several <form>
elements in one HTML page, you cannot nest them.
Quite simple, with a *
wildcard.
cp -r Folder1/* Folder2/
But according to your example recursion is not needed so the following will suffice:
cp Folder1/* Folder2/
EDIT:
Or skip the mkdir Folder2
part and just run:
cp -r Folder1 Folder2
You can't have private
class but you can have second
class:
public class App14692708 {
public static void main(String[] args) {
PC pc = new PC();
System.out.println(pc);
}
}
class PC {
@Override
public String toString() {
return "I am PC instance " + super.toString();
}
}
Also remember that static
inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass
. So if you don't want to use "closures", use static inner class.
From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
The error message suggests this is not a supported feature in the query language. But you can save a DataFrame in any format as usual through the RDD interface (df.rdd.saveAsTextFile
). Or you can check out https://github.com/databricks/spark-csv.
In bash 4, you can use associative arrays:
declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
echo "key: $key, value: ${foo[$key]}"
done
# output
# $ key: 0, value bar.
# $ key: 35, value baz.
In bash 3, this works (also works in zsh):
map=( )
map+=("0:bar")
map+=("35:baz")
for keyvalue in "${map[@]}" ; do
key=${keyvalue%%:*}
value=${keyvalue#*:}
echo "key: $key, value $value."
done
Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod
over @staticmethod
when you are creating an additional constructor.
In the example above, Rostyslav used the @classmethod
from_string
as a Factory to create Date
objects from otherwise unacceptable parameters. The same can be done with @staticmethod
as is shown in the code below:
class Date:
def __init__(self, month, day, year):
self.month = month
self.day = day
self.year = year
def display(self):
return "{0}-{1}-{2}".format(self.month, self.day, self.year)
@staticmethod
def millenium(month, day):
return Date(month, day, 2000)
new_year = Date(1, 1, 2013) # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object.
# Proof:
new_year.display() # "1-1-2013"
millenium_new_year.display() # "1-1-2000"
isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True
Thus both new_year
and millenium_new_year
are instances of the Date
class.
But, if you observe closely, the Factory process is hard-coded to create Date
objects no matter what. What this means is that even if the Date
class is subclassed, the subclasses will still create plain Date
objects (without any properties of the subclass). See that in the example below:
class DateTime(Date):
def display(self):
return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)
datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)
isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False
datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.
datetime2
is not an instance of DateTime
? WTF? Well, that's because of the @staticmethod
decorator used.
In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod
is what you need.
Rewriting Date.millenium
as (that's the only part of the above code that changes):
@classmethod
def millenium(cls, month, day):
return cls(month, day, 2000)
ensures that the class
is not hard-coded but rather learnt. cls
can be any subclass. The resulting object
will rightly be an instance of cls
.
Let's test that out:
datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)
isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True
datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"
The reason is, as you know by now, that @classmethod
was used instead of @staticmethod
Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.
I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home
There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.
If you need to make a $.post
work to a Laravel Route::delete
or Route::put
just add an argument "_method"="delete"
or "_method"="put"
.
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...
Must works for others Frameworks
Note: Tested with Laravel 5.6 and jQuery 3
To my knowledge, no.
Circumstantial indications from $LC_CTYPE
, locale
and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.
They only way to detect encoding for sure is to output something only present in the encoding, e.g. ä
, take a screenshot, analyze that image and check if the output character is correct.
So no, it's not possible, sadly.
The working solution listed are great, but the problem occurs when you want multiple default home for your git-bash.
A simple workaround is to start git-bash using bat script.
cd C:\xampp\htdocs
"C:\Program Files\Git\git-bash.exe"
The above of course assume git-bash is installed at C:\Program Files\Git\git-bash.exe
You can create multiple .bat
file so your git-bash can start where it want to be
I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.
Now well, that looks like this:
Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
while(productIds.Count > 0)
{
sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
entities.Products.Name, productIds.Dequeue());
}
}
Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where
throws the following exception:
The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.
Found this in MSDN Forums, might be helpful to have in mind.
Matthias
... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)
You can read about it here.
return render_template('page.html'), 201
Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.
How about with a :before
pseudoelement:
a:before {
content: '\a';
white-space: pre;
}
man,,, the answer is that you're basically testing PHP and not a database.
don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.
foreach ($cursor as $obj)
{
//echo $obj["thread_title"] . "<br><Br>";
}
while the other chunk is spend yacking up a bunch of rand numbers.
function get_15_random_numbers()
{
$numbers = array();
for($i=1;$i<=15;$i++)
{
$numbers[] = mt_rand(1, 20000000) ;
}
return $numbers;
}
then theres a major difference b/w implode and in.
and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.
$m = new Mongo();
vs
$db = new AQLDatabase();
so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.
urghhh.
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
For the sake of everyone and myself, here is how I use it:
def run_sql(conn_String):
output_connection = engine.create_engine(conn_string, poolclass=NullPool).connect()
rows = output_connection.execute('select * from db1.t1').fetchall()
return [dict(row) for row in rows]
Here's a quick two-liner that I use to quickly create a file if it doesn't exists.
if not os.path.exists(filename):
open(filename, 'w').close()
I think this will do:
$('#'+div_id+' .widget-head > span').text("new dialog title");
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
I figured it out through trial and error... the real chink in the armor was a little known setting in IIS in the Configuration Editor
for the website in
Section: system.webServer/security/authentication/windowsAuthentication
From: ApplicationHost.config <locationpath='ServerName/SiteName' />
called useAppPoolCredentials
(which is set to False
by default. Set this to True
and life becomes great again!!! Hope this saves pain for the next guy....
This is always fascinating. I am not a cloud developer, but based on my research there is nothing significantly different than what many of us have been doing off and on for decades. The server is platform specific. If you want to write platform agnostic code for your server that is fine, but unnecessary based on whoever your cloud server provider is. I think the biggest difference I've seen so far is the concept of providing a large set of services for the front end client to process. the front end, I'm assuming is predominantly web or web app development. As most browsers can handle LAMP vs Microsoft stack well enough, then you are still back to whatever your flavor of the month is. The only difference I truly am seeing from what I did 20 years ago in a highly distributed network environment are higher level protocol (HTTP vs. TCP/UDP). Maybe I am wrong and would welcome the education, but then again I've been doing this a long time and still have not seen anything I would consider revolutionary or significantly different, though languages like Java, C#, Python, Ruby, etc are significantly simpler to program in which is a mixed bag as the bar is lowered for those are are not familiar with writing optimized code. PAAS and SAAS to me seem to be some of the keys in the new technology, but been doing some of this to off and on for 20 years :)
os.path.dirname
is what you are looking for -
os.path.dirname(r"C:\folder1\folder2\filename.xml")
Make sure you prepend r
to the string so that its considered as a raw string.
Demo -
In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\\folder1\\folder2'
If you just want folder2
, you can use os.path.basename
with the above, Example -
os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Demo -
In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'
You can do git push --force
but be aware that you are rewriting history and anyone using the repo will have issue with this.
If you want to prevent this problem, don't use reset, but instead use git revert
A bit late here, but none of the above seemed to work. Try this, using printf, inserts spaces between each. I chose to not have newline at the end.
awk '{for(i=3;i<=NF;++i) printf("%s ", $i) }'
<script type="text/javascript">_x000D_
function validateForm() {_x000D_
var a = document.forms["Form"]["answer_a"].value;_x000D_
var b = document.forms["Form"]["answer_b"].value;_x000D_
var c = document.forms["Form"]["answer_c"].value;_x000D_
var d = document.forms["Form"]["answer_d"].value;_x000D_
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
alert("Please Fill All Required Field");_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
I know it's over a year old, but calling requestFeature()
never solved my problem. In fact I don't call it at all.
It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.
AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog()
to update that view.
Another alternative is to leverage AsyncTask for dialogs.
A final solution that I used is below:
public class CustomDialog extends AlertDialog {
private View content;
public CustomDialog(Context context) {
super(context);
LayoutInflater li = LayoutInflater.from(context);
content = li.inflate(R.layout.custom_view, null);
setUpAdditionalStuff(); // do more view cleanup
setView(content);
}
private void setUpAdditionalStuff() {
// ...
}
// Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method
public void prepare() {
setTitle(R.string.custom_title);
setIcon( getIcon() );
// ...
}
}
* Some Additional notes:
You need to be in the directory of the file and then type the following into the terminal
git reset HEAD .
Assumption is that you need to reset one file only.
Try this way
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
activityIndicator.center = super_view.center;
[super_view addSubview: activityIndicator];
[activityIndicator startAnimating];
bool isPrime(int n) {
if(n <= 3)
return (n > 1)==0? false: true;
else if(n%2 == 0 || n%3 == 0)
return false;
int i = 5;
while(i * i <= n){
if(n%i == 0 || (n%(i+2) == 0))
return false;
i = i + 6;
}
return true;
}
for any number, the minimum iterations to check if the number is prime or not can be from 2 to square root of the number. To reduce the iterations, even more, we can check if the number is divisible by 2 or 3 as maximum numbers can be eliminated by checking if the number is divisible by 2 or 3. Further any prime number greater than 3 can be expressed as 6k+1 or 6k-1. So the iteration can go from 6k+1 to the square root of the number.
I didnt see this question answered:
How should I setup a default Area when the application starts?
So, here is how you can set up a default Area:
var route = routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).DataTokens = new RouteValueDictionary(new { area = "MyArea" });
Put fragment name before the activity
Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);
ng g c componentName --module=path-to-your-module-from-src-folder
example:
ng g c testComponent --module=/src/app/home/test-component/test-component.module
You can animate the scrolltop of the page with jQuery.
$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
See this site: http://papermashup.com/jquery-page-scrolling/
I find you need the following:
I have custom a dashline which support horizontal&verical dash line . code below:
public class DashedLineView extends View
{
private float density;
private Paint paint;
private Path path;
private PathEffect effects;
public DashedLineView(Context context)
{
super(context);
init(context);
}
public DashedLineView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
public DashedLineView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init(context);
}
private void init(Context context)
{
density = DisplayUtil.getDisplayDensity(context);
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(density * 4);
//set your own color
paint.setColor(context.getResources().getColor(R.color.XXX));
path = new Path();
//array is ON and OFF distances in px (4px line then 2px space)
effects = new DashPathEffect(new float[] { 4, 2, 4, 2 }, 0);
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);
paint.setPathEffect(effects);
int measuredHeight = getMeasuredHeight();
int measuredWidth = getMeasuredWidth();
if (measuredHeight <= measuredWidth)
{
// horizontal
path.moveTo(0, 0);
path.lineTo(measuredWidth, 0);
canvas.drawPath(path, paint);
}
else
{
// vertical
path.moveTo(0, 0);
path.lineTo(0, measuredHeight);
canvas.drawPath(path, paint);
}
}
}
I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.
As an example, let's get the first and "rest" components of a name:
const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });
// As array
const components = 'Surma'.split(/\s+(.*)/);
console.log(components);
_x000D_
public partial class MyTextBox : TextBox
{
[DefaultValue(false)]
[Browsable(true)]
public override bool AutoSize
{
get
{
return base.AutoSize;
}
set
{
base.AutoSize = value;
}
}
public MyTextBox()
{
InitializeComponent();
this.AutoSize = false;
}
}
How about this EXAMPLE? It seems straightforward.
final EditText txtUrl = new EditText(this);
// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");
new AlertDialog.Builder(this)
.setTitle("Moustachify Link")
.setMessage("Paste in the link of an image to moustachify!")
.setView(txtUrl)
.setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String url = txtUrl.getText().toString();
moustachify(null, url);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
Already answer, but when I took Operating Systems in college we started with an early linux kernel and added simplistic modern features (basic file systems, virtual memory, multitasking, mutexes). Good fun. You get to skip some of the REALLY crazy low level assembly only stuff for mucking w/ protected mode and page tables while still learned some of the guts.
http://kerneltrap.org/node/14002 http://kerneltrap.org/files/linux-0.01.tar.bz2
Use del
and specify the index of the element you want to delete:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
Output using the following function:
var toFixedCurrency = function(num){
var num = (num).toString();
var one = new RegExp(/\.\d{1}$/).test(num);
var two = new RegExp(/\.\d{2,}/).test(num);
var result = null;
if(one){ result = num.replace(/\.(\d{1})$/, '.$10');
} else if(two){ result = num.replace(/\.(\d{2})\d*/, '.$1');
} else { result = num*100; }
return result;
}
function test(){
var x = 0.1 * 0.2;
document.write(toFixedCurrency(x));
}
test();
Pay attention to the output toFixedCurrency(x)
.
Use this command to update react npm install --save [email protected]
Don't forget to change 16.12.0 to the latest version or the version you need to setup.
Use the powershell pipeline to get packages and remove in single statement like this
Get-Package | Uninstall-Package
if you want to uninstall selected packages follow these steps
GetPackages
to get the list of packages GetPackages
in NimbleText(For each row in the list window)(
if requiredUninstall-Package $0
(Substitute using pattern window)That be all folks.
try [h!] first but else you can do it the ugly way.
LateX is a bit hard in placing images with such constraints as it manages placing itself. What I usually do if I want a figure right in that spot is do something like|:
text in front of image here
\newpage
\figure1
\figure2
text after images here
I know it may not be the correct way to do it but it works like a charm :).
//edit
You can do the same if you want a little text at top of the page but then just use /clearpage. Of course you can also scale them a bit smaller so it does not happen anymore. Maybe the non-seen whitespace is a bit larger than you suspect, I always try to scale down my image until they do appear on the same page, just to know for sure there is not like 1% overlap only making all of this not needed.
This example program illustrates initialization of an array of C strings.
#include <stdio.h>
const char * array[] = {
"First entry",
"Second entry",
"Third entry",
};
#define n_array (sizeof (array) / sizeof (const char *))
int main ()
{
int i;
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
return 0;
}
It prints out the following:
0: First entry
1: Second entry
2: Third entry
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
Just add like this in case 1: like this
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
and put this method at end of the your class
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
In the case where you have multiple extensions this one-liner using pathlib
and str.replace
works a treat:
>>> from pathlib import Path
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
# any python version
>>> str(p).replace(extensions, "")
'/path/to/myfile'
# python>=3.9
>>> str(p).removesuffix(extensions)
'/path/to/myfile'
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
>>> new_ext = ".jpg"
>>> str(p).replace(extensions, new_ext)
'/path/to/myfile.jpg'
If you also want a pathlib
object output then you can obviously wrap the line in Path()
>>> Path(str(p).replace("".join(p.suffixes), ""))
PosixPath('/path/to/myfile')
from pathlib import Path
from typing import Union
PathLike = Union[str, Path]
def replace_ext(path: PathLike, new_ext: str = "") -> Path:
extensions = "".join(Path(path).suffixes)
return Path(str(p).replace(extensions, new_ext))
p = Path("/path/to/myfile.tar.gz")
new_ext = ".jpg"
assert replace_ext(p, new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(str(p), new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(p) == Path('/path/to/myfile')
How the hash is computed does usually not depend on the hashtable, but on the items added to it. In frameworks/base class libraries such as .net and Java, each object has a GetHashCode() (or similar) method returning a hash code for this object. The ideal hash code algorithm and the exact implementation depends on the data represented by in the object.
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
If removing postmaster.pid
does not resolve the issue, this worked for me:
cd /usr/local/var/
rm -rf postgres/
mkdir postgres
initdb --locale=C -E UTF-8 postgres/
brew services restart postgresql
Credit to @spirito_libero 's solution on this thread.
Use this to submit and close the modal at the same time
$('#form-submit').on('click', function(e){
e.preventDefault();
$('#con-close-modal').modal('toggle'); //or $('#IDModal').modal('hide');
$('#date-form').submit();
});
Just to add my two cents... I wanted to implement this when running jobs in a gitlab pipeline on a gitlab runner. The best way to do this was to use this script:
git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA
Also in my case I wanted to filter files by extension, to achieve this I used:
git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA '*.py'
After that you can for example forward this list somewhere else, a linter perhaps ;)
Hope this will help someone.
Compatibility with older browsers can be a drag, so be adviced.
If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.
Change left and right values to meet your requirement.
Thank you.
Hope this helps.
#container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
flex: 1;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
background: orange;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="column left">this is left</div>_x000D_
<div class="column center">this is center</div>_x000D_
<div class="column right">this is right</div>_x000D_
</div>
_x000D_
Using Commons Collections:
EqualPredicate nameEqlPredicate = new EqualPredicate(3);
BeanPredicate beanPredicate = new BeanPredicate("age", nameEqlPredicate);
return CollectionUtils.filter(cats, beanPredicate);
Here:
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num==10;) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
That makes it keep looping alright! That's why it isn't runnable here.
With Java9, one can make use of the iterate(int seed, IntPredicate hasNext,IntUnaryOperator next)
as follows:-
List<Integer> indexes = IntStream
.iterate(word.indexOf(c), index -> index >= 0, index -> word.indexOf(c, index + 1))
.boxed()
.collect(Collectors.toList());
System.out.printlnt(indexes);
As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.
If you want to check whether long variable is null,you can convert that into Long and check,
long longValue=null;
if(Long.valueOf(longValue)==null)
Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation
This should be as simple as:
with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
From The Documentation:
Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.
Some useful reading:
with
statementopen()
os
(particularly os.linesep
)If your using jQuery, it's parseJSON function can be used and is preferable to JavaScript's native eval()
function.
:) Your using the thread in a wrong way. Just do the following:
private void runthread()
{
splashTread = new Thread() {
@Override
public void run() {
try {
synchronized(this){
//wait 5 sec
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
//call the handler to set the text
}
}
};
splashTread.start();
}
That's it.
Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel
I would recommend to use: Git Lens.
Note: I have seen many cases on Stack Overflow where converting a Pandas Series or DataFrame to a NumPy array or plain Python lists is entirely unecessary. If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.
To quote a comment by @jpp:
In practice, there's often no need to convert the NumPy array into a list of lists.
If a Pandas DataFrame/Series won't work, you can use the built-in DataFrame.to_numpy
and Series.to_numpy
methods.
You can do it, without writing JavaScript code
<head>
<script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
<a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>
Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).
Sample snippet:
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name),
'email'=>urlencode($email)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Credits go to http://php.dzone.com. Also, don't forget to visit the appropriate page(s) in the PHP Manual
If someone is in search for a quick minimal solution,
import signal
# The code which crashes program on interruption
signal.signal(signal.SIGINT, call_this_function_if_interrupted)
# The code skipped if interrupted
Another approach which allows you to specify how many numbers you want with size
and the min
and max
values of the returned numbers
public static int getRandomInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
public static ArrayList<Integer> getRandomNonRepeatingIntegers(int size, int min,
int max) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (numbers.size() < size) {
int random = getRandomInt(min, max);
if (!numbers.contains(random)) {
numbers.add(random);
}
}
return numbers;
}
To use it returning 7 numbers between 0 and 25.
ArrayList<Integer> list = getRandomNonRepeatingIntegers(7, 0, 25);
for (int i = 0; i < list.size(); i++) {
System.out.println("" + list.get(i));
}
Thanks for the research FIRESTICK is a solution for non Android based but there's another one Im using if you guys want to try it let me know...
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP, PHILCO and TOSHIBA.
This is an old post, but I thought I should provide an illustrated answer anyway.
Use javascript's object notation. Like so:
states_dictionary={
"CT":["alex","harry"],
"AK":["liza","alex"],
"TX":["fred", "harry"]
};
And to access the values:
states_dictionary.AK[0] //which is liza
or you can use javascript literal object notation, whereby the keys not require to be in quotes:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()