If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.
function getMaxColCount($table) {
var maxCol = 0;
$table.find('tr').each(function(i,o) {
var colCount = 0;
$(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
var cc = Number($(oo).attr('colspan'));
if (cc) {
colCount += cc;
} else {
colCount += 1;
}
});
if(colCount > maxCol) { maxCol = colCount };
});
return maxCol;
}
To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:
$('td.maxcols, th.maxcols').each(function(i,o) {
$t = $($(o).parents('table')[0]); $(o).attr('colspan', getMaxColCount($t));
});
If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.
Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId
Try splitting on a regex like /\r?\n/
to be usable by both Windows and UNIX systems.
> "a\nb\r\nc".split(/\r?\n/)
[ 'a', 'b', 'c' ]
In swift 5.3 and Inspired by @ravron answer:
extension UIButton {
/// Fits the image and text content with a given spacing
/// - Parameters:
/// - spacing: Spacing between the Image and the text
/// - contentXInset: The spacing between the view to the left image and the right text to the view
func setHorizontalMargins(imageTextSpacing: CGFloat, contentXInset: CGFloat = 0) {
let imageTextSpacing = imageTextSpacing / 2
contentEdgeInsets = UIEdgeInsets(top: 0, left: (imageTextSpacing + contentXInset), bottom: 0, right: (imageTextSpacing + contentXInset))
imageEdgeInsets = UIEdgeInsets(top: 0, left: -imageTextSpacing, bottom: 0, right: imageTextSpacing)
titleEdgeInsets = UIEdgeInsets(top: 0, left: imageTextSpacing, bottom: 0, right: -imageTextSpacing)
}
}
It adds an extra horizontal margin from the View to the Image and from the Label to the View
Sure, being in master
branch all you need to do is:
git merge <commit-id>
where commit-id
is hash of the last commit from newbranch
that you want to get in your master
branch.
You can find out more about any git command by doing git help <command>
. It that case it's git help merge
. And docs are saying that the last argument for merge
command is <commit>...
, so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.
Try
adb root
adb remount
to start the adb demon as root and ensure partitions are mounted in read-write mode (the essential part is adb root
). After push
ing, revoke root permissions again using:
adb unroot
"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."
"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."
Here is my source.
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
All above answers perfectly gives the solution to center the form using Bootstrap 4
. However, if someone wants to use out of the box Bootstrap 4
css classes without help of any additional styles and also not wanting to use flex
, we can do like this.
A sample form
HTML
<div class="container-fluid h-100 bg-light text-dark">
<div class="row justify-content-center align-items-center">
<h1>Form</h1>
</div>
<hr/>
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
<form action="">
<div class="form-group">
<select class="form-control">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" />
</div>
<div class="form-group text-center">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 1
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 2
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio" disabled>Option 3
</label>
</div>
</div>
<div class="form-group">
<div class="container">
<div class="row">
<div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
<div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Link to CodePen
https://codepen.io/anjanasilva/pen/WgLaGZ
I hope this helps someone. Thank you.
Replace:
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
with:
System.out.println("Enter EmployeeName:");
ename=(scanner.nextLine());
This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname
This is how I would do it, you don't need get-content:
ls -r | Select-String dummy | select line,path
or
ls -r | Select-String dummy | fl *
To see what the different properties are...
This is faster. The second argument is -filter:
ls -r . *.bat | select-string netsh
ls -r . -filter *.bat | select-string netsh
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
multipart/form-data
is used when you want to upload files to the server. Please check this article for details.
I believe this error can also be thrown if your project is targeting a framework version that is not installed on the server you are deploying to.
Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.
This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:
private void CombineFiles(string jpgFileName, string zipFileName)
{
using (Stream original = new FileStream(jpgFileName, FileMode.Append))
{
using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[32 * 1024];
int blockSize;
while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
{
original.Write(buffer, 0, blockSize);
}
}
}
}
If you are using MySQL you can do it like this:
SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;
For a pure PHP solution use strtotime
strtotime('+ 30 minute',$yourdate);
Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.
This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.
The program's source code is also available.
Step 1: fetch list of commits:
git log
You'll get list like in this example:
[Comp:Folder User$ git log
commit 54b11d42e12dc6e9f070a8b5095a4492216d5320
Author: author <[email protected]>
Date: Fri Jul 8 23:42:22 2016 +0300
This is last commit message
commit fd6cb176297acca4dbc69d15d6b7f78a2463482f
Author: author <[email protected]>
Date: Fri Jun 24 20:20:24 2016 +0300
This is previous commit message
commit ab0de062136da650ffc27cfb57febac8efb84b8d
Author: author <[email protected]>
Date: Thu Jun 23 00:41:55 2016 +0300
This is previous previous commit message
...
Step 2: copy needed commit hash and paste it for checkout:
git checkout fd6cb176297acca4dbc69d15d6b7f78a2463482f
That's all.
Just adding android:background="?attr/selectableItemBackgroundBorderless"
should work if you don't have background color, but don't forget to use setSelected method. If you have different background color, I just used this (I'm using data-binding);
Set isSelected at onClick function
b.setIsSelected(true);
And add this to xml;
android:background="@{ isSelected ? @color/{color selected} : @color/{color not selected} }"
I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107
function uploadAudio( blob ) {
var reader = new FileReader();
reader.onload = function(event){
var fd = {};
fd["fname"] = "test.wav";
fd["data"] = event.target.result;
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
dataType: 'text'
}).done(function(data) {
console.log(data);
});
};
reader.readAsDataURL(blob);
}
Contents of upload.php
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
You can try progress bar instead of seek bar
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginBottom="35dp"
/>
Try this:
div {
border: 1px solid black;
width: 70px;
overflow: hidden;
white-space: nowrap;
}
Here is the answer:
Download the "Windows Mobile Device Center" for your machine type, likely 64bit.
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3182
Before you run the install, change the compatibility settings to 'Windows 7'. Then install it... Then run it: You'll find it under 'WMDC'.. Your device should now recognize, when plugged in, mine did!
Adding this here because the more relevant questions have all been marked as duplicates pointing here…
My situation is simpler:
a[href='#something']
)e.preventDefault()
$("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
window.location = link;
This way, the scroll occurs, and there's no jump when the location is updated.
Instead of use set_userdata you should use set_flashdata.
According to CI user guide:
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
Using dplyr you can:
df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))
You cannot use WHILE
like that; see: mysql DECLARE WHILE outside stored procedure how?
You have to put your code in a stored procedure. Example:
CREATE PROCEDURE myproc()
BEGIN
DECLARE i int DEFAULT 237692001;
WHILE i <= 237692004 DO
INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
SET i = i + 1;
END WHILE;
END
Fiddle: http://sqlfiddle.com/#!2/a4f92/1
Alternatively, generate a list of INSERT
statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:
for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done
By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.
Close the cursor, if it is empty then deallocate it:
IF CURSOR_STATUS('global','myCursor') >= -1
BEGIN
IF CURSOR_STATUS('global','myCursor') > -1
BEGIN
CLOSE myCursor
END
DEALLOCATE myCursor
END
DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.
This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.
Image Mapster is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.
It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.
There are a few examples on the web site that show most of the features. The github repository also has more examples and complete documentation.
Vendor independent version, solely relies on ADO.NET interfaces; 2 ways:
public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
using (var conn = new T())
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Connection.ConnectionString = _connectionString;
cmd.Connection.Open();
var table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
}
public DataTable Read2<S, T>(string query) where S : IDbConnection, new()
where T : IDbDataAdapter, IDisposable, new()
{
using (var conn = new S())
{
using (var da = new T())
{
using (da.SelectCommand = conn.CreateCommand())
{
da.SelectCommand.CommandText = query;
da.SelectCommand.Connection.ConnectionString = _connectionString;
DataSet ds = new DataSet(); //conn is opened by dataadapter
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
I did some performance testing, and the second approach always outperformed the first.
Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
dt = Read1<MySqlConnection>(query); // ~9800ms
dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms
dt = Read1<SQLiteConnection>(query); // ~4000ms
dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms
dt = Read1<SqlCeConnection>(query); // ~5700ms
dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms
dt = Read1<SqlConnection>(query); // ~850ms
dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms
dt = Read1<VistaDBConnection>(query); // ~3900ms
dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
Read1
looks better on eyes, but data adapter performs better (not to confuse that one db outperformed the other, the queries were all different). The difference between the two depended on query though. The reason could be that Load
requires various constraints to be checked row by row from the documentation when adding rows (its a method on DataTable
) while Fill
is on DataAdapters which were designed just for that - fast creation of DataTables.
If your input was structured as XML, you could use the importXML
function. (More info here at quirksmode).
If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.
I've always used Baretail for tailing in Windows. It's free and pretty nice.
Edit: for a better description of Baretail see this question
To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:
.glyphicon-refresh.spinning {
transform-origin: 48% 50%;
}
If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
src:
local('DejaVu Sans'),
local('DejaVu-Sans'), /* Duplicated name with hyphen */
url('dejavu/DejaVuSans.ttf')
format('truetype');
}
/*bold version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Bold.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Bold.ttf')
format('truetype');
font-weight: bold;
}
/*italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Oblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Oblique.ttf')
format('truetype');
font-style: italic;
}
/*bold italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-BoldOblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-BoldOblique.ttf')
format('truetype');
font-weight: bold;
font-style: italic;
}
From a 'SQL the language' perspective the two constructs are equivalent and which one you choose is one of those 'lifestyle' choices we all have to make. I think there is a good case for DISTINCT being more explicit (and therefore is more considerate to the person who will inherit your code etc) but that doesn't mean the GROUP BY construct is an invalid choice.
I think this 'GROUP BY is for aggregates' is the wrong emphasis. Folk should be aware that the set function (MAX, MIN, COUNT, etc) can be omitted so that they can understand the coder's intent when it is.
The ideal optimizer will recognize equivalent SQL constructs and will always pick the ideal plan accordingly. For your real life SQL engine of choice, you must test :)
PS note the position of the DISTINCT keyword in the select clause may produce different results e.g. contrast:
SELECT COUNT(DISTINCT C) FROM myTbl;
SELECT DISTINCT COUNT(C) FROM myTbl;
If Color
is something that is specific to just Car
s then that is the way you would limit its scope. If you are going to have another Color
enum that other classes use then you might as well make it global (or at least outside Car
).
It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify Car::Color
in the function's interface.
int number = 1234567890;
Convert.ToDecimal(number).ToString("#,##0.00");
You will get the result 1,234,567,890.00
.
What features in github are you looking for?
If you don't want the collaboration, pull requests etc. but just want your own repositories to be viewable, git instaweb
will create something for you.
Edit!: Please be sure that you should have both Python installed on your computer.
Maybe my answer is late for you but I can help someone who has the same problem!
You don't have to download both Anaconda
.
If you are using Spyder
and Jupyter
in Anaconda environmen and,
If you have already Anaconda 2 type in Terminal:
python3 -m pip install ipykernel
python3 -m ipykernel install --user
If you have already Anaconda 3 then type in terminal:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
Then before use Spyder
you can choose Python environment like below!
Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!
Also this is Jupyter. You can choose python version like this!
I hope it will help.
You probably don't have the correct permissions. Try adding yourself to these groups.
sudo adduser username ttyl
sudo adduser username serial
sudo adduser username uucp
Then restart your system and check if you got added to the groups.
groups username
Good Luck!
https://firebase.google.com/docs/auth/web/manage-users
You have to add an auth state change observer.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
If you want see your buffer size in terminal, you can take a look at:
/proc/sys/net/ipv4/tcp_rmem
(for read) /proc/sys/net/ipv4/tcp_wmem
(for write)They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.
**
**
Since you wanna get all columns from the table, you can collect all of the data and then filter it using Collections function called Unique
// Get all users with unique name
User::all()->unique('name')
or
// Get all & latest users with unique name
User::latest()->get()->unique('name')
For more information you can check Laravel Collection Documentations
EDIT: You might have issue with perfomance, by using Unique() you'll get all data first from User table, and then Laravel will filter it. This way isn't good if you have lots of Users data. You can use query builder and call each fields that you wanna use, example:
User::select('username','email','name')->distinct('name')->get();
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains
method.
if(Arrays.asList(codes).contains(userCode))
Here is a solution using the plyr
package.
The following line of code essentially tells ddply
to first group your data by Group, and then within each group returns a subset where the Score equals the maximum score in that group.
library(plyr)
ddply(data, .(Group), function(x)x[x$Score==max(x$Score), ])
Group Score Info
1 1 3 c
2 2 4 d
And, as @SachaEpskamp points out, this can be further simplified to:
ddply(df, .(Group), function(x)x[which.max(x$Score), ])
(which also has the advantage that which.max
will return multiple max lines, if there are any).
puts `date`
puts $?
Mon Mar 7 19:01:15 PST 2016
pid 13093 exit 0
There are two ways,
android:screenOrientation="portrait"
for each Activity in Manifest Filethis.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
in each java file.String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);
Now lastString
has the value "directory"
For Amazon AWS ECS/ECR, you should manage your environment variables (especially secrets) via a private S3 bucket. See blog post How to Manage Secrets for Amazon EC2 Container Service–Based Applications by Using Amazon S3 and Docker.
Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
Andrezj's pretty much got it nailed... but here's an easy cross-browser solution.
Take a form like this:
<form>
<input/>
<button type="submit" value="some non-default action"/>
<button type="submit" value="another non-default action"/>
<button type="submit" value="yet another non-default action"/>
<button type="submit" value="default action"/>
</form>
and refactor to this:
<form>
<input/>
<button style="overflow: visible !important; height: 0 !important; width: 0 !important; margin: 0 !important; border: 0 !important; padding: 0 !important; display: block !important;" type="submit" value="default action"/>
<button type="submit" value="some non-default action"/>
<button type="submit" value="another non-default action"/>
<button type="submit" value="yet another non-default action"/>
<button type="submit" value="still another non-default action"/>
<button type="submit" value="default action"/>
</form>
Since the W3C spec indicates multiple submit buttons are valid, but omits guidance as to how the user-agent should handle them, the browser manufacturers are left to implement as they see fit. I've found they'll either submit the first submit button in the form, or submit the next submit button after the form field that currently has focus.
Unfortunately, simply adding a style of display: none; won't work because the W3C spec indicates any hidden element should be excluded from user interactions. So hide it in plain sight instead!
Above is an example of the solution I ended up putting into production. Hitting the enter key triggers the default form submission is behavior as expected, even when other non-default values are present and precede the default submit button in the DOM. Bonus for mouse/keyboard interaction with explicit user inputs while avoiding javascript handlers.
Note: tabbing through the form will not display focus for any visual element yet will still cause the invisible button to be selected. To avoid this issue, simply set tabindex attributes accordingly and omit a tabindex attribute on the invisible submit button. While it may seem out of place to promote these styles to !important, they should prevent any framework or existing button styles from interfering with this fix. Also, those inline styles are definitely poor form, but we're proving concepts here... not writing production code.
The following code will open the menu on the initial focus, but won't get stuck in an infinite loop when the selection re-focuses after the menu closes.
// on first focus (bubbles up to document), open the menu
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {
$(this).closest(".select2-container").siblings('select:enabled').select2('open');
});
// steal focus during close - only capture once and stop propogation
$('select.select2').on('select2:closing', function (e) {
$(e.target).data("select2").$selection.one('focus focusin', function (e) {
e.stopPropagation();
});
});
Note: The focus
event is fired twice
We can prevent an infinite loop by looking for differences between the types of focus events. Since we only want to open the menu on the initial focus to the control, we have to somehow distinguish between the following raised events:
Doing so it a cross browser friendly way is hard, because browsers send different information along with different events and also Select2 has had many minor changes to their internal firing of events, which interrupt previous flows.
One way that seems to work is to attach an event handler during the closing
event for the menu and use it to capture the impending focus
event and prevent it from bubbling up the DOM. Then, using a delegated listener, we'll call the actual focus -> open code only when the focus
event bubbles all the way up to the document
As noted in this github issue #4025 - Dropdown does not open on tab focus, we should check to make sure we only call 'open'
on :enabled
select elements like this:
$(this).siblings('select:enabled').select2('open');
We have to traverse the DOM a little bit, so here's a map of the HTML structure generated by Select2
Here are some of the relevant code sections in play:
.on('mousedown'
... .trigger('toggle')
.on('toggle'
... .toggleDropdown()
.toggleDropdown
... .open()
.on('focus'
... .trigger('focus'
.on('close'
... $selection.focus()
It used to be the case that opening select2 fired twice, but it was fixed in Issue #3503 and that should prevent some jank
PR #5357 appears to be what broke the previous focus code that was working in 4.05
$('.select2').select2({});_x000D_
_x000D_
// on first focus (bubbles up to document), open the menu_x000D_
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {_x000D_
$(this).closest(".select2-container").siblings('select:enabled').select2('open');_x000D_
});_x000D_
_x000D_
// steal focus during close - only capture once and stop propogation_x000D_
$('select.select2').on('select2:closing', function (e) {_x000D_
$(e.target).data("select2").$selection.one('focus focusin', function (e) {_x000D_
e.stopPropagation();_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"></script>_x000D_
_x000D_
<select class="select2" style="width:200px" >_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Carrot</option>_x000D_
<option value="4">Donut</option>_x000D_
</select>
_x000D_
Tested on Chrome, FF, Edge, IE11
In Windows, you could use:
const std::wstring hex = L"0x13";
const std::wstring dec = L"19";
int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
std::cout << ret << "\n";
}
if (StrToIntEx(dec.c_str(), STIF_SUPPORT_HEX, &ret)) {
std::cout << ret << "\n";
}
strtol
,stringstream
need to specify the base if you need to interpret hexdecimal.
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date
and not java.sql.Date
-- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
The question mixes two issues here:
git status
says nothing to commit, working directory clean.
The one-stop-answer is:
git fetch --prune
(optional) Updates the local snapshot of the remote repo. Further commands are local only.git reset --hard @{upstream}
Puts the local branch pointer to where the snapshot of the remote is, as well as set the index and the working directory to the files of that commit.git clean -d --force
Removes untracked files and directories which hinder git to say “working directory clean”.Easy, just define your own function that does what you want:
def enum(seq, start=0):
for i, x in enumerate(seq):
yield i+start, x
in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
First:
FirstOrDefault:
From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
With localStorage
, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Large amounts of data can be stored locally, without affecting website performance. Although localStorage
is more modern, there are some pros and cons to both techniques.
Pros
Cons
Pros
Cons
localStorage
usage is almost identical with the session one. They have pretty much exact methods, so switching from session to localStorage
is really child's play. However, if stored data is really crucial for your application, you will probably use cookies as a backup in case localStorage
is not available. If you want to check browser support for localStorage
, all you have to do is run this simple script:
/*
* function body that test if storage is available
* returns true if localStorage is available and false if it's not
*/
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
/*
* execute Test and run our custom script
*/
if(lsTest()) {
// window.sessionStorage.setItem(name, 1); // session and storage methods are very similar
window.localStorage.setItem(name, 1);
console.log('localStorage where used'); // log
} else {
document.cookie="name=1; expires=Mon, 28 Mar 2016 12:00:00 UTC";
console.log('Cookie where used'); // log
}
"localStorage values on Secure (SSL) pages are isolated" as someone noticed keep in mind that localStorage will not be available if you switch from 'http' to 'https' secured protocol, where the cookie will still be accesible. This is kind of important to be aware of if you work with secure protocols.
nothing to be done for running your wamp sites to another computer. 1. first turn off the firewall. 2. Set Put Online in wamp by clcking in wamp icon at near to clock.
Finally run your browser in another computer and type http:\ip address or computer name e.g. http:\192.168.1.100
Try put this before send e-mail
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };
Remenber to add the using libs!
you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.
"
is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value=""asd">Test</option>_x000D_
</select>
_x000D_
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in
clause...
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.
When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.
Hope this helps any others having a similar issue.
To use the parent of an element use parentElement
:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
<?php
$url1 = '/test?a=4&b=3';
$url2 = 'www.baidu.com/test?a=4&b=3&try_count=1';
$url3 = 'http://www.baidu.com/test?a=4&b=3&try_count=2';
$url4 = '/test';
function add_or_update_params($url,$key,$value){
$a = parse_url($url);
$query = $a['query'] ? $a['query'] : '';
parse_str($query,$params);
$params[$key] = $value;
$query = http_build_query($params);
$result = '';
if($a['scheme']){
$result .= $a['scheme'] . ':';
}
if($a['host']){
$result .= '//' . $a['host'];
}
if($a['path']){
$result .= $a['path'];
}
if($query){
$result .= '?' . $query;
}
return $result;
}
echo add_or_update_params($url1,'try_count',1);
echo "\n";
echo add_or_update_params($url2,'try_count',2);
echo "\n";
echo add_or_update_params($url3,'try_count',3);
echo "\n";
echo add_or_update_params($url4,'try_count',4);
echo "\n";
Please try below code to check checkbox is checked or not
$(document).ready(function(){
$("#isAgeSelected").on('change',function(){
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show(); // checked
else{
$("#txtAge").hide(); // unchecked
}
});
});
it is solved in react-router-dom 4.4.0 see: Route's proptypes fail
now it is beta, or just wait for final release.
npm install [email protected] --save
If you have the xsd of the xml message then you can generate c# classes using the .Net xsd.exe tool.
This .Net classes can then be used to generate the xml.
I use this function to convert string to tuple
import ast
def parse_tuple(string):
try:
s = ast.literal_eval(str(string))
if type(s) == tuple:
return s
return
except:
return
Usage
parse_tuple('("A","B","C",)') # Result: ('A', 'B', 'C')
In your case, you do
value = parse_tuple("('%s',)" % a)
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM
, return-path
.
svn log --verbose -r 42
Use htmlentities() to convert characters that would otherwise be displayed as HTML.
Update for Bootstrap 5 (2020)
Bootstrap 5 (currently alpha) has a new xxl breakpoint. Therefore display classes have a new tier to support this:
Hidden only on xxl: d-xxl-none
Visible only on xxl: d-none d-xxl-block
Bootstrap 4 (2018)
The hidden-*
and visible-*
classes no longer exist in Bootstrap 4. If you want to hide an element on specific tiers or breakpoints in Bootstrap 4, use the d-*
display classes accordingly.
Remember that extra-small/mobile (formerly xs
) is the default (implied) breakpoint, unless overridden by a larger breakpoint. Therefore, the -xs
infix no longer exists in Bootstrap 4.
Show/hide for breakpoint and down:
hidden-xs-down (hidden-xs)
= d-none d-sm-block
hidden-sm-down (hidden-sm hidden-xs)
= d-none d-md-block
hidden-md-down (hidden-md hidden-sm hidden-xs)
= d-none d-lg-block
hidden-lg-down
= d-none d-xl-block
hidden-xl-down
(n/a 3.x) = d-none
(same as hidden
)Show/hide for breakpoint and up:
hidden-xs-up
= d-none
(same as hidden
)hidden-sm-up
= d-sm-none
hidden-md-up
= d-md-none
hidden-lg-up
= d-lg-none
hidden-xl-up
(n/a 3.x) = d-xl-none
Show/hide only for a single breakpoint:
hidden-xs
(only) = d-none d-sm-block
(same as hidden-xs-down
)hidden-sm
(only) = d-block d-sm-none d-md-block
hidden-md
(only) = d-block d-md-none d-lg-block
hidden-lg
(only) = d-block d-lg-none d-xl-block
hidden-xl
(n/a 3.x) = d-block d-xl-none
visible-xs
(only) = d-block d-sm-none
visible-sm
(only) = d-none d-sm-block d-md-none
visible-md
(only) = d-none d-md-block d-lg-none
visible-lg
(only) = d-none d-lg-block d-xl-none
visible-xl
(n/a 3.x) = d-none d-xl-block
Demo of the responsive display classes in Bootstrap 4
Also, note that d-*-block
can be replaced with d-*-inline
, d-*-flex
, d-*-table-cell
, d-*-table
etc.. depending on the display type of the element. Read more on the display classes
I found a workaround over on GitHub: https://github.com/jmhofer/eCobertura/issues/8
For those who don't want to click the link, here's the text of the comment:
Good workaround: Create a run configuration with a filter, that excludes everything ("*") and let it run just a single test. Name it "Undo coverage".
I did this and it worked quite well in Eclipse Juno.
Credit for this goes to UsulSK.
In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.
When the DragEnter
event fires, set the argument's AllowedEffect
to something other than none (e.g. e.Effect = DragDropEffects.Move
).
When the DragDrop
event fires, you'll get a list of strings. Each string is the full path to the file being dropped.
If you are using a custom header view:
class YourCustomHeaderFooterView: UITableViewHeaderFooterView {
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = .white //Or any color you want
}
}
For those that are on Mac OSX, perhaps the easiest way to work around this is to use ditto (only on the mac, AFAIK, though). It will create the directory structure that is missing in the destination.
For instance, I did this
ditto 6.3.2/6.3.2/macosx/bin/mybinary ~/work/binaries/macosx/6.3.2/
where ~/work
did not contain the binaries directory before I ran the command.
I thought rsync should work similarly, but it seems it only works for one level of missing directories. That is,
rsync 6.3.3/6.3.3/macosx/bin/mybinary ~/work/binaries/macosx/6.3.3/
worked, because ~/work/binaries/macosx existed but not ~/work/binaries/macosx/6.3.2/
In my case, this was due to my library not being configured as 'android'.
E.g. apply plugin:'java'
instead of apply plugin:'com.android.library'
Shift + Insert usually works throughout X11.
That would only happen if PostCode
is missing a space.
You could add conditionality such that all of PostCode
is retrieved should a space not be found as follows
select SUBSTRING(PostCode, 1 ,
case when CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode)
else CHARINDEX(' ', PostCode) -1 end)
Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.
I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes
$container.scrollTo( targetPosition );
But that's not all. We need to fix the target position, too. The calculation you see in other answers,
$target.offset().top - $container.offset().top + $container.scrollTop()
mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.
Hence, a better way to calculate the target position is
var target = $target[0],
container = $container[0];
targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;
Again, have a look at the demo to see it in action.
For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.
In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.
I have the same problem, but I resolved adding jquery.min.js before angular.min.js.
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
That is all the language has to say, as far as C++03 is concerned.
Just Adding Instance Properties
For example, all components can access a global appName
, you just write one line code:
Vue.prototype.$appName = 'My App'
$
isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties.
The syntax is
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
Bypass SSL Certificate....
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
var client = new HttpClient(clientHandler)
Close nodejs app
running in another shell.
Restart the terminal and run the program again.
Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port
and run the app.
To find the PID of the application that is using port:8000
$ fuser 8000/tcp
8000/tcp: 16708
Here PID is 16708 Now kill the process using the kill [PID]
command
$ kill 16708
Not sure if this is helpful for you, but removing the container always helps.
So, if you use docker-compose for your setup, you can simply use docker-compose down && docker-compose up
instead of docker-compose restart
. With a proper setup (make sure to use volume mounts for persistent data), you don't lose any data this way.
Sure, this is more than the OP requested. But there are various situations where the other answers cannot help (if using a remote docker server or working on a Windows machine, accessing the underlying filesystem is proprietary and difficult)
you can include maven dependency like below in your pom.xml file
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
If you're interested in producing HTML5 hybrid applications (web apps wrapped in a native container giving access to device functions), the Nomad Visual Studio extension supports building for android devices.
It’s just HTML with Server Side Includes.
Try this:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!
And pay attention for one detail here:
In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000
Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...
I don't have IE8 to test this out, but I'm pretty sure it should work:
<div class="screen">
<!-- code -->
<div class="innerdiv">
text or other content
</div>
</div>
and the css:
.screen{
position: relative;
}
.innerdiv {
position: absolute;
bottom: 0;
right: 0;
}
This should place the .innerdiv in the bottom-right corner of the .screen class. I hope this helps :)
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView
in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
first it will convert 12 hours time into 24 hours then it will take diff between two times
String a = "09/06/18 01:55:33 AM";
String b = "07/06/18 05:45:33 PM";
String [] b2 = b.split(" ");
String [] a2 = a.split(" ");
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
String time1 = null ;
String time2 = null ;
if ( a.contains("PM") && b.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = displayFormat.format(date);
time2 = b2[1];
}else if (b.contains("PM") && a.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = a2[1];
time2 = displayFormat.format(date);
}else if (a.contains("PM") && b.contains("PM")){
Date datea = parseFormat.parse(a2[1]+" PM");
Date dateb = parseFormat.parse(b2[1]+" PM");
time1 = displayFormat.format(datea);
time2 = displayFormat.format(dateb);
}
System.out.println(time1);
System.out.println(time2);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference);
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
For More Details Click Here
I tested this one and it works
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be
I would recommend the rename
command for this. Type ren /?
at the command line for more help.
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})
uses a text type but forces the appearance of the numeric keyboard
<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">
the inputmode tag is the solution
If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION
.
Merging two arrays:
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var result=arr1.concat(arr2);
// result: [{name: "lang", value: "English"}, {name: "age", value: "18"}, {name : "childs", value: '5'}, {name: "lang", value: "German"}]
Merging two arrays without duplicated values for 'name':
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var i,p,obj={},result=[];
for(i=0;i<arr1.length;i++)obj[arr1[i].name]=arr1[i].value;
for(i=0;i<arr2.length;i++)obj[arr2[i].name]=arr2[i].value;
for(p in obj)if(obj.hasOwnProperty(p))result.push({name:p,value:obj[p]});
// result: [{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
You can do somthing like :
if (product != null) {
var products = Repository.Products;
var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
Repository.Products[indexOf] = product;
// or
Repository.Products[indexOf].prop = product.prop;
}
Concatenation of words in the package name is something most developers don't do.
You can use something like.
com.stackoverflow.mypackage
Refer JLS Name Declaration
That should do the trick:
echo `pwd`/`dirname $0`
It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).
json
is a built-in module, you don't need to install it with pip
.
If you need use it as a default configuration, just place min: 0
inside the node defaults.scale.ticks
, as follows:
defaults: {
global: {...},
scale: {
...
ticks: { min: 0 },
}
},
Reference: https://www.chartjs.org/docs/latest/axes/
This code is perfectly working for me.
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
[label setFont:[UIFont systemFontOfSize:11]];
Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.
Read regular-expression.info for more details.
Syntax:
(?=REGEX_1)REGEX_2
Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.
example:
(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}
REGEX_1 is [a-z0-9]{4}$
which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3}
which matches one or two letters followed by two or three digits.
REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.
Syntax:
(?!REGEX_1)REGEX_2
Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.
example:
(?!.*\bFWORD\b)\w{10,30}$
The look-ahead part checks for the FWORD
in the string and fails if it finds it. If it doesn't find FWORD
, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_
Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.
The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue
in such a case, and unlike the currently accepted answer, will not throw an exception.
dt2.GetValueOrDefault().ToString(format);
The compareTo method is described as follows:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Let's say we would like to compare Jedis by their age:
class Jedi implements Comparable<Jedi> {
private final String name;
private final int age;
//...
}
Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.
public int compareTo(Jedi jedi){
return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
By implementing the compareTo
method (coming from the Comparable
interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.
There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable
then you can do the comparison using its compareTo
method.
public int compareTo(Jedi jedi){
return this.name.compareTo(jedi.getName());
}
It would be simpler in this case.
Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.
public int compareTo(Jedi jedi){
int result = this.name.compareTo(jedi.getName());
if(result == 0){
result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}
return result;
}
If you had an array of Jedis
Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}
All you have to do is to ask to the class java.util.Arrays
to use its sort method.
Arrays.sort(jediAcademy);
This Arrays.sort
method will use your compareTo
method to sort the objects one by one.
For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version
Use CDATA in the below way for formatting your text
<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
<b>
<![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
]]>
</b>
</string>
Just add any tag you want before the <![CDATA[
and you will get your proper output.
Nobody mentioned it so far... with utf8mb4 which is 4-byte and can also store emoticons (we should never more use 3-byte utf8) and we can avoid errors like Incorrect string value: \xF0\x9F\x98\...
we should not use typical VARCHAR(255) but rather VARCHAR(191) because in case utf8mb4 and VARCHAR(255) same part of data are stored off-page and you can not create index for column VARCHAR(255) but for VARCHAR(191) you can. It is because the maximum indexed column size is 767 bytes for ROW_FORMAT=COMPACT or ROW_FORMAT=REDUNDANT.
For newer row formats ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED (which requires newer file format innodb_file_format=Barracuda not older Antelope) maximum indexed column size is 3072. It is available since MySQL >= 5.6.3 when innodb_large_prefix=1 (disabled by default for MySQL <= 5.7.6 and enabled by default for MySQL >= 5.7.7). So in this case we can use VARCHAR(768) for utf8mb4 (or VARCHAR(1024) for old utf8) for indexed column. Option innodb_large_prefix is deprecated since 5.7.7 because its behavior is built-in MySQL 8 (in this version is option removed).
Try this out with using If ELSE If conditions. You can validate your editText fields easily.
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.
That said, you can do it as That One Random Scrub proposed, using try: ... except:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".
But you can also easily test for existence:
import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
fh = open(fn, "r")
else:
fh = open(fn, "w")
Note: use raw_input() instead of input(), because input() will try to execute the entered text. If you accidently want to test for file "import", you'd get a SyntaxError.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
In Debian NGINX environment i did the following.
Goto /etc/mysql/mysql.conf.d
edit mysqld.cnf
if you find log-error = /var/log/mysql/error.log
add the following 2 lines bellow it.
general_log_file = /var/log/mysql/mysql.log
general_log = 1
To see the logs goto /var/log/mysql
and tail -f mysql.log
Remember to comment these lines out once you are done with debugging if you are in production environment delete mysql.log
as this log file will grow quickly and can be huge.
Change
JSONObject objects = getArray.getJSONArray(i);
to
JSONObject objects = getArray.getJSONObject(i);
or to
JSONObject objects = getArray.optJSONObject(i);
depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject
will work for you.)
Then, to access the string elements in the "objects" JSONObject
, get them out by element name.
String a = objects.get("A");
If you need the names of the elements in the JSONObject
, you can use the static utility method JSONObject.getNames(JSONObject)
to do so.
String[] elementNames = JSONObject.getNames(objects);
"Get the value for the first element and the value for the last element."
If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1
.
I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.
The following code does exactly that.
import org.json.JSONArray;
import org.json.JSONObject;
public class Foo
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";
// "I want to iterate though the objects in the array..."
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
// "...and get thier component and thier value."
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c
5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3
4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
If you already have var parent = document.querySelector('.parent');
you can do this to scope the search to parent
's children:
parent.querySelector('.child')
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. text
Generally issues like this are related to any of the following need to be looked at:
Try connecting to sql server with sql management server on the system that sql server is installed on and work from there. Pay attention to information in the errorlogs.
Try giving a Width in % to the image in the carousel?
.item img {
width:100%;
}
YOUR ECLIPSE MAYBE CHANGED SHA1 KEY, so you must regen your google key with new SHA1 key in here: https://console.developers.google.com/project/watchful-net-796/apiui/credential After that, copy new key into manifest and reload this google page some times, and your key will be updated, rebuild your project, it will work. P/S: For my error, I deleted .android folder so eclipse regen SHA1.
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.
If you "require" 'exampleDirective' from another directive + your logic is in 'exampleDirective's' controller (let's say 'exampleCtrl'):
app.directive('exampleDirective', function () {
return {
restrict: 'A',
scope: false,
bindToController: {
myCallback: '&exampleFunction'
},
controller: 'exampleCtrl',
controllerAs: 'vm'
};
});
app.controller('exampleCtrl', function () {
var vm = this;
vm.myCallback();
});
This snippet uses wmic.exe to build the date string. It isn't mangled by locale settings
rem DATE as YYYY-MM-DD via WMIC.EXE
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set RDATE=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%
The reason why the StaleElementReferenceException
occurs has been laid out already: updates to the DOM between finding and doing something with the element.
For the click-Problem I've recently used a solution like this:
public void clickOn(By locator, WebDriver driver, int timeout)
{
final WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(locator)));
driver.findElement(locator).click();
}
The crucial part is the "chaining" of Selenium's own ExpectedConditions
via the ExpectedConditions.refreshed()
. This actually waits and checks if the element in question has been refreshed during the specified timeout and additionally waits for the element to become clickable.
Have a look at the documentation for the refreshed method.
Tip for 1 website resizing the height. But you can change to 2 websites.
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.
You know what, there is an entire library for canvas graphics. It is called p5.js You can add it with just a single line in your head element and an additional sketch.js file.
Do this to your html and body tags first:
<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">
Add this to your head:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>
The sketch.js file
function setup() {
createCanvas(windowWidth, windowHeight);
background(r, g, b);
}
After struggling with all available options, I ended up writing a JWT token based SessionStore provider (the session travels inside a cookie, and no backend storage is needed).
http://www.drupalonwindows.com/en/content/token-sessionstate
Advantages:
Adding more options to the answer.
You could use npm i sweetalert2
Don't forget to add the style to your angular.json
"styles": [
...
"node_modules/sweetalert2/src/sweetalert2.scss"
]
Then just import,
// ES6 Modules or TypeScript
import Swal from 'sweetalert2'
// CommonJS
const Swal = require('sweetalert2')
Boom, you are ready to go.
Swal.fire({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, keep it'
}).then((result) => {
if (result.value) {
Swal.fire(
'Deleted!',
'Your imaginary file has been deleted.',
'success'
)
// For more information about handling dismissals please visit
// https://sweetalert2.github.io/#handling-dismissals
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire(
'Cancelled',
'Your imaginary file is safe :)',
'error'
)
}
})
More on this:- https://www.npmjs.com/package/sweetalert2
I do hope this helps someone.
Thanks.
I'm looking into using SSTJ for FFTs in Java. It can redirect via JNI to FFTW if the library is available or will use a pure Java implementation if not.
Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)
Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))
I found this while googling, I found best working for me...
HTML
<div class="img"></div>
CSS
.img {
background-color: red;
width: 60px;
height: 60px;
-webkit-mask-image: url('http://i.stack.imgur.com/gZvK4.png');
}
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
I get this error, and other strange git errors, when I have a server running (in Intellij). Stopping the server and re-trying the git command frequently fixes it for me.
THX for this question! Works good for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}
If you are using Swift, remember that println
will only print to the debug log (which appears in xCode's debug area). If you want to print to system.log, you have to use NSLog
as in the old days.
Then you can view the simulator log via its menu, Debug > Open System Log... (cmd + /)
Use this CSS for Modal and modal-dialog
.modal{
pointer-events: none;
}
.modal-dialog{
pointer-events: all;
}
This can resolve your problem in Modal
Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.
Duration using FileOutputStream byte stream: 4 965 078
Duration using BufferedOutputStream: 1 237 206
Duration using (character text Reader: 2 858 875
Duration using BufferedReader(Buffered character text stream: 1 998 005
Duration using (Files NIO copy): 18 351 115
when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.
I'm surprised to see all answers stating the use of alt
attribute in a
tag is not valid. This is absolutely wrong.
Html does not block you using any attributes:
<a your-custom-attribute="value">Any attribute can be used</a>
If you ask if it is semantically correct to use alt
attribute in a
then I will say:
NO. It is used to set image description <img alt="image description" />
.
It is a matter of what you'd do with the attributes. Here's an example:
a::after {_x000D_
content: attr(color); /* attr can be used as content */_x000D_
display: block;_x000D_
color: white;_x000D_
background-color: blue;_x000D_
background-color: attr(color); /* This won't work */_x000D_
display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
display: block;_x000D_
}_x000D_
[hidden] {_x000D_
display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
Again, if you ask if it is semantically correct to use custom attribute then I will say:
No. Use data-*
attributes for its semantic use.
Oops, question was asked in 2013.
You have three options:
if you want to reset to the remote tracking branch in a generic way use:
git fetch
git reset --keep origin/$(git rev-parse --abbrev-ref HEAD)
if you want to reset your local changes too:
git fetch
git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)
If your Pycharm 2016.1.4v and higher you should use
"default path" /K "<path-to-your-activate.bat>"
don't forget quotes
The authenticity token is used to prevent Cross-Site Request Forgery attacks (CSRF). To understand the authenticity token, you must first understand CSRF attacks.
Suppose that you are the author of bank.com
. You have a form on your site that is used to transfer money to a different account with a GET request:
A hacker could just send an HTTP request to the server saying GET /transfer?amount=$1000000&account-to=999999
, right?
Wrong. The hackers attack won't work. The server will basically think?
Huh? Who is this guy trying to initiate a transfer. It's not the owner of the account, that's for sure.
How does the server know this? Because there's no session_id
cookie authenticating the requester.
When you sign in with your username and password, the server sets a session_id
cookie on your browser. That way, you don't have to authenticate each request with your username and password. When your browser sends the session_id
cookie, the server knows:
Oh, that's John Doe. He signed in successfully 2.5 minutes ago. He's good to go.
A hacker might think:
Hmm. A normal HTTP request won't work, but if I could get my hand on that
session_id
cookie, I'd be golden.
The users browser has a bunch of cookies set for the bank.com
domain. Every time the user makes a request to the bank.com
domain, all of the cookies get sent along. Including the session_id
cookie.
So if a hacker could get you to make the GET request that transfers money into his account, he'd be successful. How could he trick you into doing so? With Cross Site Request Forgery.
It's pretty simply, actually. The hacker could just get you to visit his website. On his website, he could have the following image tag:
<img src="http://bank.com/transfer?amount=$1000000&account-to=999999">
When the users browser comes across that image tag, it'll be making a GET request to that url. And since the request comes from his browser, it'll send with it all of the cookies associated with bank.com
. If the user had recently signed in to bank.com
... the session_id
cookie will be set, and the server will think that the user meant to transfer $1,000,000 to account 999999!
Well, just don't visit dangerous sites and you'll be fine.
That isn't enough. What if someone posts that image to Facebook and it appears on your wall? What if it's injected into a site you're visiting with a XSS attack?
It's not so bad. Only GET requests are vulnerable.
Not true. A form that sends a POST request can be dynamically generated. Here's the example from the Rails Guide on Security:
<a href="http://www.harmless.com/" onclick="
var f = document.createElement('form');
f.style.display = 'none';
this.parentNode.appendChild(f);
f.method = 'POST';
f.action = 'http://www.example.com/account/destroy';
f.submit();
return false;">To the harmless survey</a>
When your ApplicationController
has this:
protect_from_forgery with: :exception
This:
<%= form_tag do %>
Form contents
<% end %>
Is compiled into this:
<form accept-charset="UTF-8" action="/" method="post">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
Form contents
</form>
In particular, the following is generated:
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
To protect against CSRF attacks, if Rails doesn't see the authenticity token sent along with a request, it won't consider the request safe.
How is an attacker supposed to know what this token is? A different value is generated randomly each time the form is generated:
A Cross Site Scripting (XSS) attack - that's how. But that's a different vulnerability for a different day.
In the POSIX standard, which /bin/sh
is supposed to respect, the command is .
(a single dot), not source
. The source
command is a csh
-ism that has been pulled into bash
.
Try
. $env_name/bin/activate
Or if you must have non-POSIX bash
-isms in your code, use #!/bin/bash
.
That is not changing due to the default theme set to the screen.
So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()
child: new Theme(
data: new ThemeData(
primaryColor: Colors.redAccent,
primaryColorDark: Colors.red,
),
child: new TextField(
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.teal)),
hintText: 'Tell us about yourself',
helperText: 'Keep it short, this is just a demo.',
labelText: 'Life story',
prefixIcon: const Icon(
Icons.person,
color: Colors.green,
),
prefixText: ' ',
suffixText: 'USD',
suffixStyle: const TextStyle(color: Colors.green)),
),
));
Try this:
np.concatenate((a, np.array([a[0]])))
http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html
concatenate needs both elements to be numpy arrays; however, a[0] is not an array. That is why it does not work.
Any Python file is a module, its name being the file's base name without the .py
extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py
file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py
file.
The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module
. Note, however, when you import a package, only variables/functions/classes in the __init__.py
file of that package are directly visible, not sub-packages or modules. As an example, consider the xml
package in the Python standard library: its xml
directory contains an __init__.py
file and four sub-directories; the sub-directory etree
contains an __init__.py
file and, among others, an ElementTree.py
file. See what happens when you try to interactively import package/modules:
>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>
In Python there also are built-in modules, such as sys
, that are written in C, but I don't think you meant to consider those in your question.
There is another approach here which basically helps you to forget about the whole management of the requests. It is based on an async queue method and a callable/callback based response. The main advantage is that by using this method you'll be able to make the whole process (request, get and parse response, sabe to db) completely transparent for you. Once you get the response code the work is already done. After that you just need to make a call to your db and you are done. It helps as well with the problematic of what happens when your activity is not active. What will happen here is that you'll have all your data saved in your local database but the response won't be processed by your activity, that's the ideal way.
I wrote about a general approach here http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/
I'll be putting specific sample code in upcoming posts. Hope it helps, feel free to contact me for sharing the approach and solving potential doubts or issues.
After about a half hour of searching and trying to debug this I was able to figure it out. My situation involved me using the same pem file for two different ec2 instance and it working for one and not the other.
My first instance it worked on was the standard aws linux ami amzn-ami-hvm-2014.03.2.x86_64-ebs. I simply used
ssh -i mypemfile.pem ec2-user@myec2ipaddress
and it worked.
I then launched a fedora instance Fedora-x86_64-19-20140407-sda and tried the same command but kept getting:
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
After changing my username from ec2-user to fedora it worked!
ssh -i mypemfile.pem fedora@myec2address
I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.
As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.
As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:
I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query()
twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query))
which should have simply read as if (!$query)
.
Side note: Both '".$var."'
and '$var'
do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_
with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
Note: <input type = "text" name = "var">
- $_POST['var']
match. $_POST['Var']
no match.
Consult:
Error checking references:
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_
to connect with (and querying with).
Consult the following about this:
If you are using the mysql_
API and have no choice to work with it, then consult the following Q&A on Stack:
The mysql_*
functions are deprecated and will be removed from future PHP releases.
You can also add a UNIQUE constraint to (a) row(s).
References:
I had to add X-Frame-Options for IE and Content-Security-Policy for other browsers. So i did something like following.
if allowed_domains.present?
request_host = URI.parse(request.referer)
_domain = allowed_domains.split(" ").include?(request_host.host) ? "#{request_host.scheme}://#{request_host.host}" : app_host
response.headers['Content-Security-Policy'] = "frame-ancestors #{_domain}"
response.headers['X-Frame-Options'] = "ALLOW-FROM #{_domain}"
else
response.headers.except! 'X-Frame-Options'
end
First solution:
1. switch off Xorg access control: xhost +
2. Now start google chrome as normal user "anonymous" :
sudo -i -u anonymous /opt/google/chrome/chrome
3. When done browsing, re-enable Xorg access control:
xhost -
More info : Howto run google-chrome as root
Second solution:
1. Edit the file /opt/google/chrome/google-chrome
2. find exec -a "$0" "$HERE/chrome" "$@"
or exec -a "$0" "$HERE/chrome" "$PROFILE_DIRECTORY_FLAG" \ "$@"
3. change as
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir ”/root/.config/google-chrome”
Third solution:
Run Google Chrome Browser as Root on Ubuntu Linux systems
When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em
. Just don't transition all.
As others have answered, scatter()
or plot()
will generate the plot you want. I suggest two refinements to answers that are already here:
Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.
Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.
import matplotlib.pyplot as plt
import numpy as np
data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
data_in_array = np.array(data)
'''
That looks like array([[ 2, 10],
[ 3, 100],
[ 4, 1000],
[ 5, 100000]])
'''
transposed = data_in_array.T
'''
That looks like array([[ 2, 3, 4, 5],
[ 10, 100, 1000, 100000]])
'''
x, y = transposed
# Here is the OO method
# You could also the state-based methods of pyplot
fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
ax.plot(x, y, 'ro')
ax.plot(x, y, 'b-')
ax.set_yscale('log')
fig.show()
I've also used ax.set_xlim(1, 6)
and ax.set_ylim(.1, 1e6)
to make it pretty.
I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.
Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.
\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits
OPTION 1: Using Angular providered filter comparator parameter
// declaring a comparator method
$scope.filterBy = function(actual, expected) {
return _.contains(expected, actual); // uses underscore library contains method
};
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')(employees, {name: ['a','c']}, $scope.filterBy);
OPTION 2: Using Angular providered filter negation
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')($filter('filter')(employees, {name: '!d'}), {name: '!b'});
Other answers are basically right, thanks to them I was able to restore my default web site, they're just missing some more or less important details.
This was the complete process to restore the Default Web Site in my case (IIS 7 on Windows 7 64bit):
%SystemDrive%\inetpub\wwwroot
Possible issues:
If the newly created web site cannot be started with the following message:
Internet Information Services (IIS) Manager - The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)
...it's possible that port 80 is already assigned to another application (Skype in my case :). You can change the binding port to e.g. 8080 by right clicking Default Web Site and selecting Edit Bindings... and Edit.... See Error 0x80070020 when you try to start a Web site in IIS 7.0 for details. Or you can just close the application sitting on the port 80, of course.
Some applications require Default Web Site to have the ID 1. In my case, it got ID 1 after recreation automatically. If it's not your case, see Re-create “default Website” in IIS after accidentally deleting. It's different for IIS 6 and 7.
Note: I had to recreate the Default Web Site, because I wasn't able to even open a project configured to run under IIS in Visual Studio. I had a solution with a couple of projects inside. One of the projects failed to load with the following error message:
The Web Application Project is configured to use IIS. The Web server 'http://localhost:8080/' could not be found.
After I have recreated the Default Web Site in IIS Manager, I was able to reload and open that specific project.
void htod(String hexadecimal)
{
int h = hexadecimal.length() - 1;
int d = 0;
int n = 0;
for(int i = 0; i<hexadecimal.length(); i++)
{
char ch = hexadecimal.charAt(i);
boolean flag = false;
switch(ch)
{
case '1': n = 1; break;
case '2': n = 2; break;
case '3': n = 3; break;
case '4': n = 4; break;
case '5': n = 5; break;
case '6': n = 6; break;
case '7': n = 7; break;
case '8': n = 8; break;
case '9': n = 9; break;
case 'A': n = 10; break;
case 'B': n = 11; break;
case 'C': n = 12; break;
case 'D': n = 13; break;
case 'E': n = 14; break;
case 'F': n = 15; break;
default : flag = true;
}
if(flag)
{
System.out.println("Wrong Entry");
break;
}
d = (int)(n*(Math.pow(16,h))) + (int)d;
h--;
}
System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}
You can add style to your text:
style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
text-shadow: rgb(255, 255, 255) -2px -2px 0px, rgb(255, 255, 255) -2px 2px 0px,
rgb(255, 255, 255) 2px -2px 0px, rgb(255, 255, 255) 2px 2px 0px;"
White, in this example. Does not work in IE :)
For me only deleting this file : easy-install.pth worked, rest pip install django==1.3.7
It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:
if (typeof(jQuery) != "undefined")
(No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.
function sayHello(name) {
if (name) return "Hello, " + name;
else return "Hello unknown person";
}
sayHello(); // => "Hello unknown person"
If the image is in a container with a responsive width:
HTML
<div class="img-container">
<img src="" alt="">
</div>
CSS
.img-container {
position: relative;
&::after {
content: "";
display: block;
padding-bottom: 100%;
}
img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
}
There's no exact counterpart to Java's getClass()
in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.
Depending on what you need getClass()
for, there are several options in JavaScript:
typeof
instanceof
obj.
constructor
func.
prototype
, proto
.isPrototypeOf
A few examples:
function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42
Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle
param that you can set to false is using gulp or grunt.
You can get entire post body into a POJO. Following is something similar
@RequestMapping(
value = { "/api/pojo/edit" },
method = RequestMethod.POST,
produces = "application/json",
consumes = ["application/json"])
@ResponseBody
public Boolean editWinner( @RequestBody Pojo pojo) {
Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives..
- compile
Make available into class path, don't add this dependency into final jar if it is normal jar; but add this jar into jar if final jar is a single jar (for example, executable jar)
- provided
Dependency will be available at run time environment so don't add this dependency in any case; even not in single jar (i.e. executable jar etc)
Put the things like /src/main/resources/foo/bar.properties
and then reference them as classpath:/foo/bar.properties
.
In this link explain about @model, see a excerpt:
@model
(lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.:@model MyNamespace.Models.MyModel
Later in the file, you can reference the attribute you want with
@Model.Attribute
(uppercase "M").
You can use the following to send an HTTP-POST
request to a URL
and receive the response. I always use this:
try {
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
String u = "B2mGaME";
String au = "gamewrapperB2M";
// String mob = "880xxxxxxxxxx";
params.put("usr", u.toString());
params.put("aut", au.toString());
params.put("uph", MobileNo.toString());
// params.put("uph", mob.toString());
client.post("http://196.6.13.01:88/ws/game_wrapper_reg_check.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
playStatus = response;
//////Get your Response/////
Log.i(getClass().getSimpleName(), "Response SP Status. " + playStatus);
}
@Override
public void onFailure(Throwable throwable) {
super.onFailure(throwable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
You Also need to Add bellow Jar file in libs folder
android-async-http-1.3.1.jar
Finally, I have edit your build.gradle:
dependencies {
compile files('libs/<android-async-http-1.3.1.jar>')
}
In the last Rebuild your project.
You can achieve the desired result by encapsulating the HTML code in a div tag which contains the "required' class followed by the "form-group" class. *however this works only if you have Bootstrap.
<div class="form-group required">
<div class="required">
<label>Name:</label>
<input type="text">
</div>
<div>
Use -F [field separator]
to split the lines on "
s:
awk -F '"' '{print $2}' your_input_file
or for input from pipe
<some_command> | awk -F '"' '{print $2}'
output:
A B
C
D
In Swift 4.2: You can use
myArray.append("Tim") //To add "Tim" into array
or
myArray.insert("Tim", at: 0) //Change 0 with specific location
Just guessing here, but if you have a Byte then couldn't you simply invoke toString() on the object to get the value? Or, glancing at the api, using byteValue()?
CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:
using (CERas.CERAS ceras = new CERas.CERAS())
{
// call some method on ceras
}
For anyone who wants to sort the variable in third layer:
<select ng-option="friend.pet.name for friend in friends"></select>
you can do it like this
<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>
You can use this, in a controller method or in an inline function of a route:
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}else{
die("Could not find the database. Please check your configuration.");
}
} catch (\Exception $e) {
die("Could not open connection to database server. Please check your configuration.");
}
It's been a significant percentage of our business migrating people from Heroku to AWS. There are advantages to both, but it's gets messy on Heroku after a while... once you need a certain level of complexity no longer easy to maintain with Heroku's limitations.
That said, there are increasingly options to have the ease of Heroku and the flexibility of AWS by being on AWS with great frameworks/tools.
I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.
Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).
Modify Global.asax.cs
, including the Application_Start
event with:
Database.SetInitializer<YourDatabaseContext>(
new DropCreateDatabaseIfModelChanges<YourDatabaseContext>());
There is an Excel file with regexps here. You can easily "convert" it to XML and you will be able to determine country by the full phone number.
UPD: The file that I referenced 4 years ago is no longer accessible. I would recommend using Google's libphonenumber.
The answer to Extract code country from phone number [libphonenumber] will show you the proper way to receive country code from a phone number.
Extend UITableView to create function that get indexpath for a view:
extension UITableView {
func indexPath(for view: UIView) -> IndexPath? {
self.indexPathForRow(at: view.convert(.zero, to: self))
}
}
How to use:
let row = tableView.indexPath(for: sender)?.row
when curl
is used to download a large file then CURLOPT_TIMEOUT
is the main option you have to set for.
CURLOPT_RETURNTRANSFER
has to be true in case you are getting file like pdf/csv/image etc.
You may find the further detail over here(correct url) Curl Doc
From that page:
curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins
curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false
Assume the following code:
import torch
import numpy as np
a = torch.tensor([1, 2, 3, 4, 5])
The following three calls have the exact same effect:
res_1 = a.unsqueeze(0)
res_2 = a.view(1, 5)
res_3 = a[np.newaxis,:]
res_1.shape == res_2.shape == res_3.shape == (1,5) # Returns true
Notice that for any of the resulting tensors, if you modify the data in them, you are also modifying the data in a, because they don't have a copy of the data, but reference the original data in a.
res_1[0,0] = 2
a[0] == res_1[0,0] == 2 # Returns true
The other way of doing it would be using the resize_
in place operation:
a.shape == res_1.shape # Returns false
a.reshape_((1, 5))
a.shape == res_1.shape # Returns true
Be careful of using resize_
or other in-place operation with autograd
. See the following discussion: https://pytorch.org/docs/stable/notes/autograd.html#in-place-operations-with-autograd
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
Here is an example of what I would do. I hope it's what you're looking for.
char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)
a should now contain:
data data2
1 foo_ 1
2 bar_ 2
3 ap 3
4 b 4