public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
Quoting API on referencedColumnName:
The name of the column referenced by this foreign key column.
Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
Where this would be used?
When there is a composite PK in referenced table, then you need to specify column name you are referencing.
DP size of any device is (actual resolution / density conversion factor).
Density conversion factor for density buckets are as follows:
ldpi: 0.75
mdpi: 1.0 (base density)
hdpi: 1.5
xhdpi: 2.0
xxhdpi: 3.0
xxxhdpi: 4.0
Examples of resolution/density conversion to DP:
ldpi device of 240 X 320 px will be of 320 X 426.66 DP. 240 / 0.75 = 320 dp 320 / 0.75 = 426.66 dp
xxhdpi device of 1080 x 1920 pixels (Samsung S4, S5) will be of 360 X 640 dp. 1080 / 3 = 360 dp 1920 / 3 = 640 dp
This image show more:
For more details about DIP read here.
You just need to name the anonymous property the same on both sides
on new { t1.ProjectID, SecondProperty = true } equals
new { t2.ProjectID, SecondProperty = t2.Completed } into j1
Based on the comments of @svick, here is another implementation that might make more sense:
from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
.DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object
For me, the following CSS worked (tested in Chrome, Firefox and Safari).
There are multiple things working together:
max-height: 100%;
, max-width: 100%;
and height: auto;
, width: auto;
make the img scale to whichever dimension first reaches 100% while keeping the aspect ratioposition: relative;
in the container and position: absolute;
in the child together with top: 50%;
and left: 50%;
center the top left corner of the img in the containertransform: translate(-50%, -50%);
moves the img back to the left and top by half its size, thus centering the img in the containerCSS:
.container {
height: 48px;
width: 48px;
position: relative;
}
.container > img {
max-height: 100%;
max-width: 100%;
height: auto;
width: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
MyActivity extends AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(arrow -> onBackPressed());
}
Only a few attributes get compiler support, but one very interesting use of attributes is in AOP: PostSharp uses your bespoke attributes to inject IL into methods, allowing all manner of abilities... log/trace being trivial examples - but some other good examples are things like automatic INotifyPropertyChanged implementation (here).
Some that occur and impact the compiler or runtime directly:
[Conditional("FOO")]
- calls to this method (including argument evaluation) only occur if the "FOO" symbol is defined during build[MethodImpl(...)]
- used to indicate a few thing like synchronization, inlining[PrincipalPermission(...)]
- used to inject security checks into the code automatically[TypeForwardedTo(...)]
- used to move types between assemblies without rebuilding the callersFor things that are checked manually via reflection - I'm a big fan of the System.ComponentModel
attributes; things like [TypeDescriptionProvider(...)]
, [TypeConverter(...)]
, and [Editor(...)]
which can completely change the behavior of types in data-binding scenarios (i.e. dynamic properties etc).
Check the localhost_yyyy_mm_dd.log
OR localhost.yyyy-mm-dd.log
logs that Tomcat creates, these typically store that type of info. I wouldn't expect the full stacktrace to be dumped to standard out.
You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.
You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.
Project + Properties, C/C++, Code Generation, Runtime Library.
Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll
It can be solved by using different attribute.
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
you could either use
SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)
or
SELECT CurrencyNoDecimals = '$'+ LEFT( CONVERT(varchar, @MoneyValue,1),
LEN (CONVERT(varchar, @MoneyValue,1)) - 2)
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:
<div style="position:relative">
<div style="position:absolute; z-index: 1000;">
your code
</div>
</div>
You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.
I hope that this help
The other individuals answered the question. I want to suggest you use a JTabbedPane instead of replacing content. As a general rule, it is bad to have visual elements of your application disappear or be replaced by other content. Certainly there are exceptions to every rule, and only you and your user community can decide the best approach.
Adds vertical column guides to the Visual Studio text editor. This version is for Visual Studio 2012, Visual Studio 2013 or Visual Studio 2015.
See the plugin.
componentWillReceiveProps
is being deprecated because using it "often leads to bugs and inconsistencies".
If something changes from the outside, consider resetting the child component entirely with key
.
Providing a key
prop to the child component makes sure that whenever the value of key
changes from the outside, this component is re-rendered. E.g.,
<EmailInput
defaultEmail={this.props.user.email}
key={this.props.user.id}
/>
On its performance:
While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.
Angular v2 doesn't support more than one structural directive on the same element.
As a workaround use the <ng-container>
element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.
<ng-container *ngIf="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-container>
<ng-template>
(<template>
before Angular v4) allows to do the same but with a different syntax which is confusing and no longer recommended
<ng-template [ngIf]="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-template>
It looks like request_uri
is deprecated in Ruby on Rails 3.
Using #request_uri is deprecated. Use fullpath instead.
DEPLOYABLE SOLUTION (Alpine Linux)
To be able to fix this issue in our application environments, we have prepared Linux terminal commands as follows:
cd ~
Will generate cert file in home directory.
apk add openssl
This command installs openssl in alpine Linux. You can find proper commands for other Linux distributions.
openssl s_client -connect <host-dns-ssl-belongs> < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > public.crt
Generated the needed cert file.
sudo $JAVA_HOME/bin/keytool -import -alias server_name -keystore $JAVA_HOME/lib/security/cacerts -file public.crt -storepass changeit -noprompt
Applied the generated file to the JRE with the program 'keytool'.
Note: Please replace your DNS with <host-dns-ssl-belongs>
Note2: Please gently note that -noprompt
will not prompt the verification message (yes/no) and -storepass changeit
parameter will disable password prompt and provide the needed password (default is 'changeit'). These two properties will let you use those scripts in your application environments like building a Docker image.
Note3 If you are deploying your app via Docker, you can generate the secret file once and put it in your application project files. You won't need to generate it again and again.
You can use the below statement to get the inserted Id to a variable-like thing.
INSERT INTO YOUR_TABLE(ID) VALUES ('10') returning ID into :Inserted_Value;
Now you can retrieve the value using the below statement
SELECT :Inserted_Value FROM DUAL;
You can just open cygwin terminal and write: cd and after drag n drop the folder you want end enter!
Generally to get the current week number (starts from Sunday):
from datetime import *
today = datetime.today()
print today.strftime("%U")
(left, upper, right, lower) means two points,
with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).
So, for cutting the image half:
from PIL import Image
img = Image.open("ImageName.jpg")
img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)
img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)
img_left.show()
img_right.show()
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
CSS file
.selectDD {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
JS file
$(document).ready(function () {
$("#selectDropdownID").next().children().eq(0).addClass("selectDD");
});
int cores = Runtime.getRuntime().availableProcessors();
If cores
is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.
WAMP stores the db data under WAMP\bin\mysql\mysql(version)\data
. Where the WAMP folder itself is depends on where you installed it to (on xp, I believe it is directly in the main drive, for example c:\WAMP\...
If you deleted that folder, or if the uninstall deleted that folder, if you did not do a DB backup before the uninstall, you may be out of luck.
If you did do a backup though phpmyadmin, then login, and click the import tab, and browse to the backup file.
This is an old question, but since it still comes up at the top of my results in Google, here's another way.
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))
Say you want to replicate the rows where col1="b".
reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]
You could replace the 3 if val=="b" else 1
in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.
To call a sub inside another sub you only need to do:
Call Subname()
So where you have CalculateA(Nc,kij, xi, a1, a)
you need to have call CalculateA(Nc,kij, xi, a1, a)
As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...)
cause this way it does not appear in the macro list and it's easier to work
Hope it helps, Bruno
PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."
at new chrome version (maybe 67.0.3396.62) , CSS hex color can use this model display,
eg:
div{
background-color:#FF00FFcc;
}
cc is opacity , but old chrome not support that mod
You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.
Alternatively, I checked the pom.xml and changed
<java.version>1.8</java.version>
to
<java.version>1.7</java.version>
This is the answer.
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
AutoCompleteType="Disabled"
If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go
'Options' --> 'Security'(tab) --> Untick
'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.
This should solve the problem
I would use .*
. .
matches any character, *
signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with .
.
You can use:
if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
{
//do code here
}
or
if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
{
//do code here
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
I did it using Extension Functions
in kotlin
fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)
}
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}
Usage:
"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")
Output: "11 Sep 2018"
Note:
Ensure the proper validation.
I had this problem and after check my code line by line i saw this
<textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"/>
i just changed it to
<textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"></textarea>
and it's worked. so check your tags.
You can define a simple method like:
public enum Alphabet{
A,B,C,D;
public static Alphabet get(int index){
return Alphabet.values()[index];
}
}
And use it like:
System.out.println(Alphabet.get(2));
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
This video shows how to update a fork directly from GitHub
Steps:
Pull Requests
.New Pull Request
. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.switching the base
. Now GitHub will compare your fork with the original, and you should see all the latest changes.Create a pull request
for this comparison and assign a predictable name to your pull request (e.g., Update from original).Create pull request
.Merge pull request
and finally Confirm
merge. If your fork didn’t have any changes, you will be able to merge it automatically.You can use y.count()
.
It will return the integer value of the number of times a sub string appears in a string.
For example:
string.count("bah") >> 0
string.count("Hello") >> 1
This doesn't have the regex overhead
double myNum = 0;
String testVar = "Not A Number";
if (Double.TryParse(testVar, out myNum)) {
// it is a number
} else {
// it is not a number
}
Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.
update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.
example 1:
public Boolean IsNumber(String s) {
Boolean value = true;
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
return value;
}
or if you want to be a little more fancy
public Boolean IsNumber(String value) {
return value.All(Char.IsDigit);
}
update 2 ( from @stackonfire to deal with null or empty strings)
public Boolean IsNumber(String s) {
Boolean value = true;
if (s == String.Empty || s == null) {
value=false;
} else {
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
} return value;
}
The dplyr
select
function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by
function. For example:
library(dplyr)
# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))
# Return the distinct values of x
dat %>%
group_by(x) %>%
summarise()
x
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
If you want to change the column name you can add the following:
dat %>%
group_by(x) %>%
summarise() %>%
select(unique.x=x)
This both selects column x
from among all the columns in the data frame that dplyr
returns (and of course there's only one column in this case) and changes its name to unique.x
.
You can also get the unique values directly in base R
with unique(dat$x)
.
If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE),
y=sample(letters[1:5], 100, replace=TRUE))
dat %>%
group_by(x,y) %>%
summarise() %>%
select(unique.x=x, unique.y=y)
Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression
select datediff(dd,Invdate,'2009/01/31')+1 as DaysOld,
case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else
case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else
case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end
end
end
end
end
end as Bucket
from rm20090131atb
Just make sure you have an end statement for every case statement
Executing:
java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);
before hibernate's initialization worked for me.
Note: the line above will turn every logging off (Level.OFF
). If you want to be less strict, you can use
java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
that is silent enough. (Or check the java.util.logging.Level
class for more levels).
To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.
<select class="form-control glyphicon">
<option value="">− − − Hello</option>
<option value="glyphicon-list-alt"> Text</option>
</select>
Here's a list of the icons with their unicode:
Yes, you can script using the reg
command.
Example:
reg add HKCU\Software\SomeProduct
reg add HKCU\Software\SomeProduct /v Version /t REG_SZ /d v2.4.6
This would create key HKEY_CURRENT_USER\Software\SomeProduct
, and add a String value "v2.4.6" named "Version" to that key.
reg /?
has the details.
Create the Button
and add it to Form.Controls
list to display it on your form:
Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45); //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list
Create the button click method here:
void buttonOk_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
this.Close(); //all your choice to close it or remove this line
}
You have several options ;)
$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');
I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.
To create circles
new BoxDecoration(
color: effectiveBackgroundColor,
image: backgroundImage != null
? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
: null,
shape: BoxShape.circle,
),
and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.
It would be O(n log n) if you built the heap by repeatedly inserting elements. However, you can create a new heap more efficiently by inserting the elements in arbitrary order and then applying an algorithm to "heapify" them into the proper order (depending on the type of heap of course).
See http://en.wikipedia.org/wiki/Binary_heap, "Building a heap" for an example. In this case you essentially work up from the bottom level of the tree, swapping parent and child nodes until the heap conditions are satisfied.
Using VS2017 Enterprise:
The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip
All what you must do is:
Enable the module:
LoadModule remoteip_module modules/mod_remoteip.so
Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):
RemoteIPHeader X-Forwarded-For
See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws: SecurityException - if the current thread cannot modify this thread
In-order, Pre-order, and Post-order traversals are Depth-First traversals.
For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.
Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).
Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.
The complexity then becomes O(n + n-1), which is O(n).
Here is what worked for me:
If you are installing on a 64-bit machine, make sure the application properties under the Build tab have "Any CPU" as the platform target, and unselect the check box for "Prefer 32-bit" if you have the option. Crystal is very touchy about 32/64 bit assemblies, and makes some pretty counterintuitive assumptions which are very difficult to troubleshoot.
After doing all of above I still couldn't login as root
remotely, but Telnetting to port 3306
confirmed that MySQL
was accepting connections.
I started looking at the users in MySQL and noticed there were multiple root users with different passwords.
select user, host, password from mysql.user;
So in MySQL
I set all the passwords for root again and I could finally log in remotely as root
.
use mysql;
update user set password=PASSWORD('NEWPASSWORD') where User='root';
flush privileges;
Simple is that
Like:
DECLARE @DUENO BIGINT
SET @DUENO=5
SELECT 'ND'+STUFF('000000',6-LEN(RTRIM(@DueNo))+1,LEN(RTRIM(@DueNo)),RTRIM(@DueNo)) DUENO
Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."
This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.
Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.
You might find this link helpful:
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
To replace the first match of $substring with $replacement:
${string/substring/replacement}
To replace all matches of $substring with $replacement:
${string//substring/replacement}
EDIT: Note that this applies to a variable named $string.
Here are a couple basic examples to get started quick and dirty.
Set variable:
SET(INSTALL_ETC_DIR "etc")
Use variable:
SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")
Set variable:
SET(PROGRAM_SRCS
program.c
program_utils.c
a_lib.c
b_lib.c
config.c
)
Use variable:
add_executable(program "${PROGRAM_SRCS}")
From a post by Robert Martin in comp.object:
Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.
//[Example:]
//|A|----------->|B|
class A
{
private:
B* itsB;
};
Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).
//[Example:]
//|Node|<>-------->|Node|
class Node
{
private:
vector<Node*> itsNodes;
};
The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
//[Example:]
//|Car|<#>-------->|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};
I had a similar issue, glob
was returning a list of file names in an arbitrary order but I wanted to step through them in numerical order as indicated by the file name. This is how I achieved it:
My files were returned by glob
something like:
myList = ["c:\tmp\x\123.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\12.csv"]
I sorted the list in place, to do this I created a function:
def sortKeyFunc(s):
return int(os.path.basename(s)[:-4])
This function returns the numeric part of the file name and converts to an integer.I then called the sort method on the list as such:
myList.sort(key=sortKeyFunc)
This returned a list as such:
["c:\tmp\x\12.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\123.csv"]
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))
first you need to import Sum then ..
Use itertools.chain:
itertools.chain(*iterables)
:Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
In Bootstrap 3, .form-control
(the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:
<div class="row">
<div class="col-lg-2">
<input type="text" class="form-control" placeholder=".col-lg-2">
</div>
<div class="col-lg-3">
<input type="text" class="form-control" placeholder=".col-lg-3">
</div>
<div class="col-lg-4">
<input type="text" class="form-control" placeholder=".col-lg-4">
</div>
</div>
See under Column sizing.
It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.
Excerpt from K&R:
short
is often 16 bits,long
32 bits andint
either 16 bits or 32 bits. Each compiler is free to choose appropriate sizes for its own hardware, subject only to the restriction thatshort
s andint
s are at least 16 bits,long
s are at least 32 bits, andshort
is no longer thanint
, which is no longer thanlong
.
You can make use of limits.h
that contains the definition of the limits for the decimal/float types:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
int main(int argc, char** argv) {
printf("CHAR_BIT : %d\n", CHAR_BIT);
printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("INT_MAX : %d\n", INT_MAX);
printf("INT_MIN : %d\n", INT_MIN);
printf("LONG_MAX : %ld\n", (long) LONG_MAX);
printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("SHRT_MAX : %d\n", SHRT_MAX);
printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);
printf("FLT_MAX : %g\n", (float) FLT_MAX);
printf("FLT_MIN : %g\n", (float) FLT_MIN);
printf("-FLT_MAX : %g\n", (float) -FLT_MAX);
printf("-FLT_MIN : %g\n", (float) -FLT_MIN);
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
return (EXIT_SUCCESS);
}
Maybe you might have to tweak a little bit on your machine, but it is a good template to start to get an idea of the (implementation-defined) min and max values.
You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass
You can run Xcode on Linux NATIVELY using Darling:
Darling is a translation layer that lets you run macOS software on Linux
Once installed you can install Xcode via command-line developer tool following this link.
Short answer:
try using reimport: a full featured reload for Python.
Longer answer:
It looks like this question was asked/answered prior to the release of reimport, which bills itself as a "full featured reload for Python":
This module intends to be a full featured replacement for Python's reload function. It is targeted towards making a reload that works for Python plugins and extensions used by longer running applications.
Reimport currently supports Python 2.4 through 2.6.
By its very nature, this is not a completely solvable problem. The goal of this module is to make the most common sorts of updates work well. It also allows individual modules and package to assist in the process. A more detailed description of what happens is on the overview page.
Note: Although the reimport
explicitly supports Python 2.4 through 2.6, I've been trying it on 2.7 and it seems to work just fine.
From the documentation of InetAddress.getByName(String host)
:
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
So you can use it.
A 302 redirect means that the page was temporarily moved, while a 301 means that it was permanently moved.
301s are good for SEO value, while 302s aren't because 301s instruct clients to forget the value of the original URL, while the 302 keeps the value of the original and can thus potentially reduce the value by creating two, logically-distinct URLs that each produce the same content (search engines view them as distinct duplicates rather than a single resource with two names).
Command find_package
has two modes: Module
mode and Config
mode. You are trying to
use Module
mode when you actually need Config
mode.
Find<package>.cmake
file located within your project. Something like this:
CMakeLists.txt
cmake/FindFoo.cmake
cmake/FindBoo.cmake
CMakeLists.txt
content:
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES
find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES
include_directories("${FOO_INCLUDE_DIR}")
include_directories("${BOO_INCLUDE_DIR}")
add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})
Note that CMAKE_MODULE_PATH
has high priority and may be usefull when you need to rewrite standard Find<package>.cmake
file.
<package>Config.cmake
file located outside and produced by install
command of other project (Foo
for example).
foo
library:
> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Foo)
add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)
Simplified version of config file:
> cat FooConfig.cmake
add_library(foo STATIC IMPORTED)
find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../")
set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}")
By default project installed in CMAKE_INSTALL_PREFIX
directory:
> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake
Use find_package(... CONFIG)
to include FooConfig.cmake
with imported target foo
:
> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Boo)
# import library target `foo`
find_package(Foo CONFIG REQUIRED)
add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a
Note that imported target is highly configurable. See my answer.
Update
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
Width:100%
and text-align:center
would work in my experience
<p style="display:block; line-height: 70px; width:100%; text-align:center; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
Angular lately introduced a new feature, inside angular routing module make changes like below
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'top'
})],
Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.
Use the most basic of type inference that python has:
>>> # Float Check
>>> myNumber = 2.56
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
True
>>> print(type(myNumber) == bool)
False
>>>
>>> # Integer Check
>>> myNumber = 2
>>> print(type(myNumber) == int)
True
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
False
>>>
>>> # Boolean Check
>>> myNumber = False
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
True
>>>
Easiest and Most Resilient Approach in my Opinion
string.Format("{0}", myObj);
string.Format will format null as an empty string and call ToString() on non-null objects. As I understand it, this is what you were looking for.
I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone
It is same as below:
def tag_names
if @tag_names
@tag_names
else
tags.map{ |t| t.name }.join(' ')
end
If you pass a variable data
(dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
you dont need those quotes
<td style="padding-left: 5px;padding-bottom:3px; font-size: 35px;"> <b>Datum:</b><br/>
November 2010 </td>
$.ajax({
type: "GET",
url: '<?php echo Base_url("user/your function");?>',
data: {name: mail},
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'chekEmailTaken',
success: function(msg){
}
});
return true;
In controller:
public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';
}
Question is too old and my answer might not add much but here are my two cents for making query a little useful:
;WITH DistinctRecords AS (
SELECT DISTINCT [col1,col2,col3,..]
FROM tableName
where [my condition]
),
serialize AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY [colNameAsNeeded] ORDER BY [colNameNeeded]) AS Sr,*
FROM DistinctRecords
)
SELECT * FROM serialize
Usefulness of using two cte's lies in the fact that now you can use serialized record much easily in your query and do count(*)
etc very easily.
DistinctRecords
will select all distinct records and serialize
apply serial numbers to distinct records. after wards you can use final serialized result for your purposes without clutter.
Partition By
might not be needed in most cases
Here is a possible solution the solution #3 on my comments to blubill's answer:
yourscript.php
========================
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false)
{
echo 'Directory "', $dir, '" not found!';
}
else
{
$dir_contents = scandir($dir);
foreach ($dir_contents as $file)
{
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)
{
$name = basename($file);
echo "<img src='img.php?name={$name}' />";
}
}
}
?>
img.php
========================
<?php
$name = $_GET['name'];
$mimes = array
(
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$ext = strtolower(end(explode('.', $name)));
$file = '/home/users/Pictures/'.$name;
header('content-type: '. $mimes[$ext]);
header('content-disposition: inline; filename="'.$name.'";');
readfile($file);
?>
I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:
Under Conditional Formatting > Manage Rules:
$A2<$B2
$B$2:$B$100
(assuming you have 100 rows)This worked for me in Excel 2016.
There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.
There is method:
private void zzo(Intent intent) {
Bundle bundle = intent.getExtras();
bundle.remove("android.support.content.wakelockid");
if (zza.zzac(bundle)) { // true if msg is notification sent from FirebaseConsole
if (!zza.zzdc((Context)this)) { // true if app is on foreground
zza.zzer((Context)this).zzas(bundle); // create notification
return;
}
// parse notification data to allow use it in onMessageReceived whe app is on foreground
if (FirebaseMessagingService.zzav(bundle)) {
zzb.zzo((Context)this, intent);
}
}
this.onMessageReceived(new RemoteMessage(bundle));
}
This code is from version 9.4.0, method will have different names in different version because of obfuscation.
If you want to return the original string untouched if it does not contain the search character then you can use an anonymous function (a closure):
var streetaddress=(function(s){var i=s.indexOf(',');
return i==-1 ? s : s.substr(0,i);})(addy);
This can be made more generic:
var streetaddress=(function(s,c){var i=s.indexOf(c);
return i==-1 ? s : s.substr(0,i);})(addy,',');
This works good for me.
PID=`ps -eaf | grep syncapp | grep -v grep | awk '{print $2}'` if [[ "" != "$PID" ]]; then echo "killing $PID" kill -9 $PID fi
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
This is old question but still my answer may help someone
For checking Java version in android studio version , simply open Terminal of Android Studio and type
java -version
This will display java version installed in android studio
I think it would be smart to only show the hand/pointer cursor when JavaScript is available. So people will not have the feeling they can click on something that is not clickable.
To achieve that you could use the JavaScript libary jQuery to add the CSS to the element like so
$("li").css({"cursor":"pointer"});
Or chain it directly to the click handler.
Or when modernizer in combination with <html class="no-js">
is used, the CSS would look like this:
.js li { cursor: pointer; }
Bit late to the party, but this will get it done. I left the example at 600, as that is what most people will use:
Similar to Shay's example except this also includes max-width to work on the rest of the clients that do have support, as well as a second method to prevent the expansion (media query) which is needed for Outlook '11.
In the head:
<style type="text/css">
@media only screen and (min-width: 600px) { .maxW { width:600px !important; } }
</style>
In the body:
<!--[if (gte mso 9)|(IE)]><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<div class="maxW" style="max-width:600px;">
<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td>
main content here
</td>
</tr>
</table>
</div>
<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->
Here is another example of this in use: Responsive order confirmation emails for mobile devices?
If You want get date defer from using table and column.
SELECT TO_DATE( TO_CHAR(COLUMN_NAME_1, 'YYYY-MM-DD'), 'YYYY-MM-DD') -
TO_DATE(TO_CHAR(COLUMN_NAME_2, 'YYYY-MM-DD') , 'YYYY-MM-DD') AS DATEDIFF
FROM TABLE_NAME;
If someone uses jquery, he can do it like this :
var click_count = 0;
$( "canvas" ).bind( "click", function( event ) {
//do whatever you want
click_count++;
if ( click_count == 50 ) {
//remove the event
$( this ).unbind( event );
}
});
Hope that it can help someone. Note that the answer given by @user113716 work nicely :)
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
Simply:
listPreference.setSummary("%s");
You need to escape the backslash \
:
println yourString.replace("\\", "/")
If you are using C++ and don't want/can't use Boost, you can print backtrace with demangled names using the following code [link to the original site].
Note, this solution is specific to Linux. It uses GNU's libc functions backtrace()/backtrace_symbols() (from execinfo.h) to get the backtraces and then uses __cxa_demangle() (from cxxabi.h) for demangling the backtrace symbol names.
// stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/
// published under the WTFPL v2.0
#ifndef _STACKTRACE_H_
#define _STACKTRACE_H_
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <cxxabi.h>
/** Print a demangled stack backtrace of the caller function to FILE* out. */
static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames = 63)
{
fprintf(out, "stack trace:\n");
// storage array for stack trace address data
void* addrlist[max_frames+1];
// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if (addrlen == 0) {
fprintf(out, " <empty, possibly corrupt>\n");
return;
}
// resolve addresses into strings containing "filename(function+address)",
// this array must be free()-ed
char** symbollist = backtrace_symbols(addrlist, addrlen);
// allocate string which will be filled with the demangled function name
size_t funcnamesize = 256;
char* funcname = (char*)malloc(funcnamesize);
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 1; i < addrlen; i++)
{
char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for (char *p = symbollist[i]; *p; ++p)
{
if (*p == '(')
begin_name = p;
else if (*p == '+')
begin_offset = p;
else if (*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset
&& begin_name < begin_offset)
{
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name,
funcname, &funcnamesize, &status);
if (status == 0) {
funcname = ret; // use possibly realloc()-ed string
fprintf(out, " %s : %s+%s\n",
symbollist[i], funcname, begin_offset);
}
else {
// demangling failed. Output function name as a C function with
// no arguments.
fprintf(out, " %s : %s()+%s\n",
symbollist[i], begin_name, begin_offset);
}
}
else
{
// couldn't parse the line? print the whole line.
fprintf(out, " %s\n", symbollist[i]);
}
}
free(funcname);
free(symbollist);
}
#endif // _STACKTRACE_H_
HTH!
raw_input()
takes exactly what the user typed and passes it back as a string.
input()
first takes the raw_input()
and then performs an eval()
on it as well.
The main difference is that input()
expects a syntactically correct python statement where raw_input()
does not.
raw_input()
was renamed to input()
so now input()
returns the exact string.input()
was removed. If you want to use the old input()
, meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input())
.
Simple solution without adding observer notification
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}
-(void)textFieldDidEndEditing:(UITextField *)sender
{
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:NO];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
}
Where
#define kOFFSET_FOR_KEYBOARD 80.0
You must know the full path of your angular installation. For example: C:\Users\\AppData\Roaming\npm\node_modules@angular\cli\bin\ng . Type in cmd, powershell or bash
alias ng="C:\Users\<your username>\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng"
Here's what I think is a better method:
public int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
EDIT
Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class YearsBetweenDates {
public static int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
private static class TestCase {
public Calendar date1;
public Calendar date2;
public int expectedYearDiff;
public String comment;
public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
this.date1 = date1;
this.date2 = date2;
this.expectedYearDiff = expectedYearDiff;
this.comment = comment;
}
}
private static TestCase[] tests = {
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2015, Calendar.JULY, 15),
1,
"exactly one year"),
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 14),
2,
"one day less than 3 years"),
new TestCase(
new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
new GregorianCalendar(2017, Calendar.MAY, 3),
1,
"a year and a half"),
new TestCase(
new GregorianCalendar(2016, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 15),
1,
"leap years do not compare correctly"),
};
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (TestCase t : tests) {
int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
System.out.println(t.comment + ": " +
df.format(t.date1.getTime()) + " -> " +
df.format(t.date2.getTime()) + " = " +
diff + ": " + result);
}
}
}
You just have to define that Animal implements Comparable<Animal>
i.e. public class Animal implements Comparable<Animal>
. And then you have to implement the compareTo(Animal other)
method that way you like it.
@Override
public int compareTo(Animal other) {
return Integer.compare(this.year_discovered, other.year_discovered);
}
Using this implementation of compareTo
, animals with a higher year_discovered
will get ordered higher. I hope you get the idea of Comparable
and compareTo
with this example.
Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.
import inspect, os
class ClassOne:
def method1(self):
classtwoObj.method2()
class ClassTwo:
def method2(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print '\nI was called from', calframe[1][3], \
'in', calframe[1][4][0][6: -2]
# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()
# start the program
os.system('cls')
classoneObj.method1()
Remember set sendfile off;
or cache headers doesn't work.
I use this snipped:
location / {
index index.php index.html index.htm;
try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular
#.s. kill cache. use in dev
sendfile off;
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_no_cache 1;
proxy_cache_bypass 1;
}
If you are facing problem with pip3 install pyqt5
then try pip3 install pyqt5==5.12.0
This solved the problem for me
\d+(,\d+)*(\.\d+)?
This assumes that there is always at least one digit before or after any comma or decimal and also assumes that there is at most one decimal and that all the commas precede the decimal.
First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".
Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.
Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.
What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl()
- the container finds each injection point and sets an instance there.
In your controllers, you just have the following:
@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {
// Tells the application context to inject an instance of UserService here
@Autowired
private UserService userService;
@RequestMapping("/login")
public void login(@RequestParam("username") String username,
@RequestParam("password") String password) {
// The UserServiceImpl is already injected and you can use it
userService.login(username, password);
}
}
A few notes:
applicationContext.xml
you should enable the <context:component-scan>
so that classes are scanned for the @Controller
, @Service
, etc. annotations.UserServiceImpl
should also be defined as bean - either using <bean id=".." class="..">
or using the @Service
annotation. Since it will be the only implementor of UserService
, it will be injected.@Autowired
annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject
, @Resource
can also be used.Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
You can use the javascript Promise
and async/await
to implement a synchronized call of the functions.
Suppose you want to execute n
number of functions in a synchronized manner that are stored in an array, here is my solution for that.
async function executeActionQueue(funArray) {_x000D_
var length = funArray.length;_x000D_
for(var i = 0; i < length; i++) {_x000D_
await executeFun(funArray[i]);_x000D_
}_x000D_
};_x000D_
_x000D_
function executeFun(fun) {_x000D_
return new Promise((resolve, reject) => {_x000D_
_x000D_
// Execute required function here_x000D_
_x000D_
fun()_x000D_
.then((data) => {_x000D_
// do required with data _x000D_
resolve(true);_x000D_
})_x000D_
.catch((error) => {_x000D_
// handle error_x000D_
resolve(true);_x000D_
});_x000D_
})_x000D_
};_x000D_
_x000D_
executeActionQueue(funArray);
_x000D_
with performance in mind, you'd better use typeof with a typical hardware, if you create a script with a loop of 10 million iterations the instruction: typeof str == 'string' will take 9ms while 'string' instanceof String will take 19ms
In my case, the issue was caused by a connection problem to the SQL database. I just disconnected and then reconnected the SQL datasource from the design view. I am back up and running. Hope this works for everyone.
There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.
You need to concatenate multiple variables:
header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
Add the frameBorder attribute (Capital ‘B’).
<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible. </iframe>
For special characters:
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
You may use gitignore for advanced gitignore file generation. It's fast, easy and cutting edge tags are automatically generated for you.
Use this link for most of jetbrains softwares (intelij, phpstorm...) jetbrains .gitignore file
[edit]
Below is the generated gitignore file for Jetbrains Softwares, this will prevent you from sharing sensitive informations (passwords, keystores, db passwords...) used by any of Jetbrains software to manage projects.
# Created by https://www.gitignore.io
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
Generated code is also well commented. hope it helps :)
if you just want to disable submit on enter and submit button too use form's onsubmit event
<form onsubmit="return false;">
You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:
config.Save(ConfigurationSaveMode.Modified);
Without this, the new value was still being written to the config file but the old value was retrieved when debugging.
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
Reminder inst = Reminder.instance();
inst.setAlarmText("");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
The easiest way is to use date
, which lets you mix hard-coded values with ones extracted from a timestamp. If you don't give a timestamp, it assumes the current date and time.
// Current timestamp is assumed, so these find first and last day of THIS month
$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month = date('m-t-Y');
// With timestamp, this gets last day of April 2010
$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));
date()
searches the string it's given, like 'm-t-Y'
, for specific symbols, and it replaces them with values from its timestamp. So we can use those symbols to extract the values and formatting that we want from the timestamp. In the examples above:
Y
gives you the 4-digit year from the timestamp ('2010')m
gives you the numeric month from the timestamp, with a leading zero ('04')t
gives you the number of days in the timestamp's month ('30')You can be creative with this. For example, to get the first and last second of a month:
$timestamp = strtotime('February 2012');
$first_second = date('m-01-Y 00:00:00', $timestamp);
$last_second = date('m-t-Y 12:59:59', $timestamp); // A leap year!
See http://php.net/manual/en/function.date.php for other symbols and more details.
0x7ffffff's answer is ok and definitely exhaustive.
As a plus, I suggest you to make an UIView extension, in this way:
public extension UIView {
/**
Fade in a view with a duration
- parameter duration: custom animation duration
*/
func fadeIn(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 1.0
})
}
/**
Fade out a view with a duration
- parameter duration: custom animation duration
*/
func fadeOut(duration duration: NSTimeInterval = 1.0) {
UIView.animateWithDuration(duration, animations: {
self.alpha = 0.0
})
}
}
Swift-3
/// Fade in a view with a duration
///
/// Parameter duration: custom animation duration
func fadeIn(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 1.0
})
}
/// Fade out a view with a duration
///
/// - Parameter duration: custom animation duration
func fadeOut(withDuration duration: TimeInterval = 1.0) {
UIView.animate(withDuration: duration, animations: {
self.alpha = 0.0
})
}
In this way you can do this wherever in your code:
let newImage = UIImage(named: "")
newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0)
self.view.addSubview(newImage)
...
newImage.fadeIn()
Code reuse is important!
Here's another solution using display: flex instead of position: absolute or display: grid.
.container_row{_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
width: 100%;_x000D_
background-color: rgba(255,0,0,0.5); // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
width: 100%;_x000D_
margin-left: -100%;_x000D_
background-color: rgba(0,0,255,0.5); // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
<div class="layer1">_x000D_
<span>Lorem ipsum...</span>_x000D_
</div>_x000D_
<div class="layer2">_x000D_
More lorem ipsum..._x000D_
</div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
Reset and sync local repository with remote branch
The command: Remember to replace origin and master with the remote and branch that you want to synchronize with.
git fetch origin && git reset --hard origin/master && git clean -f -d
Or step-by-step:
git fetch origin
git reset --hard origin/master
git clean -f -d
Your local branch is now an exact copy (commits and all) of the remote branch.
Command output:
Here is an example of running the command on a local clone of the Forge a git repository.
sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
I might be too late to answer this question, but wanted to share my input for the benefit of the community. For this example, let me call your matrix 'ANOVA', and I am assuming you're just trying to remove rows from this matrix with 0's only in the 5th column.
indx = []
for i in range(len(ANOVA)):
if int(ANOVA[i,4]) == int(0):
indx.append(i)
ANOVA = [x for x in ANOVA if not x in indx]
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
boolean isBeforeToday(Date d) {
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return d.before(today);
}
New introduction 2
In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.
This macro, outputs the name of the store holding the default Inbox to the Immediate Window:
Sub DsplUsernameOfDefaultStore()
Dim NS As Outlook.NameSpace
Dim DefaultInboxFldr As MAPIFolder
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)
Debug.Print DefaultInboxFldr.Parent.Name
End Sub
On my installation, this outputs: "Outlook Data File".
I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.
New introduction 1
A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.
The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)
Original text
There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.
For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.
What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.
The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.
The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:
Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.
All other comments containing hashes suggest amendments to adapt the macro to your requirements.
How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed"
.
The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.
This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:
Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on
Extracting the values from the original of this string should not be difficult.
I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.
Good luck.
Latest version of macro included within the original text
Option Explicit
Public Sub SaveEmailDetails()
' This macro creates a new Excel workbook and writes to it details
' of every email in the Inbox.
' Lines starting with hashes either MUST be changed before running the
' macro or suggest changes you might consider appropriate.
Dim AttachCount As Long
Dim AttachDtl() As String
Dim ExcelWkBk As Excel.Workbook
Dim FileName As String
Dim FolderTgt As MAPIFolder
Dim HtmlBody As String
Dim InterestingItem As Boolean
Dim InxAttach As Long
Dim InxItemCrnt As Long
Dim PathName As String
Dim ReceivedTime As Date
Dim RowCrnt As Long
Dim SenderEmailAddress As String
Dim SenderName As String
Dim Subject As String
Dim TextBody As String
Dim xlApp As Excel.Application
' The Excel workbook will be created in this folder.
' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
PathName = "C:\DataArea\SO"
' This creates a unique filename.
' #### If you use a version of Excel 2003, change the extension to "xls".
FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"
' Open own copy of Excel
Set xlApp = Application.CreateObject("Excel.Application")
With xlApp
' .Visible = True ' This slows your macro but helps during debugging
.ScreenUpdating = False ' Reduces flash and increases speed
' Create a new workbook
' #### If updating an existing workbook, replace with an
' #### Open workbook statement.
Set ExcelWkBk = xlApp.Workbooks.Add
With ExcelWkBk
' #### None of this code will be useful if you are adding
' #### to an existing workbook. However, it demonstrates a
' #### variety of useful statements.
.Worksheets("Sheet1").Name = "Inbox" ' Rename first worksheet
With .Worksheets("Inbox")
' Create header line
With .Cells(1, "A")
.Value = "Field"
.Font.Bold = True
End With
With .Cells(1, "B")
.Value = "Value"
.Font.Bold = True
End With
.Columns("A").ColumnWidth = 18
.Columns("B").ColumnWidth = 150
End With
End With
RowCrnt = 2
End With
' FolderTgt is the folder I am going to search. This statement says
' I want to seach the Inbox. The value "olFolderInbox" can be replaced
' to allow any of the standard folders to be searched.
' See FindSelectedFolder() for a routine that will search for any folder.
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
' #### Use the following the access a non-default Inbox.
' #### Change "Xxxx" to name of one of your store you want to access.
Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")
' This examines the emails in reverse order. I will explain why later.
For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
With FolderTgt.Items.Item(InxItemCrnt)
' A folder can contain several types of item: mail items, meeting items,
' contacts, etc. I am only interested in mail items.
If .Class = olMail Then
' Save selected properties to variables
ReceivedTime = .ReceivedTime
Subject = .Subject
SenderName = .SenderName
SenderEmailAddress = .SenderEmailAddress
TextBody = .Body
HtmlBody = .HtmlBody
AttachCount = .Attachments.Count
If AttachCount > 0 Then
ReDim AttachDtl(1 To 7, 1 To AttachCount)
For InxAttach = 1 To AttachCount
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
Select Case .Attachments(InxAttach).Type
Case olByValue
AttachDtl(1, InxAttach) = "Val"
Case olEmbeddeditem
AttachDtl(1, InxAttach) = "Ebd"
Case olByReference
AttachDtl(1, InxAttach) = "Ref"
Case olOLE
AttachDtl(1, InxAttach) = "OLE"
Case Else
AttachDtl(1, InxAttach) = "Unk"
End Select
' Not all types have all properties. This code handles
' those missing properties of which I am aware. However,
' I have never found an attachment of type Reference or OLE.
' Additional code may be required for them.
Select Case .Attachments(InxAttach).Type
Case olEmbeddeditem
AttachDtl(2, InxAttach) = ""
Case Else
AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
End Select
AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
AttachDtl(5, InxAttach) = "--"
' I suspect Attachment had a parent property in early versions
' of Outlook. It is missing from Outlook 2016.
On Error Resume Next
AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
On Error GoTo 0
AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
' Class 5 is attachment. I have never seen an attachment with
' a different class and do not see the purpose of this property.
' The code will stop here if a different class is found.
Debug.Assert .Attachments(InxAttach).Class = 5
AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
Next
End If
InterestingItem = True
Else
InterestingItem = False
End If
End With
' The most used properties of the email have been loaded to variables but
' there are many more properies. Press F2. Scroll down classes until
' you find MailItem. Look through the members and note the name of
' any properties that look useful. Look them up using VB Help.
' #### You need to add code here to eliminate uninteresting items.
' #### For example:
'If SenderEmailAddress <> "[email protected]" Then
' InterestingItem = False
'End If
'If InStr(Subject, "Accounts payable") = 0 Then
' InterestingItem = False
'End If
'If AttachCount = 0 Then
' InterestingItem = False
'End If
' #### If the item is still thought to be interesting I
' #### suggest extracting the required data to variables here.
' #### You should consider moving processed emails to another
' #### folder. The emails are being processed in reverse order
' #### to allow this removal of an email from the Inbox without
' #### effecting the index numbers of unprocessed emails.
If InterestingItem Then
With ExcelWkBk
With .Worksheets("Inbox")
' #### This code creates a dividing row and then
' #### outputs a property per row. Again it demonstrates
' #### statements that are likely to be useful in the final
' #### version
' Create dividing row between emails
.Rows(RowCrnt).RowHeight = 5
.Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
.Interior.Color = RGB(0, 255, 0)
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender name"
.Cells(RowCrnt, "B").Value = SenderName
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender email address"
.Cells(RowCrnt, "B").Value = SenderEmailAddress
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Received time"
With .Cells(RowCrnt, "B")
.NumberFormat = "@"
.Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
End With
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Subject"
.Cells(RowCrnt, "B").Value = Subject
RowCrnt = RowCrnt + 1
If AttachCount > 0 Then
.Cells(RowCrnt, "A").Value = "Attachments"
.Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
RowCrnt = RowCrnt + 1
For InxAttach = 1 To AttachCount
.Cells(RowCrnt, "B").Value = InxAttach & "|" & _
AttachDtl(1, InxAttach) & "|" & _
AttachDtl(2, InxAttach) & "|" & _
AttachDtl(3, InxAttach) & "|" & _
AttachDtl(4, InxAttach) & "|" & _
AttachDtl(5, InxAttach) & "|" & _
AttachDtl(6, InxAttach) & "|" & _
AttachDtl(7, InxAttach)
RowCrnt = RowCrnt + 1
Next
End If
If TextBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the text body. See below
' This outputs the text body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "text body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' ' The maximum size of a cell 32,767
' .Value = Mid(TextBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the text body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "text body"
.VerticalAlignment = xlTop
End With
TextBody = Replace(TextBody, Chr(160), "[NBSP]")
TextBody = Replace(TextBody, vbCr, "[CR]")
TextBody = Replace(TextBody, vbLf, "[LF]")
TextBody = Replace(TextBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
' The maximum size of a cell 32,767
.Value = Mid(TextBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
If HtmlBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the html body. See below
' This outputs the html body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "Html body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' .Value = Mid(HtmlBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the html body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "Html body"
.VerticalAlignment = xlTop
End With
HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
.Value = Mid(HtmlBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
End With
End With
End If
Next
With xlApp
With ExcelWkBk
' Write new workbook to disc
If Right(PathName, 1) <> "\" Then
PathName = PathName & "\"
End If
.SaveAs FileName:=PathName & FileName
.Close
End With
.Quit ' Close our copy of Excel
End With
Set xlApp = Nothing ' Clear reference to Excel
End Sub
Macros not included in original post but which some users of above macro have found useful.
Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' This routine (and its sub-routine) locate a folder within the hierarchy and
' returns it as an object of type MAPIFolder
' NameTgt The name of the required folder in the format:
' FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
' If NameSep is "|", an example value is "Personal Folders|Inbox"
' FolderName1 must be an outer folder name such as
' "Personal Folders". The outer folder names are typically the names
' of PST files. FolderName2 must be the name of a folder within
' Folder1; in the example "Inbox". FolderName2 is compulsory. This
' routine cannot return a PST file; only a folder within a PST file.
' FolderName3, FolderName4 and so on are optional and allow a folder
' at any depth with the hierarchy to be specified.
' NameSep A character or string used to separate the folder names within
' NameTgt.
' FolderTgt On exit, the required folder. Set to Nothing if not found.
' This routine initialises the search and finds the top level folder.
' FindSelectedSubFolder() is used to find the target folder within the
' top level folder.
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
Dim TopLvlFolderList As Folders
Set FolderTgt = Nothing ' Target folder not found
Set TopLvlFolderList = _
CreateObject("Outlook.Application").GetNamespace("MAPI").Folders
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
' I need at least a level 2 name
Exit Sub
End If
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To TopLvlFolderList.Count
If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
' Have found current name. Call FindSelectedSubFolder() to
' look for its children
Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
Exit For
End If
Next
End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' See FindSelectedFolder() for an introduction to the purpose of this routine.
' This routine finds all folders below the top level
' FolderCrnt The folder to be seached for the target folder.
' NameTgt The NameTgt passed to FindSelectedFolder will be of the form:
' A|B|C|D|E
' A is the name of outer folder which represents a PST file.
' FindSelectedFolder() removes "A|" from NameTgt and calls this
' routine with FolderCrnt set to folder A to search for B.
' When this routine finds B, it calls itself with FolderCrnt set to
' folder B to search for C. Calls are nested to whatever depth are
' necessary.
' NameSep As for FindSelectedSubFolder
' FolderTgt As for FindSelectedSubFolder
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
NameCrnt = NameTgt
NameChild = ""
Else
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
End If
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
' Have found current name.
If NameChild = "" Then
' Have found target folder
Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
Else
'Recurse to look for children
Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
End If
Exit For
End If
Next
' If NameCrnt not found, FolderTgt will be returned unchanged. Since it is
' initialised to Nothing at the beginning, that will be the returned value.
End Sub
One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.
ActiveX is also more customizable.
The equivalent of offsetHeight and offsetWidth in jQuery is $(window).width(), $(window).height() It's not the clientHeight and clientWidth
Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.
To set VSCODE Default Formatter
File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)
Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.
Date long getTime()
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
Also Model::all(['id'])->toArray()
it will only fetch id as array.
var text = "\"http://example.com\"";
Whatever your text, to wrap it with "
, you need to put them and escape inner ones with \
. Above will result in:
"http://example.com"
If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:
public ActionResult AddBlogPost(int userId,
[ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
//...
}
The AllowHtmlBinder code:
public class AllowHtmlBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var name = bindingContext.ModelName;
return request.Unvalidated[name]; //magic happens here
}
}
Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/
Supported Operating Systems:
- Windows 8.1 (x86 and x64)
- Windows 8 (x86 and x64)
- Windows 7 SP1 (x86 and x64)
- Windows Server 2012 R2 (x64)
- Windows Server 2012 (x64)
- Windows Server 2008 R2 SP1 (x64)
Hardware requirements:
- 1.6 GHz or faster processor
- 1 GB of RAM (1.5 GB if running on a virtual machine)
- 20 GB of available hard disk space
- 5400 RPM hard disk drive
- DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution
Additional Requirements for the laptop:
- Internet Explorer 10
- KB2883200 (available through Windows Update) is required
And don't forget to reboot after updating your windows
As per @Randal comment, you can use perl
, e.g.
$ printf 5a5a5a5a | perl -lne 'print pack "H*", $_'
ZZZZ
and other way round:
$ printf ZZZZ | perl -lne 'print unpack "H*", $_'
5a5a5a5a
Another example with file:
$ printf 5a5a5a5a | perl -lne 'print pack "H*", $_' > file.bin
$ perl -lne 'print unpack "H*", $_' < file.bin
5a5a5a5a
var Hello = React.createClass({
render: function() {
return (
<div className="divClass">
<img src={this.props.url} alt={`${this.props.title}'s picture`} className="img-responsive" />
<span>Hello {this.props.name}</span>
</div>
);
}
});
Based on drspaceboo's solution, with Kotlin you can use an extension to convert Float
to dips more easily.
fun Float.toDips() =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);
Usage:
(65f).toDips()
Further to ericwa's answer. CHECK constraints can enable a pseudo boolean column by enforcing a TEXT datatype and only allowing TRUE or FALSE case specific values e.g.
CREATE TABLE IF NOT EXISTS "boolean_test"
(
"id" INTEGER PRIMARY KEY AUTOINCREMENT
, "boolean" TEXT NOT NULL
CHECK( typeof("boolean") = "text" AND
"boolean" IN ("TRUE","FALSE")
)
);
INSERT INTO "boolean_test" ("boolean") VALUES ("TRUE");
INSERT INTO "boolean_test" ("boolean") VALUES ("FALSE");
INSERT INTO "boolean_test" ("boolean") VALUES ("TEST");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES ("true");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES ("false");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES (1);
Error: CHECK constraint failed: boolean_test
select * from boolean_test;
id boolean
1 TRUE
2 FALSE
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
FYI I can verify that the method:
import socket
addr = socket.gethostbyname(socket.gethostname())
Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:
if addr == "127.0.0.1":
import commands
output = commands.getoutput("/sbin/ifconfig")
addr = parseaddress(output)
And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.
You should add this import in your file:
import * as fetch from 'node-fetch';
And then, run this code to add the node-fetch
:
yarn add node-fetch
Working in Rails 5
ActiveModel::Type::Boolean.new.cast('t') # => true
ActiveModel::Type::Boolean.new.cast('true') # => true
ActiveModel::Type::Boolean.new.cast(true) # => true
ActiveModel::Type::Boolean.new.cast('1') # => true
ActiveModel::Type::Boolean.new.cast('f') # => false
ActiveModel::Type::Boolean.new.cast('0') # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false) # => false
ActiveModel::Type::Boolean.new.cast(nil) # => nil
I just had this issue myself. 3 points that will hopefully help:
app/assets/images
directory, then you should be able to call the image directly with no prefix in the path. ie. image_url('logo.png')
background-image:
property, then your line of code should be background-image: image-url('logo.png')
. This works for both less and sass stylesheets. If you are using it inline in the view, then you will need to use the built in image_tag
helper in rails to output your image. Once again, no prefixing <%= image_tag 'logo.png' %>
rake assets:precompile
to generate your assets, or rake assets:precompile RAILS_ENV=production
for production, otherwise, your production environment will not have the fingerprinted assets when loading the page.Also for those commands in point 3 you will need to prefix them with bundle exec
if you are running bundler.
You can do something like this:
<%!
String myMethod(String input) {
return "test " + input;
}
%>
<%= myMethod("1 2 3") %>
This will output test 1 2 3
to the page.
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.
public class Foo {
public static void doStuff(){
// does stuff
}
}
So, instead of creating an instance of Foo and then calling doStuff
like this:
Foo f = new Foo();
f.doStuff();
You just call the method directly against the class, like so:
Foo.doStuff();
I usually use svn through a gui, either my IDE or a client. Because of that, I can never remember the codes when I do have to resort to the command line.
I find this cheat sheet a great help: Subversion Cheat Sheet
Atop explanation by Konrad Kleine above.
A brief summary:
# pragma once
it is much of the compiler responsibility, not to allow its inclusion more than once. Which means, after you mention the code-snippet in the file, it is no more your responsibility.Now, compiler looks, for this code-snippet at the beginning of the file, and skips it from being included (if already included once). This definitely will reduce the compilation-time (on an average and in huge-system). However, in case of mocks/test environment, will make the test-cases implementation difficult, due to circular etc dependencies.
#ifndef XYZ_H
for the headers, it is more of the developers responsibility to maintain the dependency of headers. Which means, whenever due to some new header file, there is possibility of the circular dependency, compiler will just flag some "undefined ..
" error messages at compile time, and it is user to check the logical connection/flow of the entities and rectify the improper includes.This definitely will add to the compilation time (as needs to rectified and re-run). Also, as it works on the basis of including the file, based on the "XYZ_H" defined-state, and still complains, if not able to get all the definitions.
Therefore, to avoid situations like this, we should use, as;
#pragma once
#ifndef XYZ_H
#define XYZ_H
...
#endif
i.e. the combination of both.
This is what list comprehensions are for:
numbers = [ int(x) for x in numbers ]
A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")
plt.show()
Result is: Plot with multiple markers
The process for timing out an operations is described in the documentation for signal.
The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.
Note that this will only work on UNIX.
Here's an implementation that creates a decorator (save the following code as timeout.py
).
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
This creates a decorator called @timeout
that can be applied to any long running functions.
So, in your application code, you can use the decorator like so:
from timeout import timeout
# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
...
# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
...
# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
...
All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.
You'll need to import MatButtonModule and MatIconModule in your app module file.
From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.
<button mat-icon-button>
<mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>
In your case, use
<mat-icon>thumb_up</mat-icon>
As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Or import it in your global styles.scss.
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");
As it mentions, any icon font can be used with the mat-icon component.
If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.
In the form, add a method="GET"
attribute:
<form action="display.html" method="GET">
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
When they submit this form, the user will be directed to an address which includes the serialNumber
value as a parameter. Something like:
http://www.example.com/display.html?serialNumber=XYZ
You should then be able to parse the query string - which will contain the serialNumber
parameter value - from JavaScript, using the window.location.search
value:
// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
// the query string to extract the
// parameter you need
See also JavaScript query string.
The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html
page loads.
See also How to use JavaScript to fill a form on another page.
Log4j2 lets you format parameters into a message template, similar to String.format()
, thus doing away with the need to do isDebugEnabled()
.
Logger log = LogManager.getFormatterLogger(getClass());
log.debug("Some message [myField=%s]", myField);
Sample simple log4j2.properties:
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d %-5p: %c - %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = debug
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT
why not use "in" instead?
Select *
from table
where columnname in (word1, word2, word3)
Let me add this one, because sometimes you just want the single digit representation
( x
can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):
'{:x}'.format(15)
> f
And now with the new f''
format strings you can do:
f'{15:x}'
> f
To add 0 padding you can use 0>n
:
f'{2034:0>4X}'
> 07F2
NOTE: the initial 'f' in
f'{15:x}'
is to signify a format string
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
The 'mangler' in the above code sample was doing the equivalent of this:
bytesThing = stringThing.encode(encoding='UTF-8')
There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8')
, but the above syntax makes it obvious what is going on, and also what to do to recover the string:
newStringThing = bytesThing.decode(encoding='UTF-8')
When we do this, the original string is recovered.
Note, using str(bytesThing)
just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8')
. No error is reported if the encoding is not specified.
Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.
I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.
You have to write the query adding "[]" to foo like this:
foo[]=val1&foo[]=val2&foo[]=val3
As of today (2015, Aug., 1st), Apache2
in Debian Jessie
, you need to edit:
root@host:/etc/apache2/mods-enabled$ vi dir.conf
And change the order of that line, bringing index.php to the first position:
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
Add the file to the index:
git add path/to/untracked-file
git stash
The entire contents of the index, plus any unstaged changes to existing files, will all make it into the stash.
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>oninvalid</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >_x000D_
<input type="email" placeholder="[email protected]" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">_x000D_
<input type="submit" value="Submit">_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
The chosen answer didn't work for me...hmm...
Just add space after cow and/or before milk to trim spaces from " always gives "
/(?<=cow ).*(?= milk)/
A way to solve this without having to rely on URLs is to add a custom attribute to every partial during $routeProvider
configuration, like this:
$routeProvider.
when('/dashboard', {
templateUrl: 'partials/dashboard.html',
controller: widgetsController,
activetab: 'dashboard'
}).
when('/lab', {
templateUrl: 'partials/lab.html',
controller: widgetsController,
activetab: 'lab'
});
Expose $route
in your controller:
function widgetsController($scope, $route) {
$scope.$route = $route;
}
Set the active
class based on the current active tab:
<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:
first I check the iOS version:
if (![self compareCurVersionTo:4 minor:3 point:0])
Than:
// set RTL on the start on each line (except the first)
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
withString:@"\u202B\n"];
To me this kind of seemingly simple problem is what Python is all about. Especially if you're coming from a language like C++, where simple text parsing can be a pain in the butt, you'll really appreciate the functionally unit-wise solution that python can give you. I'd keep it really simple with a couple of built-in functions and some generator expressions.
You'll need open(name, mode)
, myfile.readlines()
, mystring.split()
, int(myval)
, and then you'll probably want to use a couple of generators to put them all together in a pythonic way.
# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]
Look up generator expressions here. They can really simplify your code into discrete functional units! Imagine doing the same thing in 4 lines in C++... It would be a monster. Especially the list generators, when I was I C++ guy I always wished I had something like that, and I'd often end up building custom functions to construct each kind of array I wanted.
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want
try {
String dateStart = "June 14 2018 16:02:37";
cal.setTime(sdf.parse(dateStart));
//all done
} catch (ParseException e) {
e.printStackTrace();
}
It happens because you call it before DOM has loaded. Firstly, create the element and add atrributes to it, then after DOM has loaded call it. In your case it should look like that:
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
window.onload = function() {
document.getElementById("CursorLayer");
}
Anwer is here How to dynamically add a style for text-align using jQuery
ALTER DATABASE MyDatabase SET RECOVERY SIMPLE
GO
DBCC SHRINKFILE (MyDatabase_Log, 5)
GO
ALTER DATABASE MyDatabase SET RECOVERY FULL
GO
I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/
Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>
max-width:80% or something like that.
Try experimenting you might find something new.
Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first)
is slowed down by that evaluation.
An equally fast and easy to read solution is using the function version .not(":first")
:
e.g.
$("li").not(":first").hide();
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
This is only few percentage points slower than slice(1)
, but is very readable as "I want all except the first one".
Every datetime field in input/output needs to be in UNIX/epoch format. This avoids the confusion between developers across different sides of the API.
Pros:
Cons:
Notes:
Mmm first your id attributes must be unique, your code is likely to be
<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>
For your problem :
if($('.roles:checkbox:checked').length == 0)
// no checkbox checked, do something...
else
// at least one checkbox checked...
BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.
Sourcing runs shell commands in your current shell. When you source inside of a script like you are doing above, you are affecting the environment for that script, but when the script exits, the environment changes are undone, as they've effectively gone out of scope.
If your intent is to run shell commands in the virtualenv, you can do that in your script after sourcing the activate script. If your intent is to interact with a shell inside the virtualenv, then you can spawn a sub-shell inside your script which would inherit the environment.