$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
The size
attribute works, as well
<input size="25" type="text">
Set
wins due to near instant 'contains' checks: https://en.wikipedia.org/wiki/Hash_table
List implementation: usually an array, low level close to the metal good for iteration and random access by element index.
Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list
could be faster if you have very few elements (< 5), the larger element count the better the set
will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !
NOTE: If the list
is already sorted, searching the list
could be quite fast on small lists, but with more data a set
is faster for contains checks.
fruits.shift(); // Removes the first element from an array and returns only that element.
fruits.pop(); // Removes the last element from an array and returns only that element.
var filterTransNos = (from so in db.SalesOrderDetails
where ItemDescription.Contains(ItemDescription)
select new { so.TransNo }).AsEnumerable();
listreceipt = listreceipt.Where(p => filterTransNos.Any(p2 => p2.TransNo == p.TransNo)).ToList();
This is a variation on pagurix's answer, but using Eclipse Mars.
Change your web.xml file to web.bak
Ignore the errors, we'll regenerate it next.
Go into project properties -> project facets and set the Dynamic Web Module version to what you need. Eclipse now allows you to save.
Now right-click on the project. Choose Java EE Tools -> Generate Deployment Descriptor Stub.
This creates a new web.xml with the required version.
Open the new web.xml and copy across the XML header and the complete web-app opening tag to your original web.bak, delete the new web.xml and rename web.bak back to web.xml.
Done.
$tomorrow = date("Y-m-d", strtotime('tomorrow'));
or
$tomorrow = date("Y-m-d", strtotime("+1 day"));
Help Link: STRTOTIME()
You could have a reference to the radio group and use getCheckedRadioButtonId ()
to get the checked radio button id. Take a look here
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);
Then when you need to get the selected radio option.
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
// No item selected
}
else{
if (checkedRadioButtonId == R.id.radio_button1) {
// Do something with the button
}
}
Simplified solution for adding linked servers
First server
EXEC sp_addlinkedserver @server='ip,port\instancename'
Second Login
EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'
Execute queries from linked to local db
INSERT INTO Tbl (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]
When issue happening on Mac VS 2017 (Which I faced).
Run your application code now.
What does it mean?
It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.
What happens if I try to iterate the map with two threads at the same time?
It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.
But if the two threads used different iterators, you should be fine.
What happens if I put or remove a value from the map while iterating it?
That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.
Depending on your needs, a simple divide-and-conquer strategy can be used. It won't converge as fast as some other methods but it may be a lot easier for a novice to understand. In addition, since it's an O(log n) algorithm (halving the search space each iteration), the worst case for a 32-bit float will be 32 iterations.
Let's say you want the square root of 62.104. You pick a value halfway between 0 and that, and square it. If the square is higher than your number, you need to concentrate on numbers less than the midpoint. If it's too low, concentrate on those higher.
With real math, you could keep dividing the search space in two forever (if it doesn't have a rational square root). In reality, computers will eventually run out of precision and you'll have your approximation. The following C program illustrates the point:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
float val, low, high, mid, oldmid, midsqr;
int step = 0;
// Get argument, force to non-negative.
if (argc < 2) {
printf ("Usage: sqrt <number>\n");
return 1;
}
val = fabs (atof (argv[1]));
// Set initial bounds and print heading.
low = 0;
high = mid = val;
oldmid = -1;
printf ("%4s %10s %10s %10s %10s %10s %s\n",
"Step", "Number", "Low", "High", "Mid", "Square", "Result");
// Keep going until accurate enough.
while (fabs(oldmid - mid) >= 0.00001) {
oldmid = mid;
// Get midpoint and see if we need lower or higher.
mid = (high + low) / 2;
midsqr = mid * mid;
printf ("%4d %10.4f %10.4f %10.4f %10.4f %10.4f ",
++step, val, low, high, mid, midsqr);
if (mid * mid > val) {
high = mid;
printf ("- too high\n");
} else {
low = mid;
printf ("- too low\n");
}
}
// Desired accuracy reached, print it.
printf ("sqrt(%.4f) = %.4f\n", val, mid);
return 0;
}
Here's a couple of runs so you hopefully get an idea how it works. For 77:
pax> sqrt 77
Step Number Low High Mid Square Result
1 77.0000 0.0000 77.0000 38.5000 1482.2500 - too high
2 77.0000 0.0000 38.5000 19.2500 370.5625 - too high
3 77.0000 0.0000 19.2500 9.6250 92.6406 - too high
4 77.0000 0.0000 9.6250 4.8125 23.1602 - too low
5 77.0000 4.8125 9.6250 7.2188 52.1104 - too low
6 77.0000 7.2188 9.6250 8.4219 70.9280 - too low
7 77.0000 8.4219 9.6250 9.0234 81.4224 - too high
8 77.0000 8.4219 9.0234 8.7227 76.0847 - too low
9 77.0000 8.7227 9.0234 8.8730 78.7310 - too high
10 77.0000 8.7227 8.8730 8.7979 77.4022 - too high
11 77.0000 8.7227 8.7979 8.7603 76.7421 - too low
12 77.0000 8.7603 8.7979 8.7791 77.0718 - too high
13 77.0000 8.7603 8.7791 8.7697 76.9068 - too low
14 77.0000 8.7697 8.7791 8.7744 76.9893 - too low
15 77.0000 8.7744 8.7791 8.7767 77.0305 - too high
16 77.0000 8.7744 8.7767 8.7755 77.0099 - too high
17 77.0000 8.7744 8.7755 8.7749 76.9996 - too low
18 77.0000 8.7749 8.7755 8.7752 77.0047 - too high
19 77.0000 8.7749 8.7752 8.7751 77.0022 - too high
20 77.0000 8.7749 8.7751 8.7750 77.0009 - too high
21 77.0000 8.7749 8.7750 8.7750 77.0002 - too high
22 77.0000 8.7749 8.7750 8.7750 76.9999 - too low
23 77.0000 8.7750 8.7750 8.7750 77.0000 - too low
sqrt(77.0000) = 8.7750
For 62.104:
pax> sqrt 62.104
Step Number Low High Mid Square Result
1 62.1040 0.0000 62.1040 31.0520 964.2267 - too high
2 62.1040 0.0000 31.0520 15.5260 241.0567 - too high
3 62.1040 0.0000 15.5260 7.7630 60.2642 - too low
4 62.1040 7.7630 15.5260 11.6445 135.5944 - too high
5 62.1040 7.7630 11.6445 9.7037 94.1628 - too high
6 62.1040 7.7630 9.7037 8.7334 76.2718 - too high
7 62.1040 7.7630 8.7334 8.2482 68.0326 - too high
8 62.1040 7.7630 8.2482 8.0056 64.0895 - too high
9 62.1040 7.7630 8.0056 7.8843 62.1621 - too high
10 62.1040 7.7630 7.8843 7.8236 61.2095 - too low
11 62.1040 7.8236 7.8843 7.8540 61.6849 - too low
12 62.1040 7.8540 7.8843 7.8691 61.9233 - too low
13 62.1040 7.8691 7.8843 7.8767 62.0426 - too low
14 62.1040 7.8767 7.8843 7.8805 62.1024 - too low
15 62.1040 7.8805 7.8843 7.8824 62.1323 - too high
16 62.1040 7.8805 7.8824 7.8815 62.1173 - too high
17 62.1040 7.8805 7.8815 7.8810 62.1098 - too high
18 62.1040 7.8805 7.8810 7.8807 62.1061 - too high
19 62.1040 7.8805 7.8807 7.8806 62.1042 - too high
20 62.1040 7.8805 7.8806 7.8806 62.1033 - too low
21 62.1040 7.8806 7.8806 7.8806 62.1038 - too low
22 62.1040 7.8806 7.8806 7.8806 62.1040 - too high
23 62.1040 7.8806 7.8806 7.8806 62.1039 - too high
sqrt(62.1040) = 7.8806
For 49:
pax> sqrt 49
Step Number Low High Mid Square Result
1 49.0000 0.0000 49.0000 24.5000 600.2500 - too high
2 49.0000 0.0000 24.5000 12.2500 150.0625 - too high
3 49.0000 0.0000 12.2500 6.1250 37.5156 - too low
4 49.0000 6.1250 12.2500 9.1875 84.4102 - too high
5 49.0000 6.1250 9.1875 7.6562 58.6182 - too high
6 49.0000 6.1250 7.6562 6.8906 47.4807 - too low
7 49.0000 6.8906 7.6562 7.2734 52.9029 - too high
8 49.0000 6.8906 7.2734 7.0820 50.1552 - too high
9 49.0000 6.8906 7.0820 6.9863 48.8088 - too low
10 49.0000 6.9863 7.0820 7.0342 49.4797 - too high
11 49.0000 6.9863 7.0342 7.0103 49.1437 - too high
12 49.0000 6.9863 7.0103 6.9983 48.9761 - too low
13 49.0000 6.9983 7.0103 7.0043 49.0598 - too high
14 49.0000 6.9983 7.0043 7.0013 49.0179 - too high
15 49.0000 6.9983 7.0013 6.9998 48.9970 - too low
16 49.0000 6.9998 7.0013 7.0005 49.0075 - too high
17 49.0000 6.9998 7.0005 7.0002 49.0022 - too high
18 49.0000 6.9998 7.0002 7.0000 48.9996 - too low
19 49.0000 7.0000 7.0002 7.0001 49.0009 - too high
20 49.0000 7.0000 7.0001 7.0000 49.0003 - too high
21 49.0000 7.0000 7.0000 7.0000 49.0000 - too low
22 49.0000 7.0000 7.0000 7.0000 49.0001 - too high
23 49.0000 7.0000 7.0000 7.0000 49.0000 - too high
sqrt(49.0000) = 7.0000
Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).
Long answer: here's a complete decision diagram (click to magnify).
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
To resolve this problem just make a scan.nextLine(), where scan is an instance of the Scanner object. For example, I am using a simple HackerRank Problem for the explanation.
package com.company;
import java.util.Scanner;
public class hackerrank {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
scan.nextLine(); // This line shall stop the skipping the nextLine()
String s = scan.nextLine();
scan.close();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
Swift 3:
protocol
@objc protocol SomeDelegate {
@objc optional func method()
}
Object
class SomeObject : NSObject {
weak var delegate:SomeObject?
func delegateMethod() {
if let delegateMethod = delegate?.method{
delegateMethod()
}else {
//Failed
}
}
}
(The answer was heavily modified after clarifications to the original question)
After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the ImageView
so that image's one dimension would always be 250dp and the ImageView
would have the same dimensions as the image.
This code scales Drawable
of an ImageView
to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then the ImageView
is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.
Enjoy. :)
private void scaleImage(ImageView view) throws NoSuchElementException {
// Get bitmap from the the ImageView.
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
// Check bitmap is Ion drawable
bitmap = Ion.with(view).getBitmap();
}
// Get current dimensions AND the desired bounding box
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(250);
Log.i("Test", "original width = " + Integer.toString(width));
Log.i("Test", "original height = " + Integer.toString(height));
Log.i("Test", "bounding = " + Integer.toString(bounding));
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Log.i("Test", "scaled width = " + Integer.toString(width));
Log.i("Test", "scaled height = " + Integer.toString(height));
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Log.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
The xml code for the ImageView
:
<ImageView a:id="@+id/image_box"
a:background="#ff0000"
a:src="@drawable/star"
a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:layout_marginTop="20dp"
a:layout_gravity="center_horizontal"/>
Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
UPDATE 7th, November 2012:
Added null pointer check as suggested in comments
The solution with FileWriter
is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!
So at best use FileOutputStream
:
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
This directive pass the selected files as well:
/**
*File Input - custom call when the file has changed
*/
.directive('onFileChange', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeHandler = scope.$eval(attrs.onFileChange);
element.bind('change', function() {
scope.$apply(function() {
var files = element[0].files;
if (files) {
onChangeHandler(files);
}
});
});
}
};
});
The HTML, how to use it:
<input type="file" ng-model="file" on-file-change="onFilesSelected">
In my controller:
$scope.onFilesSelected = function(files) {
console.log("files - " + files);
};
With Chrome browser, you can use console.trace
method: https://developer.chrome.com/devtools/docs/console-api#consoletraceobject
On Windows, the location can be found here. I didn't find any documentation on the internet for this, and this wasn't immediately obvious to me:
C:\Users\\{username}\\.vagrant.d\boxes
Dealing with colour sequences can get messy and different systems might use different Colour Sequence Indicators.
I would suggest you try using ncurses. Other than colour, ncurses can do many other neat things with console UI.
If you want to make a branch from some another branch then follow bellow steps:
Assumptions:
BranchExisting
is the name of branch from which you need to make a new branch with name BranchMyNew
.Steps:
Fetch the branch to your local machine.
$ git fetch origin BranchExisting : BranchExisting
This command will create a new branch in your local with same branch name.
Now, from master branch checkout to the newly fetched branch
$ git checkout BranchExisting
You are now in BranchExisting. Now create a new branch from this existing branch.
$ git checkout -b BranchMyNew
Here you go!
The default namespace in Python is "__main__"
. When you use import scipy
, Python creates a separate namespace as your module name.
The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.
I have worked with SSRS for over 10 years and the answers above are the go to answers. BUT. If nothing works, and you are completely stuffed....remove items from the report until the problem goes away. Once you have identified which row or report item is causing the problem, put it inside a rectangle container. That's it. Has helped us many many times! Extra pages are mostly caused by report items flowing over the right margin. When all else fails, putting things inside a rectangle or an empty rectangle to the right of an item, can stop this from happening. Good luck out there!
Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{ $1=""; print $0}')
;;
esac
It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like
root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript
Just an FYI
Expired certificate was the cause of our "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated".
keytool -list -v -keystore filetruststore.ts
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: somealias
Creation date: Jul 26, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Unknown, OU=SomeOU, O="Some Company, Inc.", L=SomeCity, ST=GA, C=US
Issuer: CN=Unknown, OU=SomeOU, O=Some Company, Inc.", L=SomeCity, ST=GA, C=US
Serial number: 5011a47b
Valid from: Thu Jul 26 16:11:39 EDT 2012 until: Wed Oct 24 16:11:39 EDT 2012
Sounds like a job for XMLUnit
Example:
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}
Since Swift 3.0 is published, it is even a little bit more subtle to declare a targetAction appropriate
class MyCustomView : UIView {
func addTapGestureRecognizer() {
// the "_" is important
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyCustomView.handleTapGesture(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
}
// since Swift 3.0 this "_" in the method implementation is very important to
// let the selector understand the targetAction
func handleTapGesture(_ tapGesture : UITapGestureRecognizer) {
if tapGesture.state == .ended {
print("TapGesture detected")
}
}
}
use the
setInterval(function, 60000);
EDIT : (In case if you want to stop the clock after it is started)
Script section
<script>
var int=self.setInterval(function, 60000);
</script>
and HTML Code
<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>
Calling erase will invalidate iterators, you could use:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
while (iter != myNumbers_in.end())
{
if (*iter == number_in)
{
iter = myNumbers_in.erase(iter);
}
else
{
++iter;
}
}
}
Or you could use std::remove_if together with a functor and std::vector::erase:
struct Eraser
{
Eraser(int number_in) : number_in(number_in) {}
int number_in;
bool operator()(int i) const
{
return i == number_in;
}
};
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());
Instead of writing your own functor in this case you could use std::remove:
std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());
In C++11 you could use a lambda instead of a functor:
std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());
In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):
std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda
or:
std::vector<int> myNumbers;
std::erase(myNumbers, number_in);
TL;DR don't try to do this
$ make run arg
instead create script:
#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"
and do this:
$ ./buildandrunprog.sh arg
answer to the stated question:
you can use a variable in the recipe
run: prog
./prog $(var)
then pass a variable assignment as an argument to make
$ make run var=arg
this will execute ./prog arg
.
but beware of pitfalls. i will elaborate about the pitfalls of this method and other methods further down.
answer to the assumed intention behind the question:
the assumption: you want to run prog
with some arguments but have it rebuild before running if necessary.
the answer: create a script which rebuilds if necessary then runs prog with args
#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"
this script makes the intention very clear. it uses make to do what it is good for: building. it uses a shell script to do what it is good for: batch processing.
plus you can do whatever else you might need with the full flexibility and expressiveness of a shell script without all the caveats of a makefile.
also the calling syntax is now practically identical:
$ ./buildandrunprog.sh foo "bar baz"
compare to:
$ ./prog foo "bar baz"
contrast to
$ make run var="foo bar\ baz"
background:
make is not designed to pass arguments to a target. all arguments on the command line are interpreted either as a goal (a.k.a. target), as an option, or as a variable assignment.
so if you run this:
$ make run foo --wat var=arg
make will interpret run
and foo
as goals (targets) to update according to their recipes. --wat
as an option for make. and var=arg
as a variable assignment.
for more details see: https://www.gnu.org/software/make/manual/html_node/Goals.html#Goals
for the terminology see: https://www.gnu.org/software/make/manual/html_node/Rule-Introduction.html#Rule-Introduction
about the variable assignment method and why i recommend against it
$ make run var=arg
and the variable in the recipe
run: prog
./prog $(var)
this is the most "correct" and straightforward way to pass arguments to a recipe. but while it can be used to run a program with arguments it is certainly not designed to be used that way. see https://www.gnu.org/software/make/manual/html_node/Overriding.html#Overriding
in my opinion this has one big disadvantage: what you want to do is run prog
with argument arg
. but instead of writing:
$ ./prog arg
you are writing:
$ make run var=arg
this gets even more awkward when trying to pass multiple arguments or arguments containing spaces:
$ make run var="foo bar\ baz"
./prog foo bar\ baz
argcount: 2
arg: foo
arg: bar baz
compare to:
$ ./prog foo "bar baz"
argcount: 2
arg: foo
arg: bar baz
for the record this is what my prog
looks like:
#! /bin/sh
echo "argcount: $#"
for arg in "$@"; do
echo "arg: $arg"
done
also note that you should not put $(var)
in quotes in the makefile:
run: prog
./prog "$(var)"
because then prog
will always get just one argument:
$ make run var="foo bar\ baz"
./prog "foo bar\ baz"
argcount: 1
arg: foo bar\ baz
all this is why i recommend against this route.
for completeness here are some other methods to "pass arguments to make run".
method 1:
run: prog
./prog $(filter-out $@, $(MAKECMDGOALS))
%:
@true
super short explanation: filter out current goal from list of goals. create catch all target (%
) which does nothing to silently ignore the other goals.
method 2:
ifeq (run, $(firstword $(MAKECMDGOALS)))
runargs := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS))
$(eval $(runargs):;@true)
endif
run:
./prog $(runargs)
super short explanation: if the target is run
then remove the first goal and create do nothing targets for the remaining goals using eval
.
both will allow you to write something like this
$ make run arg1 arg2
for deeper explanation study the manual of make: https://www.gnu.org/software/make/manual/html_node/index.html
problems of method 1:
arguments that start with a dash will be interpreted by make and not passed as a goal.
$ make run --foo --bar
workaround
$ make run -- --foo --bar
arguments with an equal sign will be interpreted by make and not passed
$ make run foo=bar
no workaround
arguments with spaces is awkward
$ make run foo "bar\ baz"
no workaround
if an argument happens to be run
(equal to the target) it will also be removed
$ make run foo bar run
will run ./prog foo bar
instead of ./prog foo bar run
workaround possible with method 2
if an argument is a legitimate target it will also be run.
$ make run foo bar clean
will run ./prog foo bar clean
but also the recipe for the target clean
(assuming it exists).
workaround possible with method 2
when you mistype a legitimate target it will be silently ignored because of the catch all target.
$ make celan
will just silently ignore celan
.
workaround is to make everything verbose. so you see what happens. but that creates a lot of noise for the legitimate output.
problems of method 2:
if an argument has same name as an existing target then make will print a warning that it is being overwritten.
no workaround that i know of
arguments with an equal sign will still be interpreted by make and not passed
no workaround
arguments with spaces is still awkward
no workaround
arguments with space breaks eval
trying to create do nothing targets.
workaround: create the global catch all target doing nothing as above. with the problem as above that it will again silently ignore mistyped legitimate targets.
it uses eval
to modify the makefile at runtime. how much worse can you go in terms of readability and debugability and the Principle of least astonishment.
workaround: don't do this!!1 instead write a shell script that runs make and then runs prog
.
i have only tested using gnu make. other makes may have different behaviour.
TL;DR don't try to do this
$ make run arg
instead create script:
#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"
and do this:
$ ./buildandrunprog.sh arg
npm set registry http://85.10.209.91/
(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).
The other solutions seem to have outdated versions.
When I have added/modified/deleted many files (since the last commit), I like to look at those modifications in chronological order.
For that I use:
To list all non-staged files:
git ls-files --other --modified --exclude-standard
To get the last modified date for each file:
while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done
Although ruvim suggests in the comments:
xargs -0 stat -c '%y %n' --
To sort them from oldest to more recent:
sort
An alias makes it easier to use:
alias gstlast='git ls-files --other --modified --exclude-standard|while read filename; do echo -n "$(stat -c%y -- $filename 2> /dev/null) "; echo $filename; done|sort'
Or (shorter and more efficient, thanks to ruvim)
alias gstlast='git ls-files --other --modified --exclude-standard|xargs -0 stat -c '%y %n' --|sort'
For example:
username@hostname:~> gstlast
2015-01-20 11:40:05.000000000 +0000 .cpl/params/libelf
2015-01-21 09:02:58.435823000 +0000 .cpl/params/glib
2015-01-21 09:07:32.744336000 +0000 .cpl/params/libsecret
2015-01-21 09:10:01.294778000 +0000 .cpl/_deps
2015-01-21 09:17:42.846372000 +0000 .cpl/params/npth
2015-01-21 12:12:19.002718000 +0000 sbin/git-rcd
I now can review my modifications, from oldest to more recent.
@John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.
My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.
So given the following (pay attention to the string parameter inside ofPattern();
String str = "20190927T182730.000Z"
LocalDateTime fin;
fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );
Error:
Exception in thread "main" java.time.format.DateTimeParseException: Text
'20190927T182730.000Z' could not be parsed at index 19
The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change
"yyyyMMdd'T'HHmmss.SSSZ"
to "yyyyMMdd'T'HHmmss.SSS'Z'"
and it works.
Removing the Z from the pattern alltogether also led to errors.
Frankly, I'd expect a Java class to have anticipated this.
For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:
Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.
The result of a subtraction generating a negative number in an unsigned type is well-defined:
- [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type. (ISO/IEC 9899:1999 (E) §6.2.5/9)
As you can see, (unsigned)0 - (unsigned)1
equals -1 modulo UINT_MAX+1, or in other words, UINT_MAX.
Note that although it does say "A computation involving unsigned operands can never overflow", which might lead you to believe that it applies only for exceeding the upper limit, this is presented as a motivation for the actual binding part of the sentence: "a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." This phrase is not restricted to overflow of the upper bound of the type, and applies equally to values too low to be represented.
Isn't string.replace returning a value, rather than modifying the source string?
So if you wanted to modify variableABC, you'd need to do this:
var variableABC = "A B C";
variableABC = variableABC.replace('B', 'D') //output: 'A D C'
If you are trying to do a form validation received from the client, or just a bean validation - keep it simple. It's better to do a loose email validation rather than to do a strict one and reject some people, (e.g. when they are trying to register for your web service). With almost anything allowed in the username part of the email and so many new domains being added literally every month (e.g. .company, .entreprise, .estate), it's safer not to be restrictive:
Pattern pattern = Pattern.compile("^.+@.+\\..+$");
Matcher matcher = pattern.matcher(email);
function currentUrl() {
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
return $protocol . '://' . $host . $script . '?' . $params;
}
Then add your value with something like;
echo currentUrl().'&value=myVal';
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
Other that the differences in the default access (public/private), there is no difference.
However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."
Note that C unions work with C++, but not the other way around. For example
union WorksWithCppOnly{
WorksWithCppOnly():a(0){}
friend class FloatAccessor;
int a;
private:
float b;
};
And likewise
typedef union friend{
int a;
float b;
} class;
only works in C
this one System.IO.Path.GetDirectory(Application.ExecutablePath)
changed to System.IO.Path.GetDirectoryName(Application.ExecutablePath)
$HOME/.gitconfig
is your global config for git.
There are three levels of config files.
cat $(git rev-parse --show-toplevel)/.git/config
(mentioned by bereal) is your local config, local to the repo you have cloned.
you can also type from within your repo:
git remote -v
And see if there is any remote named 'origin' listed in it.
If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:
git remote add origin url/to/your/fork
The OP mentions:
Doing
git remote -v
gives:
upstream git://git.moodle.org/moodle.git (fetch)
upstream git://git.moodle.org/moodle.git (push)
So 'origin
' is missing: the reference to your fork.
See "What is the difference between origin
and upstream
in github"
I was also having this same problem. I developed a synchronous solution thanks to the research done by @tpeczek in the following SO article: Unable to authenticate to ASP.NET Web Api service with HttpClient
My solution uses a WebClient
, which as you correctly noted passes the credentials without issue. The reason HttpClient
doesn't work is because of Windows security disabling the ability to create new threads under an impersonated account (see SO article above.) HttpClient
creates new threads via the Task Factory thus causing the error. WebClient
on the other hand, runs synchronously on the same thread thereby bypassing the rule and forwarding its credentials.
Although the code works, the downside is that it will not work async.
var wi = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;
var wic = wi.Impersonate();
try
{
var data = JsonConvert.SerializeObject(new
{
Property1 = 1,
Property2 = "blah"
});
using (var client = new WebClient { UseDefaultCredentials = true })
{
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
client.UploadData("http://url/api/controller", "POST", Encoding.UTF8.GetBytes(data));
}
}
catch (Exception exc)
{
// handle exception
}
finally
{
wic.Undo();
}
Note: Requires NuGet package: Newtonsoft.Json, which is the same JSON serializer WebAPI uses.
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super
in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
What worked for me was echo $testVar | tr "\n" " "
Where testVar contained my variable/script-output
What ended up working for me after a few hours of pain..
if you're running brew..
brew install ruby
in the terminal output/log, identify the path where ruby was installed, brew suggests 'You may want to add this to your PATH', so that's what we'll do. For example, mine is
/usr/local/lib/ruby/gems/3.0.0/bin
Add this to your path by running (omitting braces)
echo 'export PATH"{the_path_you_found_above}:$PATH"' >> ~/.bash_profile
then update your environment by running
source ~/.bash_profile
now, try running your install, i.e.,
sudo gem install middleman
Are you looking for the max date for each model?
SELECT model, max(date) FROM doc
GROUP BY model
If you're looking for all models matching the max date of the entire table...
SELECT model, date FROM doc
WHERE date IN (SELECT max(date) FROM doc)
[--- Added ---]
For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):
SELECT d.model, d.date, d.color, d.etc FROM doc d
WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)
MySQL 8.0 and newer supports the OVER
clause, producing the same results a bit faster for larger data sets.
SELECT model, date, color, etc FROM (SELECT model, date, color, etc,
max(date) OVER (PARTITION BY model) max_date FROM doc) predoc
WHERE date=max_date;
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Reference the checkbox by it's id and not with the # Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Just noting a different way of questionable usefulness, using os.environ
:
import os
python_executable_path = os.environ['_']
e.g.
$ python -c "import os; print(os.environ['_'])"
/usr/bin/python
I had the same issue connecting to a remote machine. but I managed to login as below:
ssh -p 22 myName@hostname
or:
ssh -l myName -p 22 hostname
Try this.
First in your searchable xml the fields (name and hint etc) put @string
and not literal strings.
Then method onCreateOptionsMenu
, it must have a ComponentName
object with your package name and your completed class name (with package name) - In case activity which has the SearchView
component is the same as the show search results use getComponentName()
, as the google android developer says.
I tried a lot of solutions and after much,much work this solution works for me.
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.
public interface MyGlobalConstants {
public static final int TIMEOUT_IN_SECS = 25;
}
But don't then implement it. Just refer to them directly in code via the fully qualified classname.
You can try a 3rd party library like json.net There's documention on the project site. It does say it requires .net 3.5.
Otherwise there's another one called Nii.json which i believe is a port from java. I found a link to it on this blog
If you think the space before and after "=" is mandatory, try it as separate item in the list.
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Here's a gitHub project that does just that.
It records audio from the browser in mp3 format, and it automatically saves it to the webserver. https://github.com/Audior/Recordmp3js
You can also view a detailed explanation of the implementation: http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/
Here you can find every thing you need:
http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
This config works in my setup:
[http]
proxy = <your proxy>
[https] proxy = <your proxy>
[http]
sslVerify = false
[https]
sslVerify = false
[credential]
helper = wincred
This is quite the tricky thing to do in Android and I haven't done it yet. But maybe these links may help you:
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm
to the command:
gcc test.c -o test -lm
The math library is named libm.so
, and the -l
command option assumes a lib
prefix and .a
or .so
suffix.
you need length() function
select length(customer_name) from ar.ra_customers
The second half of the currently accepted answer is outdated and has two deprecations. First and most important, you can no longer pass a dictionary of dictionaries to the agg
groupby method. Second, never use .ix
.
If you desire to work with two separate columns at the same time I would suggest using the apply
method which implicitly passes a DataFrame to the applied function. Let's use a similar dataframe as the one from above
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df
a b c d group
0 0.418500 0.030955 0.874869 0.145641 0
1 0.446069 0.901153 0.095052 0.487040 0
2 0.843026 0.936169 0.926090 0.041722 1
3 0.635846 0.439175 0.828787 0.714123 1
A dictionary mapped from column names to aggregation functions is still a perfectly good way to perform an aggregation.
df.groupby('group').agg({'a':['sum', 'max'],
'b':'mean',
'c':'sum',
'd': lambda x: x.max() - x.min()})
a b c d
sum max mean sum <lambda>
group
0 0.864569 0.446069 0.466054 0.969921 0.341399
1 1.478872 0.843026 0.687672 1.754877 0.672401
If you don't like that ugly lambda column name, you can use a normal function and supply a custom name to the special __name__
attribute like this:
def max_min(x):
return x.max() - x.min()
max_min.__name__ = 'Max minus Min'
df.groupby('group').agg({'a':['sum', 'max'],
'b':'mean',
'c':'sum',
'd': max_min})
a b c d
sum max mean sum Max minus Min
group
0 0.864569 0.446069 0.466054 0.969921 0.341399
1 1.478872 0.843026 0.687672 1.754877 0.672401
apply
and returning a SeriesNow, if you had multiple columns that needed to interact together then you cannot use agg
, which implicitly passes a Series to the aggregating function. When using apply
the entire group as a DataFrame gets passed into the function.
I recommend making a single custom function that returns a Series of all the aggregations. Use the Series index as labels for the new columns:
def f(x):
d = {}
d['a_sum'] = x['a'].sum()
d['a_max'] = x['a'].max()
d['b_mean'] = x['b'].mean()
d['c_d_prodsum'] = (x['c'] * x['d']).sum()
return pd.Series(d, index=['a_sum', 'a_max', 'b_mean', 'c_d_prodsum'])
df.groupby('group').apply(f)
a_sum a_max b_mean c_d_prodsum
group
0 0.864569 0.446069 0.466054 0.173711
1 1.478872 0.843026 0.687672 0.630494
If you are in love with MultiIndexes, you can still return a Series with one like this:
def f_mi(x):
d = []
d.append(x['a'].sum())
d.append(x['a'].max())
d.append(x['b'].mean())
d.append((x['c'] * x['d']).sum())
return pd.Series(d, index=[['a', 'a', 'b', 'c_d'],
['sum', 'max', 'mean', 'prodsum']])
df.groupby('group').apply(f_mi)
a b c_d
sum max mean prodsum
group
0 0.864569 0.446069 0.466054 0.173711
1 1.478872 0.843026 0.687672 0.630494
EDIT: Original question did not specify language. My answer is in C#.
You should instead use HashSet for this purpose. If you must use ArrayList, you could use the following extension methods:
var a = arrayListA.Cast<DateTime>();
var b = arrayListB.Cast<DateTime>();
var c = b.Except(a);
var arrayListC = new ArrayList(c.ToArray());
using HashSet...
var a = new HashSet<DateTime>(); // ...and fill it
var b = new HashSet<DateTime>(); // ...and fill it
b.ExceptWith(a); // removes from b items that are in a
In TortoiseSVN you can configure the proxy server under Settings=> Network
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:
To stop:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()
To start:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()
After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.
Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.
For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.
Here are my results:
2 mb --> 5744 threads
4 mb --> 5743 threads
8 mb --> 5735 threads
12 mb --> 5724 threads
16 mb --> 5712 threads
24 mb --> 5687 threads
32 mb --> 5662 threads
48 mb --> 5610 threads
64 mb --> 5561 threads
96 mb --> 5457 threads
128 mb --> 5357 threads
192 mb --> 5190 threads
256 mb --> 5014 threads
384 mb --> 4606 threads
512 mb --> 4202 threads
768 mb --> 3388 threads
1024 mb --> 2583 threads
So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.
Which is weird.
As oxbow_lakes mentions, you can use reflection to get around the access restrictions (assuming your SecurityManager will let you).
That said, if this class is so badly designed that it makes you resort to such hackery, maybe you should look for an alternative. Sure this little hack might be saving you a few hours now, but how much will it cost you down the road?
Here's another approach that takes advantage of Matlab's strjoin
function. With strjoin
it's easy to customize the delimiter between values.
x = [1, 2, 3];
fprintf('Answer: (%s)\n', strjoin(cellstr(num2str(x(:))),', '));
This results in: Answer: (1, 2, 3)
If anyone wants to add an URL on a single marker which not require for loops, here is how it goes:
if ($('#googleMap').length) {
var initialize = function() {
var mapOptions = {
zoom: 15,
scrollwheel: false,
center: new google.maps.LatLng(45.725788, -73.5120818),
styles: [{
stylers: [{
saturation: -100
}]
}]
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
animation: google.maps.Animation.BOUNCE,
icon: 'example-marker.png',
map: map,
url: 'https://example.com'
});
//Add an url to the marker
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
// Add the map initialize function to the window load function
google.maps.event.addDomListener(window, "load", initialize);
}
Updated Answer
* Updated answer which support the v2.1.1** bootstrap version stylesheet.
**But be careful because this solution has been removed from v3
Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:
http://jsfiddle.net/2Smgv/2858/
Original Answer
There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.
Relevant code
CSS
.dropdown-menu .sub-menu {
left: 100%;
position: absolute;
top: 0;
visibility: hidden;
margin-top: -1px;
}
.dropdown-menu li:hover .sub-menu {
visibility: visible;
display: block;
}
.navbar .sub-menu:before {
border-bottom: 7px solid transparent;
border-left: none;
border-right: 7px solid rgba(0, 0, 0, 0.2);
border-top: 7px solid transparent;
left: -7px;
top: 10px;
}
.navbar .sub-menu:after {
border-top: 6px solid transparent;
border-left: none;
border-right: 6px solid #fff;
border-bottom: 6px solid transparent;
left: 10px;
top: 11px;
left: -6px;
}
Created my own .sub-menu
class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.
package main
import "fmt"
import "strconv"
func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
}
func main() {
fmt.Println(FloatToString(21312421.213123))
}
If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg
strconv.FormatFloat(input_num, 'f', -1, 64)
Personally I find fmt
easier to use. (Playground link)
fmt.Printf("x = %.6f\n", 21312421.213123)
Or if you just want to convert the string
fmt.Sprintf("%.6f", 21312421.213123)
java.sql.Timestamp
.valueOf( // Class-method parses SQL-style formatted date-time strings.
"2007-11-11 12:13:14"
) // Returns a `Timestamp` object.
.toInstant() // Converts from terrible legacy classes to modern *java.time* class.
java.sql.Timestamp.valueOf
parses SQL formatIf you can use the full four digits for the year, your input string of 2007-11-11 12:13:14
would be in standard SQL format assuming this value is meant to be in UTC time zone.
The java.sql.Timestamp
class has a valueOf
method to directly parse such strings.
String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;
In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString
method. In contrast, the java.time classes by default use the standard ISO 8601 formats.
System.out.println( "Output: " + ts.toInstant().toString() );
You can use unset
:
unset($array['key-here']);
Example:
$array = array("key1" => "value1", "key2" => "value2");
print_r($array);
unset($array['key1']);
print_r($array);
unset($array['key2']);
print_r($array);
Output:
Array
(
[key1] => value1
[key2] => value2
)
Array
(
[key2] => value2
)
Array
(
)
On a related note, if you had:
class User; // let the compiler know such a class will be defined
class MyMessageBox
{
public:
User* myUser;
};
class User
{
public:
// also ok, since it's now defined
MyMessageBox dataMsgBox;
};
Then that would also work, because the User is defined in MyMessageBox as a pointer
ToString() Vs Convert.ToString()
Similarities :-
Both are used to convert a specific type to string i.e int to string, float to string or an object to string.
Difference :-
ToString()
can't handle null while in case with Convert.ToString()
will handle null value.
Example :
namespace Marcus
{
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
class Startup
{
public static void Main()
{
Employee e = new Employee();
e = null;
string s = e.ToString(); // This will throw an null exception
s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
}
}
}
<div id="scroll">
<p>Try to add more text</p>
</div>
here's the css code
#scroll {
overflow-y:auto;
height:auto;
max-height:200px;
border:1px solid black;
width:300px;
}
here's the demo JSFIDDLE
Vector
is a broken class that is not threadsafe, despite it being "synchronized" and is only used by students and other inexperienced programmers.
ArrayList
is the go-to List implementation used by professionals and experienced programmers.
Professionals wanting a threadsafe List implementation use a CopyOnWriteArrayList
.
You can just pass it
def my_function(my_data):
my_data["schoolname"] = "something"
print my_data
or if you really want to
def my_function(**kwargs):
kwargs["schoolname"] = "something"
print kwargs
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
Union has not good performance : this article describe about compare them with together
var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
dict[person.Number] = person;
}
var merged = dict.Values.ToList();
Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms
For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName
-- to use the query (&(objectCategory=group)(CN=GroupCN))
. This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.
The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499
attribute to be returned, then for the member;range=1500-2999
attribute.
With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}
Try something like the following in your case.
class Pill extends React.Component {
render() {
return (
<button className={['pill', this.props.styleName]}>{this.props.children}</button>
);
}
}
The best solution is the word-spacing
property.
Add the <p>
in a container with a specific size (example 300px
) and after you have to add that size as the value in the word-spacing.
HTML
<div>
<p>Sentence Here</p>
</div>
CSS
div {
width: 300px;
}
p {
width: auto;
text-align: center;
word-spacing: 300px;
}
In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.
Here an example Codepen
I saw it's solved, but I still want to share a solution which worked for me.
.env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]
MySQL admin:
SELECT user, host FROM mysql.user
Console:
php artisan cache:clear
php artisan config:cache
Now it works for me.
As per new Interface follow these steps
I encountered this issue because I used setState
instead of state
in the constructor.
EXAMPLE
Change the following incorrect code
constructor(props) {
super(props);
this.setState({
key: ''
});
}
to
constructor(props) {
super(props);
this.state = {
key: ''
};
}
You must use a more recent version of tomcat which has support for JDK 8.
I can confirm that apache-tomcat-7.0.35 does NOT have support for JDK8, I can also confirm that apache-tomcat-7.0.50 DOES have support for JDK8.
For inspection/debugging check the Data::Printer
module. It is meant to do one thing and one thing only:
display Perl variables and objects on screen, properly formatted (to be inspected by a human)
Example usage:
use Data::Printer;
p @array; # no need to pass references
The code above might output something like this (with colors!):
[
[0] "a",
[1] "b",
[2] undef,
[3] "c",
]
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
Assuming Unix file type and you only want the last newline this works.
sed -e '${/^$/d}'
It will not work on multiple newlines...
* Works only if the last line is a blank line.
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
Not sure how you were calling concat()
but it should work as long as both objects are of the same type. Maybe the issue is that you need to cast your second vector to a dataframe? Using the df that you defined the following works for me:
df2 = pd.DataFrame([[2,3,4]], columns=['A','B','C'])
pd.concat([df2, df])
You can use a zip
function with a list comprehension :
with open('ex.txt') as f:
print zip(*[line.split() for line in f])[1]
result :
('10', '20', '30', '40', '23', '13')
If all you need is a user provided dictionary, possible better solution is json.loads
. The main limitation is that json dicts requires string keys. Also you can only provide literal data, but that is also the case for literal_eval
.
Add a toolbar to your xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment title"/>
</android.support.v7.widget.Toolbar>
Then inside your onCreateView method in the Fragment:
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
As often stated before, you should not use regular expressions to process XML or HTML documents. They do not perform very well with HTML and XML documents, because there is no way to express nested structures in a general way.
You could use the following.
String result = Regex.Replace(htmlDocument, @"<[^>]*>", String.Empty);
This will work for most cases, but there will be cases (for example CDATA containing angle brackets) where this will not work as expected.
I can only get CSV to parse properly in Excel 2007 as tab-separated little-endian UTF-16 starting with the proper byte order mark.
Use sprintf.
int sprintf ( char * str, const char * format, ... );
Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).
A terminating null character is automatically appended after the content.
After the format parameter, the function expects at least as many additional arguments as needed for format.
str
Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
You can specify that a Thread
is a daemon one by using setDaemon
method, they usually don't exit, neither they are interrupted.. they just stop when application stops.
You need to put SongsTableSeeder
into file SongsTableSeeder.php
in the same directory where you have your DatabaseSeeder.php
file.
And you need to run in your console:
composer dump-autoload
to generate new class map and then run:
php artisan db:seed
I've just tested it. It is working without a problem in Laravel 5
Here is an interesting approach using JavaScript ...
String.prototype.csv = String.prototype.split.partial(/,\s*/);
var results = ("Mugan, Jin, Fuu").csv();
console.log(results[0]=="Mugan" &&
results[1]=="Jin" &&
results[2]=="Fuu",
"The text values were split properly");
I've wrapped Darin's answer into a nicely reusable extension method.
public static class UriExtensions
{
/// <summary>
/// Adds the specified parameter to the Query String.
/// </summary>
/// <param name="url"></param>
/// <param name="paramName">Name of the parameter to add.</param>
/// <param name="paramValue">Value for the parameter to add.</param>
/// <returns>Url with added parameter.</returns>
public static Uri AddParameter(this Uri url, string paramName, string paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[paramName] = paramValue;
uriBuilder.Query = query.ToString();
return uriBuilder.Uri;
}
}
I hope this helps!
From the Mongo documentation:
The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output
Read more here: http://www.mongodb.org/display/DOCS/mongoexport
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};
There are problems with some data. Consider:
as.double(as.character("2.e")) # This results in 2
Another solution:
get_numbers <- function(X) {
X[toupper(X) != tolower(X)] <- NA
return(as.double(as.character(X)))
}
This is not right. Here's how you should use Runtime.exec()
. You might also try its more modern cousin, ProcessBuilder
:
The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):
body{
$colorStart: rgba(0,0,0,0);
$colorEnd: rgba(0,0,0,0.8);
@include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}
Only one condition, I tested that it wasn't null was, if you allow enough time to user to touch the "get my location" layer button, then it will not get null value.
I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.
The reason of this error is a wrong order of app.use. You must configure express in this order:
app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
1. Can not instantiate abstract class: Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract.
Example below :
abstract class AbstractClass
{
abstract protected function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new AbstractClass();
$obj->printOut();
//Fatal error: Cannot instantiate abstract class AbstractClass
2. Any class that contains at least one abstract method must also be abstract: Abstract class can have abstract and non-abstract methods, but it must contain at least one abstract method. If a class has at least one abstract method, then the class must be declared abstract.
Note: Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.
Example below :
class Non_Abstract_Class
{
abstract protected function getValue();
public function printOut() {
echo "Hello how are you?";
}
}
$obj=new Non_Abstract_Class();
$obj->printOut();
//Fatal error: Class Non_Abstract_Class contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Non_Abstract_Class::getValue)
3. An abstract method can not contain body: Methods defined as abstract simply declare the method's signature - they cannot define the implementation. But a non-abstract method can define the implementation.
abstract class AbstractClass
{
abstract protected function getValue(){
return "Hello how are you?";
}
public function printOut() {
echo $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
//Fatal error: Abstract function AbstractClass::getValue() cannot contain body
4. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child :If you inherit an abstract class you have to provide implementations to all the abstract methods in it.
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
// Common method
public function printOut() {
print $this->getValue() . "<br/>";
}
}
class ConcreteClass1 extends AbstractClass
{
public function printOut() {
echo "dhairya";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
//Fatal error: Class ConcreteClass1 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (AbstractClass::getValue)
5. Same (or a less restricted) visibility:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Note that abstract method should not be private.
abstract class AbstractClass
{
abstract public function getValue();
abstract protected function prefixValue($prefix);
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."<br/>";
//Fatal error: Access level to ConcreteClass1::getValue() must be public (as in class AbstractClass)
6. Signatures of the abstract methods must match:When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.
abstract class AbstractClass
{
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "<br/>";
echo $class->prefixName("Pacwoman"), "<br/>";
//output: Mr. Pacman
// Mrs. Pacwoman
7. Abstract class doesn't support multiple inheritance:Abstract class can extends another abstract class,Abstract class can provide the implementation of interface.But it doesn't support multiple inheritance.
interface MyInterface{
public function foo();
public function bar();
}
abstract class MyAbstract1{
abstract public function baz();
}
abstract class MyAbstract2 extends MyAbstract1 implements MyInterface{
public function foo(){ echo "foo"; }
public function bar(){ echo "bar"; }
public function baz(){ echo "baz"; }
}
class MyClass extends MyAbstract2{
}
$obj=new MyClass;
$obj->foo();
$obj->bar();
$obj->baz();
//output: foobarbaz
Note: Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error. So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code.
below example will cause Fatal error: Class 'horse' not found
class cart extends horse {
public function get_breed() { return "Wood"; }
}
abstract class horse extends animal {
public function get_breed() { return "Jersey"; }
}
abstract class animal {
public abstract function get_breed();
}
$cart = new cart();
print($cart->get_breed());
This calls exactly for the using the Maven JAR Plugin
For example, if you want to exclude everything under src/test/resources/
from the final jar, put this:
<build>
<plugins>
<!-- configure JAR build -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<excludes>
<exclude>src/test/resources/**</exclude>
</excludes>
</configuration>
</plugin>
...
Files under src/test/resources/
will still be available on class-path, they just won't be in resulting JAR.
I tried changing the Internal Testers option, tried changing other items on the app details page, and tried uploading several new binaries (with the same code, only changing the build number) over a 2-day period to no effect. I also contacted Apple through the iTunes Connect support link; they replied in less than 24 hours, but only to ask for more info (most of which I had already provided).
Finally, the fifth build I uploaded, two days later, went through in the normal few minutes and I was finally able to submit my app for review.
Following Query works for me. Database Tabel t_sonde_results has domain d_date (datatype DATE) and d_time (datatype TIME) The intention is to query for last entry in t_sonde_results sorted by Date and Time
select * from
(select * from
(SELECT * FROM t_sonde_results
WHERE d_user_name = 'kenis' and d_smartbox_id = 6 order by d_time asc) AS tmp
order by d_date and d_time limit 1) as tmp1
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];_x000D_
var results = array.map(function(item){_x000D_
return {good : item["good"]}_x000D_
});_x000D_
console.log(JSON.stringify(results));
_x000D_
Use the CLIM function (equivalent to CAXIS function in MATLAB):
plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4) # identical to caxis([-4,4]) in MATLAB
plt.show()
In my case I had tried to make code more readable by putting:
"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"
Once I changed it to
LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING
Then it worked
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.'
and the slash '/'
.
Instead of writing:
D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"
Write:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
i just change gradle version classpath 'com.android.tools.build:gradle:3.5.3'
to
classpath 'com.android.tools.build:gradle:3.3.2'
and now working.
For me, this helped: 1. Configuration properties/General/Platform Toolset = Windows XP (V110_xp) 2. C/C++ Preprocessor definitions, add "WIN32" 3. Linker/System/Minimum required version = 5.01
You can use dummynet ofcourse, There is extension of dummynet called KauNet. which can provide even more precise control of network conditions. It can drop/delay/re-order specific packets (that way you can perform more in-depth analysis of dropping key packets like TCP handshake to see how your web pages digest it). It also works in time domain. Usually most the emulators are tuned to work in data domain. In time domain you can specify from what time to what time you can alter the network conditions.
I dont think youre returning json object from server. just a string.
you need the dataType of the return object to be json
Consider using a dictionary:
myDict = {}
for i in range(20):
myDict[i] = i * i
print(5 in myDict)
Others answers are great, I just wanted to add an alternative solution with ES6
Array function : filter
.
filter()
creates a new array with elements that fall under a given criteria from an existing array.
So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.
Some examples :
Remove first element :
// Not very useful but it works
function removeFirst(element, index) {
return index > 0;
}
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]
Remove second element :
function removeSecond(element, index) {
return index != 1;
}
var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]
Remove odd element :
function removeOdd(element, index) {
return !(element % 2);
}
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]
Remove items not in stock
const inventory = [
{name: 'Apple', qty: 2},
{name: 'Banana', qty: 0},
{name: 'Orange', qty: 5}
];
const res = inventory.find( product => product.qty > 0);
The icon file is added to your project as a content file.
Recently, I have tried to develop a simple web app that uses drag and drop components and has lines connecting them. I came across these two simple and amazing javascript libraries:
Working example link (usage: click on add scene to create a draggable, click on add choice to draw a leader line between two different draggables)
You haven't mentioned a language, so I'm going to give you some some hints how to do it with the straight Windows API in C.
First, open a connection to the printer with OpenPrinter
. Next, start a document with StartDocPrinter
having the pDatatype
field of the DOC_INFO_1
structure set to "RAW"
- this tells the printer driver not to encode anything going to the printer, but to pass it along unchanged. Use StartPagePrinter
to indicate the first page, WritePrinter
to send the data to the printer, and close it with EndPagePrinter
, EndDocPrinter
and ClosePrinter
when done.
The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want:
1) Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references.
2) Add 'using mshtml;' to your namespaces.
3) Get a reference to your script element's IHTMLElement:
IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;
4) Call the insertAdjacentText method, with the first parameter value of "afterBegin". All the possible values are listed here:
iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }");
5) Now you'll be able to see the code in the scriptEl.InnerText property.
Hth, Richard
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
print
For your own classes, just def a __str__
method
Here's a Swift 3 adaptation of @leviatan's answer :
EXTENSION
import UIKit
extension UIScrollView {
func resizeScrollViewContentSize() {
var contentRect = CGRect.zero
for view in self.subviews {
contentRect = contentRect.union(view.frame)
}
self.contentSize = contentRect.size
}
}
USAGE
scrollView.resizeScrollViewContentSize()
Very easy to use !
In ASCII the upper and lower case alphabet are 0x20 apart from each other, so this is another way to do it.
int lower(int a)
{
if ((a >= 0x41) && (a <= 0x5A))
a |= 0x20;
return a;
}
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation
http://www.java-samples.com/showtutorial.php?tutorialid=458
cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;
outputs
.....lolcat
Came across this while looking for help. I was trying to implement the favicon in my Django project and it was not showing -- wanted to add to the conversation.
While trying to implement the favicon in my Django project I renamed the 'favicon.ico' file to 'my_filename.ico' –– the image would not show. After renaming to 'favicon.ico' resolved the issue and graphic displayed. below is the code that resolved my issue:
<link rel="shortcut icon" type="image/png" href="{% static 'img/favicon.ico' %}" />
How about splay trees?
Also, Chris Okasaki's purely functional data structures come to mind.
SELECCT TO_BASE64(blobfield)
FROM the Table
worked for me.
The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.
This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).
For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
If IsNumeric(r) Then
r.Value = CSng(r.Value)
r.NumberFormat = "0.00"
End If
Next
Using loop in hbs little bit complex
<tbody>
{{#each item}}
<tr>
<td><!--HOW TO GET ARRAY INDEX HERE?--></td>
<td>{{@index}}</td>
<td>{{this}}</td>
</tr>
{{/each}}
</tbody>
Go to http://localhost/phpmyadmin and click on the Privileges tab. There is a "Add a new user" link.
Ctrl-Alt-X is the keyboard shortcut I use, although that may because I have Resharper
installed - otherwise Ctrl W, X.
From the menu: View -> Toolbox.
You can easily view/change key bindings using Tools -> Options Environment->Keyboard. It has a convenient UI where you can enter a word, and it shows you what key bindings include that word, including View.Toolbox
.
You might want to browse through the online MSDN documentation on getting started with Visual Studio.
There is a simple, easy and better approach, if we need to change only the color of hamburger/back icon.
It is better as it changes color only of desired icon, whereas colorControlNormal
and android:textColorSecondary
might affect other childviews of toolbar as well.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@android:color/white</item>
</style>
There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append
.
resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)
outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))
which gives your requested format
> str(outlist)
List of 3
$ :List of 5
..$ : num 1
..$ : num 2
..$ : num 3
..$ : num 4
..$ : num 5
$ :List of 5
..$ : num 6
..$ : num 7
..$ : num 8
..$ : num 9
..$ : num 10
$ :List of 5
..$ : num 11
..$ : num 12
..$ : num 13
..$ : num 14
..$ : num 15
Why don't you simply use set_index
method?
In : col = ['a','b','c']
In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
In : data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In : data2 = data.set_index('a')
In : data2
Out:
b c
a
1 2 3
10 11 12
20 21 22
There are very well answers here, but I want to add one line:
In android:onclick
in XML, Android uses java reflection behind the scene to handle this.
And as explained here, reflection always slows down the performance. (especially on Dalvik VM). Registering onClickListener
is a better way.
If you have several ruby installed, it might be sufficient just to remove one of them, on MacosX with extra ports install, remove the ports ruby installation with:
sudo port -f uninstall ruby
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
var a = ["one", "two", "three", "four", "five"]
// Remove/filter item with value 'three'
a = a.filter { $0 != "three" }
On Windows Powershell I run this:
git stash apply "stash@{1}"
You're nearly there, just take out the EXECUTE:
DECLARE
procId NUMBER;
BEGIN
PKG1.INIT(1143824, 0, procId);
DBMS_OUTPUT.PUT_LINE(procId);
END;
There is a HUGE difference between VARCHAR and TEXT. While VARCHAR fields can be indexed, TEXT fields cannot. VARCHAR type fields are stored inline while TEXT are stored offline, only pointers to TEXT data is actually stored in the records.
If you have to index your field for faster search, update or delete than go for VARCHAR, no matter how big. A VARCHAR(10000000) will never be the same as a TEXT field bacause these two data types are different in nature.
than go for TEXT.
Just use Collections.sort(yourListHere)
here to sort.
You can read more about Collections from here.
I received this error in my code because I'd not run JSON.parse(result).
So my result was a string instead of an array of objects.
i.e. I got:
"[{},{}]"
instead of:
[{},{}]
import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
.then((value) => {
let servers: Server[] = JSON.parse(value) as Server[];
}
);
I had this issue was trying to remove a ui element inside an event reactive:
myReactives <- eventReactive(input$execute, {
... # Some other long running function here
removeUI(selector = "#placeholder2")
})
I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.
I have done this way:
Set Color on Text by passing String and color:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Set text on TextView / Button / EditText etc by calling below code:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
Get Colored String:
String name = getColoredSpanned("Hiren", "#800000");
String surName = getColoredSpanned("Patel","#000080");
Set Text on TextView of two strings with different colors:
txtView.setText(Html.fromHtml(name+" "+surName));
Done
Step 1 - The problem is with Eclipse IDE Step 2 - Right Click Maven Dependencies -> Build Path -> Remove Build Path
Update pom.xml for spring-web and spring-webmvc
Step 3 - Update Maven Dependencies
You will see the Spring-Web files will be in the maven dependencies folder.
You can get the Silverlight Chart Controls running on WPF, they're quite nice (and free).
just use file_put_contents('file',$myarray);
file_put_contents() works with arrays too.
Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.
unsigned short crc16(const unsigned char* data_p, unsigned char length){
unsigned char x;
unsigned short crc = 0xFFFF;
while (length--){
x = crc >> 8 ^ *data_p++;
x ^= x>>4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
}
return crc;
}
There isn't a last()
or first()
method in a Collection interface. For getting the last method, you can either do get(size() - 1)
on a List or reverse the List and do get(0)
. I don't see a need to have last()
method in any Collection API unless you are dealing with Stacks
or Queues
x
is Unsigned hexadecimal integer ( 32 Bit )
p
is Pointer address
See printf on the C++ Reference. Even if both of them would write the same, I would use %p
to print a pointer.
For the timer part of your script i highly reccomend using:
echo.
echo Waiting For One Hour...
TIMEOUT /T 3600 /NOBREAK
echo.
echo (Put some Other Processes Here)
echo.
pause >nul
This script waits for 1 hour (3600 seconds) and then continues on with the script and the user cannot press any buttons to bypass the timer (besides CTRL+C).
You can use
Timeout /t 3600 /nobreak >nul
If you don't want to see a countdown on the screen.
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
document.getElementById('myinput').onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8
|| e.keyCode == 9)) {
return false;
}
}
In my case, executing "Sync Project with Gradle Files" helped. Neither restarting Andoid Studio nor clearing the cache did anything.
Additional info to generate absolute URL using a command (to send an email for instance)
In a command, {{ absolute_url(path('index')) }}
is not working out of the box.
You will need to add the additional configuration shown in antongorodezkiy's answer.
But in case you don't want to change the configuration because you are not sure how it could impact the whole app, you can configure the router in the command.
Here is the doc :
https://symfony.com/doc/3.4/console/request_context.html
Here is the code :
use Symfony\Component\Routing\RouterInterface;
// ...
class DemoCommand extends Command
{
private $router;
public function __construct(RouterInterface $router)
{
parent::__construct();
$this->router = $router;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$context = $this->router->getContext();
$context->setHost('example.com');
$context->setScheme('https');
$context->setBaseUrl('my/path');
$url = $this->router->generate('route-name', ['param-name' => 'param-value']);
// ...
}
}
To generate the URL in the Twig template
<a href="{{ absolute_url(path(...)) }}"></a>
You can fetch the HOST and SCHEME from your env file
$context = $this->router->getContext();
$context->setHost($_ENV['NL_HOST']);
$context->setScheme($_ENV['NL_SCHEME']);
Just define the variable in .env and .env.local files
NL_HOST=mydomain.com
NL_SCHEME=https
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
MSDN Documentation Here
To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code
SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')
If that doesn't work check to make sure you have entered a valid GUID
Just add this line :
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
If you wirte to a .csv file in C++ - you should use the syntax of :
myfile <<" %s; %s; %d", string1, string2, double1 <<endl;
This will write the three variables (string 1&2 and double1) into separate columns and leave an empty row below them. In excel the ; means the new row, so if you want to just take a new row - you can alos write a simple ";" before writing your new data into the file. If you don't want to have an empty row below - you should delete the endl and use the:
myfile.open("result.csv", std::ios::out | std::ios::app);
syntax when opening the .csv file (example the result.csv). In this way next time you write something into your result.csv file - it will write it into a new row directly below the last one - so you can easily manage a for cycle if you would like to.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
To convert the year from string to int, you can add the following option to the csv reader: "inferSchema" -> "true", see DataBricks documentation
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
It's great answer in here. And I want to add 'Why Add a element in Maven3'.
In Maven 3.x Compatibility Notes
Plugin Metaversion Resolution
Internally, Maven 2.x used the special version markers RELEASE and LATEST to support automatic plugin version resolution. These metaversions were also recognized in the element for a declaration. For the sake of reproducible builds, Maven 3.x no longer supports usage of these metaversions in the POM. As a result, users will need to replace occurrences of these metaversions with a concrete version.
And I also find in maven-compiler-plugin - usage
Note: Maven 3.0 will issue warnings if you do not specify the version of a plugin.
The current answers contain a lot of hand-rolled or library code. This is not necessary.
Use JSON.parse('{"a":1}')
to create a plain object.
Use one of the standardized functions to set the prototype:
Object.assign(new Foo, { a: 1 })
Object.setPrototypeOf({ a: 1 }, Foo.prototype)
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
That is correct behaviour, it's up to you to create the contents for the 404 page.
The 404 header is used by spiders and download-managers to determine if the file exists.
(A page with a 404 header won't be indexed by google or other search-engines)
Normal users however don't look at http-headers and use the page as a normal page.
If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
It will use to make menu bar in directory format
$pathLen = 0;
function prePad($level)
{
$ss = "";
for ($ii = 0; $ii < $level; $ii++)
{
$ss = $ss . "| ";
}
return $ss;
}
function myScanDir($dir, $level, $rootLen)
{
global $pathLen;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry))
{
$allFiles[] = "D: " . $dir . "/" . $entry;
}
else
{
$allFiles[] = "F: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($allFiles);
foreach($allFiles as $value)
{
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", " ", substr($value, $pathLen + 3));
if (is_dir($fileName))
{
echo "<li ><a class='dropdown'><span>" . $displayName . " </span></a><ul>";
myScanDir($fileName, $level + 1, strlen($fileName));
echo "</ul></li>";
}
else {
$newstring = substr($displayName, -3);
if($newstring == "PDF" || $newstring == "pdf" )
echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";
}
$t;
if($level != 0)
{
if($level < $t)
{
$r = int($t) - int($level);
for($i=0;$i<$r;$i++)
{
echo "</ul></li>";
}
}
}
$t = $level;
}
}
}
?>
<li style="color: #ffffff">
<?php
// ListFolder('D:\PDF');
$root = 'D:\PDF';
$pathLen = strlen($root);
myScanDir($root, 0, strlen($root));
?>
</li>
If you don't have to support IE, you can use selectionStart
and selectionEnd
attributes of textarea
.
To get caret position just use selectionStart
:
function getCaretPosition(textarea) {
return textarea.selectionStart
}
To get the strings surrounding the selection, use following code:
function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}
See also HTMLTextAreaElement docs.
This happens when you specify the incorrect position for the notifyItemChanged , notifyItemRangeInserted etc.For me :
Before : (Erroneous)
public void addData(List<ChannelItem> list) {
int initialSize = list.size();
mChannelItemList.addAll(list);
notifyItemRangeChanged(initialSize - 1, mChannelItemList.size());
}
After : (Correct)
public void addData(List<ChannelItem> list) {
int initialSize = mChannelItemList.size();
mChannelItemList.addAll(list);
notifyItemRangeInserted(initialSize, mChannelItemList.size()-1); //Correct position
}
The existing answers missed an option, so here's a complete list:
// 1. Explicitly declare the type
var arr: Criminal[] = [];
// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];
// 3. Using the Array constructor
var arr = new Array<Criminal>();
Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.
The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.
Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.
It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.
*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.
You may also use get_chunks
function of utilspie
library as:
>>> from utilspie import iterutils
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(iterutils.get_chunks(a, 5))
[[1, 2, 3, 4, 5], [6, 7, 8, 9]]
You can install utilspie
via pip:
sudo pip install utilspie
Disclaimer: I am the creator of utilspie library.