$now = date("Y-m-d H:i:s");
date("Y-m-d H:i:s", strtotime("+1 hours $now"));
Try following code will Add one day to current date
select DateAdd(day, 1, GetDate())
And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function
select dateadd(dd,360,getdate())
will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
I spent a while trying to do the same thing, trying to subtract the hours:minutes
from datetime
- here's how I did it:
convert( varchar, cast((RouteMileage / @average_speed) as integer))+ ':' + convert( varchar, cast((((RouteMileage / @average_speed) - cast((RouteMileage / @average_speed) as integer)) * 60) as integer)) As TravelTime,
dateadd( n, -60 * CAST( (RouteMileage / @average_speed) AS DECIMAL(7,2)), @entry_date) As DepartureTime
DeliveryDate TravelTime DepartureTime
2012-06-02 12:00:00.000 25:49 2012-06-01 10:11:00.000
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
Another approach to count number of list elements:
var num = $("#mylist").find("li").length;_x000D_
console.log(num);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul id="mylist">_x000D_
<li>Element 1</li>_x000D_
<li>Element 2</li>_x000D_
<li>Element 3</li>_x000D_
<li>Element 4</li>_x000D_
<li>Element 5</li>_x000D_
</ul>
_x000D_
You can log in via browser and copy the needed headers afterwards:
Use "Copy as cURL" in the Network tab of browser developer tools and replace curl's flag -H
with wget's --header
(and also --data
with --post-data
if needed).
I guess the question arises, why would you need to do this? The reason for async
in C# 5.0 is so you can await a result. This method is not actually asynchronous, but simply called at a time so as not to interfere too much with the current thread.
Perhaps it may be better to start a thread and leave it to finish on its own.
Check your local .m2 direcory for a sub directory of this artifact. If exixts - delete it, and perform Maven update again
Félix's answer is correct and upvoted, backed-up by Dan Abramov himself.
But for those who would like to change the structure of the output itself (within the build
folder), one can run post-build commands with the help of postbuild
, which automatically runs after the build
script defined in the package.json
file.
The example below changes it from static/
to user/static/
, moving files and updating file references on relevant files (full gist here):
package.json
{
"name": "your-project",
"version": "0.0.1",
[...]
"scripts": {
"build": "react-scripts build",
"postbuild": "./postbuild.sh",
[...]
},
}
postbuild.sh
#!/bin/bash
# The purpose of this script is to do things with files generated by
# 'create-react-app' after 'build' is run.
# 1. Move files to a new directory called 'user'
# The resulting structure is 'build/user/static/<etc>'
# 2. Update reference on generated files from
# static/<etc>
# to
# user/static/<etc>
#
# More details on: https://github.com/facebook/create-react-app/issues/3824
# Browse into './build/' directory
cd build
# Create './user/' directory
echo '1/4 Create "user" directory'
mkdir user
# Find all files, excluding (through 'grep'):
# - '.',
# - the newly created directory './user/'
# - all content for the directory'./static/'
# Move all matches to the directory './user/'
echo '2/4 Move relevant files'
find . | grep -Ev '^.$|^.\/user$|^.\/static\/.+' | xargs -I{} mv -v {} user
# Browse into './user/' directory
cd user
# Find all files within the folder (not subfolders)
# Replace string 'static/' with 'user/static/' on all files that match the 'find'
# ('sed' requires one to create backup files on OSX, so we do that)
echo '3/4 Replace file references'
find . -type f -maxdepth 1 | LC_ALL=C xargs -I{} sed -i.backup -e 's,static/,user/static/,g' {}
# Delete '*.backup' files created in the last process
echo '4/4 Clean up'
find . -name '*.backup' -type f -delete
# Done
Try something along these lines:
int divisors(int myNum) {
int limit = myNum;
int divisorCount = 0;
if (x == 1)
return 1;
for (int i = 1; i < limit; ++i) {
if (myNum % i == 0) {
limit = myNum / i;
if (limit != i)
divisorCount++;
divisorCount++;
}
}
return divisorCount;
}
I'm happily using FileSaver.js. Its compatibility is pretty good (IE10+ and everything else), and it's very simple to use:
var blob = new Blob(["some text"], {
type: "text/plain;charset=utf-8;",
});
saveAs(blob, "thing.txt");
Update for 64-bit Change: According to apple docs about 64-bit changes,
Enumerations Are Also Typed : In the LLVM compiler, enumerated types can define the size of the enumeration. This means that some enumerated types may also have a size that is larger than you expect. The solution, as in all the other cases, is to make no assumptions about a data type’s size. Instead, assign any enumerated values to a variable with the proper data type
So you have to create enum with type as below syntax if you support for 64-bit.
typedef NS_ENUM(NSUInteger, ShapeType) {
kCircle,
kRectangle,
kOblateSpheroid
};
or
typedef enum ShapeType : NSUInteger {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
Otherwise, it will lead to warning as Implicit conversion loses integer precision: NSUInteger (aka 'unsigned long') to ShapeType
Update for swift-programming:
In swift, there's an syntax change.
enum ControlButtonID: NSUInteger {
case kCircle , kRectangle, kOblateSpheroid
}
The accepted answer is out of date; nowadays you can simply add enctype="application/json"
to your form tag and the browser will jsonify the data automatically.
The spec for this behavior is here: https://www.w3.org/TR/html-json-forms/
Here is the solution.
The HTML:
<table cellspacing="0" cellpadding="0">
<tr>
<td>
123
</td>
</tr>
</table>
The CSS:
table {
border-spacing:0;
border-collapse:collapse;
}
Hope this helps.
EDIT
td, th {padding:0}
Delete /*# sourceMappingURL=bootstrap.min.css.map */ in css/bootstrap.min.css
and delete /*# sourceMappingURL=bootstrap.css.map */ in css/bootstrap.css
To run test cases in IE Browser make sure you have downloaded IE driver and you need to set the property as well.
Below code will help you
// This will set the driver
System.setProperty("webdriver.ie.driver","driver path\\IEDriverServer.exe");
// Initialise browser
WebDriver driver=new InternetExplorerDriver();
You can check IE Browser challenges with Selenium and complete code for more details
Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:
$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
REVISION CHANGE-CAUSE
1 <none>
2 <none>
3 <none>
To see the details of each revision, run:
kubectl rollout history deployment my-dep --revision=2
And then returning to the previous revision by running:
$kubectl rollout undo deployment my-dep --to-revision=2
And then returning back to the new one.
Like running ctrl+z -> ctrl+y
(:
(*) The CHANGE-CAUSE is <none>
because you should run the updates with the --record
flag - like mentioned here:
kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record
(**) There is a discussion regarding deprecating this flag.
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
I had a weird encounter with this problem. when renaming variable name
to user_name
, I mistakenly rename all of the name to user_name
for the project. So my xml tag <color name:"">
became <color user_name:"">
same goes for string, style, manifest too. But when I check merged manifest, it showed nothing, because I had only one manifest, nothing to find.
So, check if you have any malformed xml file or not.
I've made an alias git squash-all
.
Example usage: git squash-all "a brand new start"
.
[alias]
squash-all = "!f(){ git reset $(git commit-tree HEAD^{tree} -m \"${1:-A new start}\");};f"
Note: the optional message is for commit message, if omitted, it will default to "A new start".
Or you can create the alias with the following command:
git config --global alias.squash-all '!f(){ git reset $(git commit-tree HEAD^{tree} -m "${1:-A new start}");};f'
git reset $(git commit-tree HEAD^{tree} -m "A new start")
Here, the commit message "A new start
" is just an example, feel free to use your own language.
No need to squash, use git commit-tree
to create an orphan commit and go with it.
create a single commit via git commit-tree
What git commit-tree HEAD^{tree} -m "A new start"
does is:
Creates a new commit object based on the provided tree object and emits the new commit object id on stdout. The log message is read from the standard input, unless -m or -F options are given.
The expression HEAD^{tree}
means the tree object corresponding to HEAD
, namely the tip of your current branch. see Tree-Objects and Commit-Objects.
Then git reset
simply reset the current branch to the newly created
commit object.
This way, nothing in the workspace is touched, nor there's need for rebase/squash, which makes it really fast. And the time needed is irrelevant to the repository size or history depth.
This is useful to create the "initial commit" in a new project using another repository as the template/archetype/seed/skeleton. For example:
cd my-new-project
git init
git fetch --depth=1 -n https://github.com/toolbear/panda.git
git reset --hard $(git commit-tree FETCH_HEAD^{tree} -m "initial commit")
This avoids adding the template repo as a remote (origin
or otherwise) and collapses the template repo's history into your initial commit.
I had some code that was failing with an HTTPConnection (MOVED_PERMANENTLY error)
, but as soon as I switched to HTTPS
it worked perfectly again with no other changes needed. That's a very simple fix!
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterUnless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
Here is how do it with single statement
WITH deleted_rows AS (
DELETE FROM source_table WHERE id = 1
RETURNING *
)
INSERT INTO destination_table
SELECT * FROM deleted_rows;
EXAMPLE:
postgres=# select * from test1 ;
id | name
----+--------
1 | yogesh
2 | Raunak
3 | Varun
(3 rows)
postgres=# select * from test2;
id | name
----+------
(0 rows)
postgres=# WITH deleted_rows AS (
postgres(# DELETE FROM test1 WHERE id = 1
postgres(# RETURNING *
postgres(# )
postgres-# INSERT INTO test2
postgres-# SELECT * FROM deleted_rows;
INSERT 0 1
postgres=# select * from test2;
id | name
----+--------
1 | yogesh
(1 row)
postgres=# select * from test1;
id | name
----+--------
2 | Raunak
3 | Varun
Reducing the image size before output results in something that looks sharper, in my case:
convert -density 300 a.pdf -resize 25% a.png
I had the same problem after upgrading a bunch of NuGet packages.
I have tried all kinds of deleting, cleaning, resintalling described here and beyong to no avail. The references did not have Microsoft.Web.Infrastructure despite the NuGet manager showed it was installed.
The problem was solved by replacing:
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
with
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
in packages.config. The culprit is apparently "net45".
This works for me:
Create/edit .htaccess
file with these lines:
AddDefaultCharset UTF-8
AddCharset UTF-8 .php
If you prefer create/edit php.ini
:
default_charset = "utf-8"
Sources:
You need to store it in a String
variable first before displaying it like so:
String Txt = TxtBoxContent.getText();
System.out.println(Txt);
Great answers from a couple of years ago. Now Bitbucket has made it easier.
Tag the Commit you want to download (as mentioned in answer by Rudy Matela).
Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.
This has already been answered in detail on SO. Check out this thread, It should answer all your questions: Executing a subprocess fails
I've tried it myself with this code:
batchtest.py
from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()
batch.bat
echo Hello World!
pause
I've got the batchtest.py example from the aforementioned thread.
I also did a little workaround of my own.
I created a (dropdownOpen) event which I listen to at my ng-select element component and call a function which will close all the other SelectComponent's opened apart from the currently opened SelectComponent.
I modified one function inside the select.ts file like below to emit the event:
private open():void {
this.options = this.itemObjects
.filter((option:SelectItem) => (this.multiple === false ||
this.multiple === true && !this.active.find((o:SelectItem) => option.text === o.text)));
if (this.options.length > 0) {
this.behavior.first();
}
this.optionsOpened = true;
this.dropdownOpened.emit(true);
}
In the HTML I added an event listener for (dropdownOpened):
<ng-select #elem (dropdownOpened)="closeOtherElems(elem)"
[multiple]="true"
[items]="items"
[disabled]="disabled"
[isInputAllowed]="true"
(data)="refreshValue($event)"
(selected)="selected($event)"
(removed)="removed($event)"
placeholder="No city selected"></ng-select>
This is my calling function on event trigger inside the component having ng2-select tag:
@ViewChildren(SelectComponent) selectElem :QueryList<SelectComponent>;
public closeOtherElems(element){
let a = this.selectElem.filter(function(el){
return (el != element)
});
a.forEach(function(e:SelectComponent){
e.closeDropdown();
})
}
Your formula is wrong. You probably meant something like:
=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Another equivalent:
=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Or even shorter:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))
OR EVEN SHORTER:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))
It seems that the only correct answer here so far has been given by romnex: "onDestroy() may not be called at all". Even though in practice, in almost all cases it will, there is no guarantee: The documentation on finish() only promises that the result of the activity is propagated back to the caller, but nothing more. Moreover, the lifecycle documentation clarifies that the activity is killable by the OS as soon as onStop() finishes (or even earlier on older devices), which, even though unlikely and therefore rare to observe in a simple test, might mean that the activity might be killed while or even before onDestroy() is executed.
So if you want to make sure some work is done when you call finish(), you cannot put it in onDestroy(), but will need to do in the same place where you call finish(), right before actually calling it.
To add a project within a solution, just open the Team Explorer window and go to Changes. Then, under Untracked Files, click on View options and select Switch to Tree View (unless it is already in tree view), right click on the project root folder, and select Add.
If the problem allows it, try with EXISTS, since it's optimized to end as soon as a result is found (And don't buffer any response), so, if you are just trying to normalize data for a WHERE clause like this
SELECT FROM SOMETHING S WHERE S.ID IN ( SELECT DISTINCT DCR.SOMETHING_ID FROM DIFF_CARDINALITY_RELATIONSHIP DCR ) -- to keep same cardinality
A faster response would be:
SELECT FROM SOMETHING S WHERE EXISTS ( SELECT 1 FROM DIFF_CARDINALITY_RELATIONSHIP DCR WHERE DCR.SOMETHING_ID = S.ID )
This isn't always possible but when available you will see a faster response.
You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.
XAML:
<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...
Code behind:
private void listView_Click(object sender, RoutedEventArgs e)
{
var item = (sender as ListView).SelectedItem;
if (item != null)
{
...
}
}
Or, even cleaner:
when(mockFoo.someMethod()).thenReturn(obj1, obj2);
Select
MonthEndDate MED,
SUM(GrossBalance/1000000) GrossBalance,
PortfolioRename PR
into
testDynamic
from
Risk_PortfolioOverview
Group By MonthEndDate, PortfolioRename
Try doing this in a shell:
var=" 3918912k"
echo ${var//[[:blank:]]/}
That uses parameter expansion (it's a non posix feature)
[[:blank:]]
is a POSIX regex class (remove spaces, tabs...), see http://www.regular-expressions.info/posixbrackets.html
Here is my Extension method. It's very efficient and it's lazy.
Usage:
var checkBoxes = tableLayoutPanel1.FindChildControlsOfType<CheckBox>();
foreach (var checkBox in checkBoxes)
{
checkBox.Checked = false;
}
The code is:
public static IEnumerable<TControl> FindChildControlsOfType<TControl>(this Control control) where TControl : Control
{
foreach (var childControl in control.Controls.Cast<Control>())
{
if (childControl.GetType() == typeof(TControl))
{
yield return (TControl)childControl;
}
else
{
foreach (var next in FindChildControlsOfType<TControl>(childControl))
{
yield return next;
}
}
}
}
This is an interview question :Remove duplicates from an array.I shall not use any Set or collections. The complete solution is :
public class Test4 {
public static void main(String[] args) {
int a[] = {1, 2, 2, 3, 3, 3, 6,6,6,6,6,66,7,65};
int newlength = lengthofarraywithoutduplicates(a);
for(int i = 0 ; i < newlength ;i++) {
System.out.println(a[i]);
}//for
}//main
private static int lengthofarraywithoutduplicates(int[] a) {
int count = 1 ;
for (int i = 1; i < a.length; i++) {
int ch = a[i];
if(ch != a[i-1]) {
a[count++] = ch;
}//if
}//for
return count;
}//fix
}//end1
try setting RowCount to 0(allowuserstorows should be false), along with calling clear
this way i follow and its work for me fine, may it will works for you,
<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
height: iframeHeight * 0.75 + 'px'
}" style="width:100%"></iframe>
here trustThisUrl is just filter,
angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
return function (val) {
return $sce.trustAsResourceUrl(val);
};
}]);
In order to maintain for numerical stability, max(x) should be subtracted. The following is the code for softmax function;
def softmax(x):
if len(x.shape) > 1:
tmp = np.max(x, axis = 1)
x -= tmp.reshape((x.shape[0], 1))
x = np.exp(x)
tmp = np.sum(x, axis = 1)
x /= tmp.reshape((x.shape[0], 1))
else:
tmp = np.max(x)
x -= tmp
x = np.exp(x)
tmp = np.sum(x)
x /= tmp
return x
The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.
I recommend you follow NuGet's instructions but just to recap what I did:
packages
folder is not committed to TFS. If it is, get it out of there..sln
file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this)..nuget
folder. You can use Windows Explorer to name it .nuget.
for it to successfully save as .nuget
(it automatically removes the last period) but directly trying to name it .nuget
may not work (you may get an error or it may change the name, depending on your version of Windows).
Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nugetNuGet.config
file and add the following contents and save it:NuGet.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
.sln
's folder and create a new text file and name it .tfignore
(if using Windows Explorer, use the same trick as above and name it .tfignore.
).tfignore:
# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's
# not in the same folder as .tfignore.
packages
# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
.tfignore
file and .nuget
folder to all of my various solutions and committed them and I no longer have the packages
folder trying to sneak into my source control repo!While not mine, I have found this .tfignore
template by sirkirby to be handy. The example in my answer covers the Nuget packages
folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.
Finally got it working after 1 hour struggle.
This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .
For a new WebApi 2 application example:
Postman (looks exactly, like below):
POST http://localhost:61402/api/values [Send]
Body
(*) raw JSON (application/json) v
"{ \"key1\": \"value1\" }"
The port 61402 or url /api/values above, may be different for you.
ValuesController.cs
using Newtonsoft.Json;
// ..
// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
// add reference to Newtonsoft.Json
// using Newtonsoft.Json;
// jsonString to myJsonObj
var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
// value1 is myJsonObj[key1]
var valueOfkey1 = myJsonObj["key1"];
return myJsonObj;
}
All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.
I had to switch from Eclipse Oxygen that I got from IBM and used IBM JDK 8 to Eclipse Photon and Oracle JDK 8. I'm working on Java customizations for maximo.
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
I don't know why do you need this onmousedown
event here, but what you have to do is put your function above actual usage. Look at the snipplet below:
<script type="text/javascript">_x000D_
function jsFunction(value)_x000D_
{_x000D_
alert(value);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">_x000D_
<option value='1'>One</option>_x000D_
<option value='2'>Two</option>_x000D_
<option value='3'>Three</option>_x000D_
</select>
_x000D_
That might be because you would be using functional component and in that you would be using these '{}' braces instead of '()' Example : const Main = () => ( ... then your code ... ). Basically, you will have to wrap up your code within these brackets '()'.
Here is code based on bestsss' answer:
Enumeration<URL> en = getClass().getClassLoader().getResources(
"META-INF");
List<String> profiles = new ArrayList<>();
while (en.hasMoreElements()) {
URL url = en.nextElement();
JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
try (JarFile jar = urlcon.getJarFile();) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
System.out.println(entry);
}
}
}
This is the most comprehensive AngularJS learning resource repository I've come across:
To pluck out the best parts (in recommended order of learning):
You can do this :
df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))
Create a drawable checkbox selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/checkbox"
android:state_checked="false"/>
<item android:drawable="@drawable/checkboxselected"
android:state_checked="true"/>
<item android:drawable="@drawable/checkbox"/>
</selector>
Make sure your checkbox is like this android:button="@drawable/checkbox_selector"
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_selector"
android:text="CheckBox"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/Black" />
UPDATE:
In bootstrap 3
you need to change the modal-dialog.
So in this case you can add the class modal-admin
in the place where modal-dialog
stands.
Original Answer (Bootstrap < 3)
Is there a certain reason you're trying to change it with JS/jQuery?
You can easily do it with just CSS, which means you don't have to do your styling in the document. In your own custom CSS file, you add:
body .modal {
/* new custom width */
width: 560px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -280px;
}
In your case:
body .modal-admin {
/* new custom width */
width: 750px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -375px;
}
The reason I put body before the selector is so that it takes a higher priority than the default. This way you can add it to an custom CSS file, and without worries update Bootstrap.
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
print buffalo
As an output you will see:
2
A few comments:
ws.[a1]
and xlNext
below so my search starts in A2
of the specified sheet. Find
s arguments - including lookat
use the prior search settings. So you should always specify xlWhole
or xlPart
to match all or part a string respectively.Select
or Activate
suggested code
Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json
. If you do this, certain CommonJS variables can't be used, including require
.
To fix this, remove "type": "module"
from your package.json
and make sure you don't have any files ending with .mjs
.
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
I think you should call the super.draw()
method first before you do anything in surfaceView's draw method.
document.location
was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location
instead.
Read more:
Post increment(a++)
If int b = a++,then this means
int b = a;
a = a+1;
Here we add 1 to the value. The value is returned before the increment is made,
For eg a = 1; b = a++;
Then b=1 and a=2
Pre-increment (++a)
If int b = ++a; then this means
a=a+1;
int b=a ;
Pre-increment: This will add 1 to the main value. The value will be returned after the increment is made, For a = 1; b = ++a; Then b=2 and a=2.
.test * {padding: 40px 100px 40px 50px;}
SELECT s.id, s.name, LENGTH(s.name) len, ASCII(s.name) ASCCCI FROM table_name s ORDER BY ASCCCI,len,NAME ASC;
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
svn delete --keep-local the_file
Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:
What I like about it is that it aligns the unit-of-work (as the user sees it - i.e. a page submit) with the unit-of-work in the ORM sense.
Therefore, you can make the entire page submission transactional, which you could not do if you were exposing CRUD methods with each creating a new context.
The best loading and blocking that particular div for ajax call until it succeeded is Blockui
go through this link http://www.malsup.com/jquery/block/#element
example usage:
<span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>
script
jQuery.ajax(
{
url: site_path+"/restaurantlist/addtocart",
type: "POST",
success: function (data) {
jQuery("#id").unblock();
},
beforeSend:function (data){
jQuery("#id").block({
message: jQuery(".smallLoader").html(),
css: {
border: 'none',
backgroundColor: 'none'
},
overlayCSS: { backgroundColor: '#afafaf' }
});
}
});
hope this helps really it is very interactive.
Insert Into FEMALE(ID, Image)
Select '1', BulkColumn
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image
You will also need admin rights to run the query.
Using update directly is more efficient and could also prevent integrity problems.
From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update
If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:
e = Entry.objects.get(id=10) e.comments_on = False e.save()
…do this:
Entry.objects.filter(id=10).update(comments_on=False)
Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().
devnull is right;
sudo update-alternatives --config x-terminal-emulator
import operator
def max_positions(iterable, key=None, reverse=False):
if key is None:
def key(x):
return x
if reverse:
better = operator.lt
else:
better = operator.gt
it = enumerate(iterable)
for pos, item in it:
break
else:
raise ValueError("max_positions: empty iterable")
# note this is the same exception type raised by max([])
cur_max = key(item)
cur_pos = [pos]
for pos, item in it:
k = key(item)
if better(k, cur_max):
cur_max = k
cur_pos = [pos]
elif k == cur_max:
cur_pos.append(pos)
return cur_max, cur_pos
def min_positions(iterable, key=None, reverse=False):
return max_positions(iterable, key, not reverse)
>>> L = range(10) * 2
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_positions(L)
(9, [9, 19])
>>> min_positions(L)
(0, [0, 10])
>>> max_positions(L, key=lambda x: x // 2, reverse=True)
(0, [0, 1, 10, 11])
for i in range(a.count(' ')):
a.remove(' ')
Much simpler I believe.
If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, SAX would be ideal.
import has from 'lodash/has';
is better because lodash holds all it's functions in a single file, so rather than import the whole 'lodash' library at 100k, it's better to just import lodash's has
function which is maybe 2k.
I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.
<DataGrid IsReadOnly="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"/>
<DataGridTextColumn IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
On some versions of Chrome, you can:
ctx.drawImage(image1, 0, 0, w, h);
Extracting a specific folder (directory) within war file:
# unzip <war file> '<folder to extract/*>' -d <destination path>
unzip app##123.war 'some-dir/*' -d extracted/
You get ./extracted/some-dir/
as a result.
According to the API, the headers can all be passed in using requests.get
:
import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})
UPDATE: The stroke-alignment
attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.
As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the with the values stroke-alignment
property is presentinner
, center
(default) and outer
.
It seems to work the same way as the stroke-location
property proposed by @Phrogz and the later stroke-position
suggestion. This property has been planned since at least 2011, but apart from an annotation that said
SVG 2 shall include a way to specify stroke position
, it has never been detailed in the spec as it was deferred - until now, it seems.
No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.
There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.
You should not use available()
. It gives no guarantees what so ever. From the API docs of available()
:
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
You can explicitly tell Eclipse where to find it. Open eclipse.ini
and add the following lines to the top of the file:
-vm
/absolute/path/to/jre6/bin
Update: I just nailed down the root cause on my own Windows machine. The GlassFish installer complained with exactly the same error message and after digging in GlassFish forums, the cause was clear: a corrupt JRE install on a Windows machine. My JRE came along with the JDK and the Java 6 JDK installer didn't install the JRE properly somehow. A DLL file was missing in JDK's JRE installation. After I reinstalled the standalone JRE from http://java.com, overwriting the old one, the GlassFish installer continued and also Eclipse was able to start flawlessly without those two lines in eclipse.ini
.
FINALLY THE BEST WAY WORKED PERFECTLY FOR ME
None of the solutions in this page worked for me EXCEPT THE FOLLOWING
Below the comment sections of the second answer, try the following :
Adding to my above comment, Task Manager does not display the filename.exe process but Resource Monitor does, so I'm able to kill it from there which solves the issue without having to reboot. – A__ Jun 19 '19 at 21:23
I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.
Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.
Then I realized, that you can create macros easily, so I recorded one doing:
That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)
how about:
def fix_unicode(data):
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
data = dict((fix_unicode(k), fix_unicode(data[k])) for k in data)
elif isinstance(data, list):
for i in xrange(0, len(data)):
data[i] = fix_unicode(data[i])
return data
If you are using PHP 5.6, the command is:
sudo apt-get install php5.6-pgsql
you can add this plugin configuration to your pom if you do not want to set command line arg:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException )
and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
I think these could be helpful for you .
Using a SELECT
statement with a simple CASE
expression
Within a SELECT
statement, a simple CASE
expression allows for only an equality check; no other comparisons are made. The following example uses the CASE
expression to change the display of product line categories to make them more understandable.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
Using a SELECT
statement with a searched CASE
expression
Within a SELECT
statement, the searched CASE
expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Using CASE
in an ORDER BY
clause
The following examples uses the CASE
expression in an ORDER BY
clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
ELSE CountryRegionName END;
Using CASE
in an UPDATE
statement
The following example uses the CASE
expression in an UPDATE
statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT
clause is used to display the before and after vacation values.
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue,
Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0;
Using CASE
in a HAVING
clause
The following example uses the CASE
expression in a HAVING
clause to restrict the rows returned by the SELECT
statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING
clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.
USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M'
THEN ph1.Rate
ELSE NULL END) > 40.00
OR MAX(CASE WHEN Gender = 'F'
THEN ph1.Rate
ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;
For more details description of these example visit the source.
Also visit here and here for some examples with great details.
In simple terms Dependency Injection vs Factory method implies push vs pull mechanism respectively.
Pull mechanism : class indirectly have dependency on Factory Method which in turn have dependency on concrete classes.
Push mechanism : Root component can be configured with all dependent components in a single location and thus promoting high maintenance and loose coupling.
With Factory method responsibility still lies with class (though indirectly) to create new object where as with dependency injection that responsibility is outsourced (at the cost of leaking abstraction though)
I had a similar issue with the SQL Server Express Edition on Windows Server 2003. I simply added the network service as a user in the database security.
You can this query:
pip install image
I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.
Varchar has its own limits. Maybe try changing datatype to text.!
Yes, you surely can... but it needs some work to make it work seamlessly. This is some code I came up with. Bear in mind that it does not use combobox's auto-complete features, and it might be quite slow if you use it to sift thru a lot of items...
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.ToUpper().StartsWith(comboBox1.Text.ToUpper())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int sStart = comboBox1.SelectionStart;
if (sStart > 0)
{
sStart--;
if (sStart == 0)
{
comboBox1.Text = "";
}
else
{
comboBox1.Text = comboBox1.Text.Substring(0, sStart);
}
}
e.Handled = true;
}
}
I think you what you want is a tuple. If you use return (i, card)
, you can get these two results by:
i, card = select_choice()
mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name
should probably be
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
Install distribute by downloading and running distribute_setup.py. This will make easy_install available, and from there you can install pip with easy_install pip. Then you can run pip install CAGE. Using pip to install things is a lot easier than messing with manually running setup.py, because pip can do things like:
automatically resolve dependencies
show you a list of all installed packages and their versions
install a set of specified packages from a requirements.txt
upgrade and uninstall packages
work with virtualenv
If you're on Windows, the one downside of pip occurs when there are C library dependencies, as pip will want a C toolchain installed so it can compile things. If that is the case, then there are two options. If there are precompiled binaries on PyPI, then just run easy_install package instead; easy_install knows how to use binary packages. You can also check Christoph Gohlke's site for executable installers of many binary packages. These can also be installed by easy_install if you want to use them with a virtualenv (just point it to the path of the .exe) or you can click and run if you don't care about virtualenv.
The main point is that no matter what route you choose to install packages, at no point are you ever moving around files by hand. You need to get out of the mindset of "I extracted this archive, where do I put these .py files?" That's not how it works. You're either running pip, running easy_install, running setup.py, clicking on an installer package, or using your distribution's installer. At no point are you ever doing anything by hand with the files directly.
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:
=SUM(A1:INDIRECT(CONCATENATE("A",B1)))
CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).
INDIRECT convert "A3" to a index.
see this link Using the value in a cell as a cell reference in a formula?
You need to create Object
for the class.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
I tried make a telnet
over remote server on port 3306
.
The error message is clear
Host 'x.x.x.x' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'Connection closed by foreign host.
As root
at server mysqladmin flush-hosts
worked at all!
xargs
is fast:
#!/usr/bin/bash
echo "while loop:"
n=0; time while (( n++ < 10000 )); do /usr/bin/true ; done
echo -e "\nfor loop:"
time for ((n=0;n<10000;n++)); do /usr/bin/true ; done
echo -e "\nseq,xargs:"
time seq 10000 | xargs -I{} -P1 -n1 /usr/bin/true
echo -e "\nyes,xargs:"
time yes x | head -n10000 | xargs -I{} -P1 -n1 /usr/bin/true
echo -e "\nparallel:"
time parallel --will-cite -j1 -N0 /usr/bin/true ::: {1..10000}
On a modern 64-bit Linux, gives:
while loop:
real 0m2.282s
user 0m0.177s
sys 0m0.413s
for loop:
real 0m2.559s
user 0m0.393s
sys 0m0.500s
seq,xargs:
real 0m1.728s
user 0m0.013s
sys 0m0.217s
yes,xargs:
real 0m1.723s
user 0m0.013s
sys 0m0.223s
parallel:
real 0m26.271s
user 0m4.943s
sys 0m3.533s
This makes sense, as the xargs
command is a single native process that spawns the /usr/bin/true
command multiple time, instead of the for
and while
loops that are all interpreted in Bash. Of course this only works for a single command; if you need to do multiple commands in each iteration the loop, it will be just as fast, or maybe faster, than passing sh -c 'command1; command2; ...'
to xargs
The -P1
could also be changed to, say, -P8
to spawn 8 processes in parallel to get another big boost in speed.
I don't know why GNU parallel is so slow. I would have thought it would be comparable to xargs.
I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use
StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64
This may be what you want:
This code places a default text string Enter your name here
inside the <input>
textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
You can check out using branch names, for one thing.
I know there are several ways to move the HEAD around, but I'll leave it to a git expert to enumerate them.
I just wanted to suggest gitk --all
-- I found it enormously helpful when starting with git.
Your json contains an array, but you're trying to parse it as an object.
This error occurs because objects must start with {
.
You have 2 options:
You can get rid of the ShopContainer
class and use Shop[]
instead
ShopContainer response = restTemplate.getForObject(
url, ShopContainer.class);
replace with
Shop[] response = restTemplate.getForObject(url, Shop[].class);
and then make your desired object from it.
You can change your server to return an object instead of a list
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
replace with
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
new ShopContainer(list));
I would perform a git clone via the command line (outside Eclipse) then use File -> Import... -> Existing Maven Projects.
Your projects will be understood as using Git and Maven. It's the fastest and most reliable way to import IMO.
The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
Long story short you need to create a launch file. So, from Terminal:
sudo vi /Library/LaunchDaemons/com.mysql.mysql.plist
(If you are not familiar with vi, then press i to start inserting text)
This should be the content of your file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true />
<key>Label</key>
<string>com.mysql.mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld_safe</string>
<string>--user=mysql</string>
</array>
</dict>
</plist>
press esc then : wq!enter
Then you need to give the file the right permissions and set it to load on startup.
sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
And that is it.
Create site/includes/.htaccess
file and add this line:
Deny from all
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
document.querySelector('input').onchange = e => {
const fr = new FileReader()
fr.onloadend = () => document.write(fr.result)
fr.readAsDataURL(e.target.files[0])
}
_x000D_
<input type="file">
_x000D_
You can actually send it as JSON the following way:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
Save the following into a file with ".reg" suffix:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe]
"CodePage"=dword:0000fde9
Double click this file, and regedit will import it.
It basically sets the key HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exe\CodePage
to 0xfde9 (65001 in decimal system).
I just tried to show you the solution in a simple code
@IBAction func Button(sender : AnyObject) {
if textField1.text != "" {
// either textfield 1 is not empty then do this task
}else{
//show error here that textfield1 is empty
}
}
In android, we can easily check whether GPS is enabled in device or not using LocationManager.
Here is a simple program to Check.
GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Your java class file should be
public class ExampleApp extends Activity {
/** Called when the activity is first created. */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
The output will looks like
If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('')
section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.
Example link: http://www.base64-image.de/
When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')
With your texture images, you'll want to employ a similar process.
Am using Mountain Lion. What I did was Look for /usr/local and Get Info. On it there is Sharing and Permissions. Make sure that its only the user and Admin are the only ones who have read and write permissions. Anyone else should have read access only. That sorted my problem.
Its normally helpful is your Run disk utilities and repair permissions too.
This bug is filed here. This is a bug of android devices having API level less than 12. You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher. And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.
For example: I had to design a button with rounded corner at bottom-right.
In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.
<shape>
<corners android:bottomLeftRadius="15dp"/>
</shape>
You can download code here.
Step 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCustomToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast" />
</RelativeLayout>
Step 2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/custom_toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/custom_toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My custom Toast Example Text" />
</LinearLayout>
Step 3:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btnCustomToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCustomToast= (Button) findViewById(R.id.btnCustomToast);
btnCustomToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Find custom toast example layout file
View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null);
// Creating the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
// gravity, xOffset, yOffset
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layoutValue);//setting the view of custom toast layout
toast.show();
}
});
}
}
Update from Keith Shaw's comment on Jun 22, 2017:
As of February 2017, RFC8081 is the proposed standard. It defines a top-level media type for fonts, therefore the standard media type for WOFF and WOFF2 are as follows:
font/woff
font/woff2
In January 2011 it was announced that in the meantime Chromium will recognize
application/x-font-woff
as the mime-type for WOFF. I know this change is now in Chrome beta and if not in stable yet, it shouldn't be too far away.
Actually, I've seen this sort of thing used in BIRT reports. The query passed to the BIRT runtime is of the form:
select a,b,c from t where a = ?
and the '?' is replaced at runtime by an actual parameter value selected from a drop-down box. The choices in the drop-down are given by:
select distinct a from t
union all
select '*' from sysibm.sysdummy1
so that you get all possible values plus "*
". If the user selects "*
" from the drop down box (meaning all values of a should be selected), the query has to be modified (by Javascript) before being run.
Since the "?" is a positional parameter and MUST remain there for other things to work, the Javascript modifies the query to be:
select a,b,c from t where ((a = ?) or (1==1))
That basically removes the effect of the where clause while still leaving the positional parameter in place.
I've also seen the AND case used by lazy coders whilst dynamically creating an SQL query.
Say you have to dynamically create a query that starts with select * from t
and checks:
some people would add the first with a WHERE and subsequent ones with an AND thus:
select * from t where name = 'Bob' and salary > 20000
Lazy programmers (and that's not necessarily a bad trait) wouldn't distinguish between the added conditions, they'd start with select * from t where 1=1
and just add AND clauses after that.
select * from t where 1=1 and name = 'Bob' and salary > 20000
old question but just to mention the solution for MVC5 developers, you can use the Model
property same as in view.
The Model
property in both view and layout is assosiated with the same ViewDataDictionary
object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName
in the layout.
But notice that when you use @Model.XXX
in the layout the intelliSense context menu will not appear because the Model
here is a dynamic object just like ViewBag
.
Not Obvious, But Fast
f, u = pd.factorize(df.name.values)
counts = np.bincount(f)
u[counts == counts.max()]
array(['alex', 'helen'], dtype=object)
You can change the text in the titlebar in Windows Forms by using the Text
property.
// This class is added to the namespace containing the Form1 class.
class MainApplication
{
public static void Main()
{
// Instantiate a new instance of Form1.
Form1 f1 = new Form1();
// Display a messagebox. This shows the application
// is running, yet there is nothing shown to the user.
// This is the point at which you customize your form.
System.Windows.Forms.MessageBox.Show("The application "
+ "is running now, but no forms have been shown.");
// Customize the form.
f1.Text = "Running Form";
// Show the instance of the form modally.
f1.ShowDialog();
}
}
For any googlers like me, where..
.btn:focus {
outline: none;
}
still didn't work in Google Chrome, the following should completely remove any button glow.
.btn:focus,.btn:active:focus,.btn.active:focus,
.btn.focus,.btn:active.focus,.btn.active.focus {
outline: none;
}
If you copy a folder from local then it will copy folder with all its sub folders to HDFS.
For copying a folder from local to hdfs, you can use
hadoop fs -put localpath
or
hadoop fs -copyFromLocal localpath
or
hadoop fs -put localpath hdfspath
or
hadoop fs -copyFromLocal localpath hdfspath
Note:
If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.
To copy from hdfs to local
hadoop fs -get hdfspath localpath
This problem is also caused by:
If you are on a mac/linux, and are using 'ControlMaster' in your ~/.ssh/config, there may be some ssh control master processes running.
To find them, run:
ps aux | grep '\[mux\]'
And kill the relevant ones.
Try using "uname". For example, in Linux: "uname -a".
According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.
BTW: $OSTYPE is also set to linux-gnu
here :)
The best way to center content in a table (for example <video>
or <img>
) is to do the following:
<table width="100%" border="0" cellspacing="0" cellpadding="100%">
<tr>
<td>Video Tag 1 Here</td>
<td>Video Tag 2 Here</td>
</tr>
</table>
_x000D_
Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.
There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.
Progressive Enhancement consists of the following core principles:
- basic content should be accessible to all browsers
- basic functionality should be accessible to all browsers
- sparse, semantic markup contains all content
- enhanced layout is provided by externally linked CSS
- enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
- end user browser preferences are respected
Use the Soot Java Optimization framework to directly modify the bytecode. http://www.sable.mcgill.ca/soot/
Soot is completely written in Java and works with new Java versions.
Just to modify scott's answer to make it a function:
Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant
Dim LookAtWhat As Integer
If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart
With RngIn
Set FindFirstInRange = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=LookAtWhat, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=UseCase)
If FindFirstInRange Is Nothing Then FindFirstInRange = False
End With
End Function
This returns FALSE if the value isn't found, and if it's found, it returns the range.
You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.
I took out the TRIM because you can add that beforehand if you want to.
An example:
MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address
That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:
MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address
You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.
Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.
Provided that the remote repository is origin
, and that you're interested in branch_name
:
git fetch origin
git reset --hard origin/<branch_name>
Also, you go for reset the current branch of origin
to HEAD
.
git fetch origin
git reset --hard origin/HEAD
How it works:
git fetch origin
downloads the latest from remote without trying to merge or rebase anything.
Then the git reset
resets the <branch_name>
branch to what you just fetched. The --hard
option changes all the files in your working tree to match the files in origin/branch_name
.
Full option searchable select box
This also supports Control buttons keyboards such as ArrowDown
ArrowUp
and Enter
keys
function filterFunction(that, event) {_x000D_
let container, input, filter, li, input_val;_x000D_
container = $(that).closest(".searchable");_x000D_
input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
keyControl(event, container)_x000D_
} else {_x000D_
li = container.find("ul li");_x000D_
li.each(function (i, obj) {_x000D_
if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
$(this).show();_x000D_
} else {_x000D_
$(this).hide();_x000D_
}_x000D_
});_x000D_
_x000D_
container.find("ul li").removeClass("selected");_x000D_
setTimeout(function () {_x000D_
container.find("ul li:visible").first().addClass("selected");_x000D_
}, 100)_x000D_
}_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
if (e.key == "ArrowDown") {_x000D_
_x000D_
if (container.find("ul li").hasClass("selected")) {_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
_x000D_
} else {_x000D_
container.find("ul li:first-child").addClass("selected");_x000D_
}_x000D_
_x000D_
} else if (e.key == "ArrowUp") {_x000D_
_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
} else if (e.key == "Enter") {_x000D_
container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
onSelect(container.find("ul li.selected").text())_x000D_
}_x000D_
_x000D_
container.find("ul li.selected")[0].scrollIntoView({_x000D_
behavior: "smooth",_x000D_
});_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
$(this).closest(".searchable").find("ul").show();_x000D_
$(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
let that = this;_x000D_
setTimeout(function () {_x000D_
$(that).closest(".searchable").find("ul").hide();_x000D_
}, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
$(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
$(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
$(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
width: 300px;_x000D_
float: left;_x000D_
margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
width: 100%;_x000D_
height: 50px;_x000D_
font-size: 18px;_x000D_
padding: 10px;_x000D_
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
-moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
box-sizing: border-box; /* Opera/IE 8+ */_x000D_
display: block;_x000D_
font-weight: 400;_x000D_
line-height: 1.6;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: .25rem;_x000D_
transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
display: none;_x000D_
list-style-type: none;_x000D_
background-color: #fff;_x000D_
border-radius: 0 0 5px 5px;_x000D_
border: 1px solid #add8e6;_x000D_
border-top: none;_x000D_
max-height: 180px;_x000D_
margin: 0;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
padding: 7px 9px;_x000D_
border-bottom: 1px solid #e1e1e1;_x000D_
cursor: pointer;_x000D_
color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
background-color: #e8e8e8;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
<input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
<ul>_x000D_
<li>Algeria</li>_x000D_
<li>Bulgaria</li>_x000D_
<li>Canada</li>_x000D_
<li>Egypt</li>_x000D_
<li>Fiji</li>_x000D_
<li>India</li>_x000D_
<li>Japan</li>_x000D_
<li>Iran (Islamic Republic of)</li>_x000D_
<li>Lao People's Democratic Republic</li>_x000D_
<li>Micronesia (Federated States of)</li>_x000D_
<li>Nicaragua</li>_x000D_
<li>Senegal</li>_x000D_
<li>Tajikistan</li>_x000D_
<li>Yemen</li>_x000D_
</ul>_x000D_
</div>
_x000D_
You have a JSON object of the exception thrown, in the xhr object. Just use
alert(xhr.responseJSON.Message);
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
If the database in question is local, the following is probably the most robust way to export a query result to a CSV file (that is, giving you the most control).
After going through this process exhaustively, I found the following to be the best option
PowerShell Script
$dbname = "**YOUR_DB_NAME_WITHOUT_STARS**"
$AttachmentPath = "c:\\export.csv"
$QueryFmt= @"
**YOUR_QUERY_WITHOUT_STARS**
"@
Invoke-Sqlcmd -ServerInstance **SERVER_NAME_WITHOUT_STARS** -Database $dbname -Query $QueryFmt | Export-CSV $AttachmentPath -NoTypeInformation
Run PowerShell as Admin
& "c:\path_to_your_ps1_file.ps1"
I'm using these classes to alter top margin:
.margin-top-05 { margin-top: 0.5em; }
.margin-top-10 { margin-top: 1.0em; }
.margin-top-15 { margin-top: 1.5em; }
.margin-top-20 { margin-top: 2.0em; }
.margin-top-25 { margin-top: 2.5em; }
.margin-top-30 { margin-top: 3.0em; }
When I need an element to have 2em spacing from the element above I use it like this:
<div class="row margin-top-20">Something here</div>
If you prefere pixels so change the em to px to have it your way.
I was facing the same problem when import projects into IntelliJ.
for in my case first, check SDK details and check you have configured JDK correctly or not.
Go to File-> Project Structure-> platform Settings-> SDKs
Check your JDK is correct or not.
Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.
The above solution worked in my case.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
You need to create a TypeReference
object for each generic type you use and use that for deserialization. For example -
mapper.readValue(jsonString, new TypeReference<Data<String>>() {});
DECLARE @INPUT VARCHAR (MAX)='N,A,R,E,N,D,R,A'
DECLARE @ELIMINATE_CHAR CHAR (1)=','
DECLARE @L_START INT=1
DECLARE @L_END INT=(SELECT LEN (@INPUT))
DECLARE @OUTPUT CHAR (1)
WHILE @L_START <=@L_END
BEGIN
SET @OUTPUT=(SUBSTRING (@INPUT,@L_START,1))
IF @OUTPUT!=@ELIMINATE_CHAR
BEGIN
PRINT @OUTPUT
END
SET @L_START=@L_START+1
END
For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.
The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.
Read this one for more info.
The route.snapshot provides the initial value of the route parameter map. You can access the parameters directly without subscribing or adding observable operators. It's much simpler to write and read:
Quote from the Angular Docs
To break it down for you, here is how to do it with the new router:
this.router.navigate(['/login'], { queryParams: { token:'1234'} });
And then in the login component (notice the new .snapshot
added):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sessionId = this.route.snapshot.queryParams['token']
}
Use
driver.findElement(By.linkText("App Configuration")).click()
Other Approaches will be
JavascriptLibrary jsLib = new JavascriptLibrary();
jsLib.callEmbeddedSelenium(selenium, "triggerMouseEventAt", elementToClick,"click", "0,0");
or
((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementToClick);
For detailed answer, View this post
From the comments:
import msvcrt # built-in module
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:
#include <conio.h>
int kb_inkey () {
int rc;
int key;
key = _kbhit();
if (key == 0) {
rc = 0;
} else {
rc = _getch();
}
return rc;
}
And I access it in python using the ctypes module (built into python 2.5):
import ctypes
import time
#
# first, load the DLL
#
try:
kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
raise ("Error Loading PyKeyboardAccess.dll")
#
# now, find our function
#
try:
kbfunc = kblib.kb_inkey
except:
raise ("Could not find the kb_inkey function in the dll!")
#
# Ok, now let's demo the capability
#
while 1:
x = kbfunc()
if x != 0:
print "Got key: %d" % x
else:
time.sleep(.01)
You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.
brew outdated | xargs brew upgrade
I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:
if HAVE_CLIENT
libtest_LIBS = $(top_builddir)/libclient.la
else
if HAVE_SERVER
libtest_LIBS = $(top_builddir)/libserver.la
else
libtest_LIBS =
endif
endif
(The indentation is for clarity. Don't indent the lines, they won't work.)
Or just...
var response = (function() {
var a;
// calculate a
return a;
})();
In this case, the response variable receives the return value of the function. The function executes immediately.
You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.
Wrap the input fields and other stuff into a <fieldset>
and give it the disabled="disabled"
attribute.
Example (http://jsfiddle.net/7qGHN/):
<form>_x000D_
<fieldset disabled="disabled">_x000D_
<input type="text" name="something" placeholder="enter some text" />_x000D_
<select>_x000D_
<option value="0" disabled="disabled" selected="selected">select somethihng</option>_x000D_
<option value="1">woot</option>_x000D_
<option value="2">is</option>_x000D_
<option value="3">this</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>
_x000D_
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
test ! -f README.md || echo 'Support OpenSource!' >> README.md
"If README.md does not exist, do nothing (and exit successfully). Otherwise, append text to the end."
If you use &&
instead of ||
then you generate an error when the file doesn't exist:
Makefile:42: recipe for target 'dostuff' failed
make: *** [dostuff] Error 1
$resource("../rest/api"}).get();
returns an object.
$resource("../rest/api").query();
returns an array.
You must use :
return $resource('../rest/api.php?method=getTask&q=*').query();
Life cycle is a sequence of named phases.
Phases executes sequentially. Executing a phase means executes all previous phases.Plugin is a collection of goals also called MOJO (Maven Old Java Object).
Analogy : Plugin is a class and goals are methods within the class.
Maven is based around the central concept of a Build Life Cycles. Inside each Build Life Cycles there are Build Phases, and inside each Build Phases there are Build Goals.
We can execute either a build phase or build goal. When executing a build phase we execute all build goals within that build phase. Build goals are assigned to one or more build phases. We can also execute a build goal directly.
There are three major built-in Build Life Cycles:
Each Build Lifecycle is Made Up of Phases
For example the default
lifecycle comprises of the following Build Phases:
?validate - validate the project is correct and all necessary information is available
?compile - compile the source code of the project
?test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
?package - take the compiled code and package it in its distributable format, such as a JAR.
?integration-test - process and deploy the package if necessary into an environment where integration tests can be run
?verify - run any checks to verify the package is valid and meets quality criteria
?install - install the package into the local repository, for use as a dependency in other projects locally
?deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
So to go through the above phases, we just have to call one command:
mvn <phase> { Ex: mvn install }
For the above command, starting from the first phase, all the phases are executed sequentially till the ‘install’ phase. mvn
can either execute a goal or a phase (or even multiple goals or multiple phases) as follows:
mvn clean install plugin:goal
However, if you want to customize the prefix used to reference your plugin, you can specify the prefix directly through a configuration parameter on the maven-plugin-plugin
in your plugin's POM.
A Build Phase is Made Up of Plugin Goals
Most of Maven's functionality is in plugins. A plugin provides a set of goals that can be executed using the following syntax:
mvn [plugin-name]:[goal-name]
For example, a Java project can be compiled with the compiler-plugin's compile-goal by running mvn compiler:compile
.
Build lifecycle is a list of named phases that can be used to give order to goal execution.
Goals provided by plugins can be associated with different phases of the lifecycle. For example, by default, the goal compiler:compile
is associated with the compile
phase, while the goal surefire:test
is associated with the test
phase. Consider the following command:
mvn test
When the preceding command is executed, Maven runs all goals associated with each of the phases up to and including the test
phase. In such a case, Maven runs the resources:resources
goal associated with the process-resources
phase, then compiler:compile
, and so on until it finally runs the surefire:test
goal.
However, even though a build phase is responsible for a specific step in the build lifecycle, the manner in which it carries out those responsibilities may vary. And this is done by declaring the plugin goals bound to those build phases.
A plugin goal represents a specific task (finer than a build phase) which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation. The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean
and package
arguments are build phases, while the dependency:copy-dependencies
is a goal (of a plugin).
mvn clean dependency:copy-dependencies package
If this were to be executed, the clean
phase will be executed first (meaning it will run all preceding phases of the clean lifecycle, plus the clean
phase itself), and then the dependency:copy-dependencies
goal, before finally executing the package
phase (and all its preceding build phases of the default lifecycle).
Moreover, if a goal is bound to one or more build phases, that goal will be called in all those phases.
Furthermore, a build phase can also have zero or more goals bound to it. If a build phase has no goals bound to it, that build phase will not execute. But if it has one or more goals bound to it, it will execute all those goals.
Built-in Lifecycle Bindings
Some phases have goals bound to them by default. And for the default lifecycle, these bindings depend on the packaging value.
Maven Architecture:
Eclipse sample for Maven Lifecycle Mapping
No way. You'll need some dependency injection, i.e. instead of having the obj1
instantiated it should be provided by some factory.
MyObjectFactory factory;
public void setMyObjectFactory(MyObjectFactory factory)
{
this.factory = factory;
}
void method1()
{
MyObject obj1 = factory.get();
obj1.method();
}
Then your test would look like:
@Test
public void testMethod1() throws Exception
{
MyObjectFactory factory = Mockito.mock(MyObjectFactory.class);
MyObject obj1 = Mockito.mock(MyObject.class);
Mockito.when(factory.get()).thenReturn(obj1);
// mock the method()
Mockito.when(obj1.method()).thenReturn(Boolean.FALSE);
SomeObject someObject = new SomeObject();
someObject.setMyObjectFactory(factory);
someObject.method1();
// do some assertions
}
Somewhere around r59 this gets easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
I don't think the Chrome Developer tools pretty print XHR content. See: Viewing HTML response from Ajax call through Chrome Developer tools?
Here is the sample code.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
ms.Position = 0;
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.txt";
// I guess you know how to send email with an attachment
// after sending email
ms.Close();
Edit 1
You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf
Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"
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
This might work:
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
Try this: http://jsbin.com/axaler/3/edit
$(function(){
$(window).scroll(function(){
var aTop = $('.ad').height();
if($(this).scrollTop()>=aTop){
alert('header just passed.');
// instead of alert you can use to show your ad
// something like $('#footAd').slideup();
}
});
});
<link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />
_x000D_
This worked for me. If anyone is troubleshooting while reading this - I found issues when my favicon.ico was not nested in the root folder. I had mine in the Resources folder and was struggling at that point.
Even I also say the below one is better :)
while(true)
{
}
It basically means that the object implements the __getitem__()
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
Also you can try to go to services and restart your Sql server instance
I suppose the easiest and the best solution is using OUTER APPLY
. You only use one field with DISTINCT
but to retrieve more data about that record, you utilize OUTER APPLY
.
To test the solution, execute following query which firstly creates a temp table then retrieves data:
DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
SET NOCOUNT ON
INSERT @tblFruit VALUES (1,'Citrus ','Orange')
INSERT @tblFruit VALUES (2,'Citrus','Lime')
INSERT @tblFruit VALUES (3,'Citrus','Lemon')
INSERT @tblFruit VALUES (4,'Seed','Cherry')
INSERT @tblFruit VALUES (5,'Seed','Banana')
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
SELECT TOP(1) *
FROM @tblFruit AS inner_f
WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f
The result will be:
Citrus 1
Seed 4
I think you have an issue with your server certificate, is not a valid certificate (I think this is what "handshake_failure" means in this case):
Import your server certificate into your trustcacerts keystore on client's JRE. This is easily done with keytool:
keytool
-import
-alias <provide_an_alias>
-file <certificate_file>
-keystore <your_path_to_jre>/lib/security/cacerts
You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.
Create a service:
public class YourService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do your jobs here
return super.onStartCommand(intent, flags, startId);
}
}
Create an Application class and start your service:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, YourService.class));
}
}
Add "name" attribute into the "application" tag of your AndroidManifest.xml
android:name=".App"
Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml
<service android:name=".YourService"/>
And also this permission request in the "manifest" tag (if API level 28 or higher):
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
UPDATE
After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.
public class YourService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
startForeground();
return super.onStartCommand(intent, flags, startId);
}
private void startForeground() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running background")
.setContentIntent(pendingIntent)
.build());
}
}
EDIT: RESTRICTED OEMS
Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.
If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.
By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)
I have had this problem. It appears that although permission to "View1" as part of schema "schema1" needs to be granted by the owner "dbo" if View1 uses dbo.table1.
Unless a schema gets used which is not part of dbo then this problem may not become apparent, and the regular solution of "Grant Select to user" would work.
At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:
SELECT
itemName as ItemName,
substring(itemName, 1,1) as FirstLetter,
Count(itemName)
FROM table1
GROUP BY 1, 2
Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.
First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate. For example you have css styling with a selector of:
.style-head span
{
//Some style set
}
You would need to do this with Jquery already included above this script:
var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();
Needless to say
theWidthYouWant
will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));
if you have adapter to set. So you can follow this. Just call the getContext
adapter = new Adapter(getContext(), myModelList);
If you have Toast to show, use same thing above
Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();
Hope this will work.
HappyCoding
A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:
// Placeholder fallback
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
I had exactly this issue using requests. Thanks to Christophe Roussy for his explanation.
To debug, I used:
response = requests.get(url)
logger.info(type(response))
I was getting a 404 response back from the API.
This is what I did for bulk update:
UPDATE tableName SET isDeleted = 1 where columnName in ('430903GW4j683537882','430903GW4j667075431','430903GW4j658444015')
try this
$("#mprDetailDataTable tr:gt(0)").each(function () {
var this_row = $(this);
var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
var product = $.trim(this_row.find('td:eq(1)').html())
var Quantity = $.trim(this_row.find('td:eq(2)').html())
});
You can write to multiple sheets with the xlsx
package. You just need to use a different sheetName
for each data frame and you need to add append=TRUE
:
library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)
Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:
wb = createWorkbook()
sheet = createSheet(wb, "Sheet 1")
addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)
sheet = createSheet(wb, "Sheet 2")
addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)
saveWorkbook(wb, "My_File.xlsx")
In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx
:
http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software
If you need to continuously insert an element at the beginning of an array, it is faster to use push
statements followed by a call to reverse
, instead of calling unshift
all the time.
Benchmark test: http://jsben.ch/kLIYf
You can use the sort
keyword like this:
sort(unique(c))[1:N]
Example:
c <- c(4,2,44,2,1,45,34,2,4,22,244)
sort(unique(c), decreasing = TRUE)[1:5]
will give the first 5 max numbers.
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue)
as a parameter, but the Queue
class is abstract. I solved that by using a QueuePtr(myQueue)
constructor like so:
using QueuePtr = std::unique_ptr<Queue>;
and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue
when you make a std::unique_ptr
of its type, which can't happen.
you can use of promise
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
use
console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });
or
console.log("Hello");
await sleep(2000);
console.log("World!");
I eventually shut-down and restarted Microsoft SQL Server Management Studio; and that fixed it for me. But at other times, just starting a new query window was enough.
According to Transact-SQL Syntax Conventions (Transact-SQL) (MSDN)
Transact-SQL statement terminator. Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version.
(also see @gerryLowry 's comment)
geonames.org has an api and a data dump of worldwide geographical places.
Hive supports bigint literal since 0.8 version. So, additional "L" is enough:
COALESCE(column, 0L)
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
None of the proposed answers works for surrogate pairs used to encode characters outside of the Unicode Basic Multiligual Plane.
Here is an example using three different techniques to iterate over the "characters" of a string (incl. using Java 8 stream API). Please notice this example includes characters of the Unicode Supplementary Multilingual Plane (SMP). You need a proper font to display this example and the result correctly.
// String containing characters of the Unicode
// Supplementary Multilingual Plane (SMP)
// In that particular case, hieroglyphs.
String str = "The quick brown jumps over the lazy ";
The first solution is a simple loop over all char
of the string:
/* 1 */
System.out.println(
"\n\nUsing char iterator (do not work for surrogate pairs !)");
for (int pos = 0; pos < str.length(); ++pos) {
char c = str.charAt(pos);
System.out.printf("%s ", Character.toString(c));
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
}
The second solution uses an explicit loop too, but accessing individual code points with codePointAt and incrementing the loop index accordingly to charCount:
/* 2 */
System.out.println(
"\n\nUsing Java 1.5 codePointAt(works as expected)");
for (int pos = 0; pos < str.length();) {
int cp = str.codePointAt(pos);
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
pos += Character.charCount(cp);
// ^^^^^^^^^^^^^^^^^^^^^^^
// Increment pos by 1 of more depending
// the number of Java `char` required to
// encode that particular codepoint.
}
The third solution is basically the same as the second, but using the Java 8 Stream API:
/* 3 */
System.out.println(
"\n\nUsing Java 8 stream (works as expected)");
str.codePoints().forEach(
cp -> {
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
});
When you run that test program, you obtain:
Using char iterator (do not work for surrogate pairs !)
T h e q u i c k b r o w n ? ? j u m p s o v e r t h e l a z y ? ? ? ? ? ? ? ?
Using Java 1.5 codePointAt(works as expected)
T h e q u i c k b r o w n j u m p s o v e r t h e l a z y
Using Java 8 stream (works as expected)
T h e q u i c k b r o w n j u m p s o v e r t h e l a z y
As you can see (if you're able to display hieroglyphs properly), the first solution does not handle properly characters outside of the Unicode BMP. On the other hand, the other two solutions deal well with surrogate pairs.
Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.
Here you can see the some more points on Main Advantages of MVC Architecture.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
The element.style
property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle
property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle
method.
The two ways have differences, for example, the IE element.currentStyle
property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight
, fontSize
, backgroundColor
, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height
, font-size
, background-color
, etc).
Also, the IE element.currentStyle
will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
/**
* Intent to open a YouTube Video
*
* @param pm
* The {@link PackageManager}.
* @param url
* The URL or YouTube video ID.
* @return the intent to open the YouTube app or Web Browser to play the video
*/
public static Intent newYouTubeIntent(PackageManager pm, String url) {
Intent intent;
if (url.length() == 11) {
// youtube video id
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
} else {
// url to video
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
try {
if (pm.getPackageInfo("com.google.android.youtube", 0) != null) {
intent.setPackage("com.google.android.youtube");
}
} catch (NameNotFoundException e) {
}
return intent;
}
You probably want to flatten all of the lists in Values
into a single list:
List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
If you need to get datetime.time
value, you can use this trick:
my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
You cannot add timedelta
to time
, but can add it to datetime
.
UPD: Yet another variation of the same technique:
my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
Instead of 1
you can use any number greater than 0. Here we use the fact that datetime.fromordinal
will always return datetime
object with time
component being zero.
import { MatDialogModule } from '@angular/material/dialog';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
Visual Studio in left panel is Python "interactive Select karnel"
Pyton 3.7.x anaconda3/python.exe ('base':conda) I'm this fixing
Needs installed excel as it uses the Excel.Application
com object.Save this as .bat
file:
@if (@X)==(@Y) @end /* JScript comment
@echo off
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%
@if (@X)==(@Y) @end JScript comment */
var ARGS = WScript.Arguments;
var xlCSV = 6;
var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;
var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);
objExcel.Quit();
It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:
call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"
printf("\nmaximum of %d and %d is = %d",a,b,c);