For iOS 10+, you can use this method for knowing when your notification is clicked irrespective of the state of the app.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//Notification clicked
completionHandler()
}
In VueJS you can use forEach like below.
let list=[];
$.each(response.data.message, function(key, value) {
list.push(key);
});
So, now you can have all arrays into list . use for loop to get values or keys
Don't do this use a dictionary
import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
setattr(this, 'string%s' % x, 'Hello')
print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8
don't do this use a dict
globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
print $item->title;
}
There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:
private bool IsValidPath(string path)
{
// Check if the path is rooted in a driver
if (path.Length < 3) return false;
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
// Check if such driver exists
IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;
// Check if the rest of the path is valid
string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
InvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
if (path[path.Length - 1] == '.') return false;
return true;
}
This solution does not take relative paths into account.
In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.
For objects, their default constructor is called. For example, for std::string
, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.
For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.
For references (e.g. std::string&
), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.
So, in your specific case, if they are not explicitly initialized:
int *ptr; // Contains junk
string name; // Empty string
string *pname; // Contains junk
string &rname; // Compile error
const string &crname; // Compile error
int age; // Contains junk
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
You can select the database when connecting with psql. This is handy when using it from a script:
sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test
SYSDATE returns the system date, of the system on which the database resides
CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE
execute this comman
ALTER SESSION SET TIME_ZONE = '+3:0';
and it will provide you the same result.
There is the concatenate function. For example
=CONCATENATE(E2,"-",F2)But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
In Visual Studio 2013 AND VS15 (but i guess if the same for all other version) just press F4 and change this two properties: -Anonymous Authentication: Disable -Windows Authentication: Enable
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
I ended up having to make a slight change using the click event on the input element by also setting the checked prop after firing the click event.
$(y.Ctrl).multiselect("widget").find(":checkbox").each(function () {
if ($.inArray(this.value, uniqueVals) != -1) {
$(this).click();
$(this).prop('checked', true);
}
});
fearless_fool has a great answer for older versions. I just wanted to add that you need to make sure you have all the columns listed. So if you have 3 columns, you need to make sure select acts on 3 columns.
Example: I have 3 columns but I only want to insert 2 columns worth of data. Assume I don't care about the first column because it's a standard integer id. I could do the following...
INSERT INTO 'tablename'
SELECT NULL AS 'column1', 'data1' AS 'column2', 'data2' AS 'column3'
UNION SELECT NULL, 'data3', 'data4'
UNION SELECT NULL, 'data5', 'data6'
UNION SELECT NULL, 'data7', 'data8'
Note: Remember the "select ... union" statement will lose the ordering. (From AG1)
first,i used "localhost:port" format met this error.then I changed the address to "ip:port" format and the problem solved.
textBox1.Text = "Line1" + Environment.NewLine + "Line2";
Also the markup needs to include TextMode="MultiLine" (otherwise it shows text as one line)
<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>
With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key. Example - Pageone.html -
<script>
localStorage.setItem("firstname", "Smith");
</script>
Pagetwo.html -
<script>
var name=localStorage.getItem("firstname");
</script>
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
note: set Locale
according to your environment/requirement
See Also
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
Here is a simple example.
this method will return a 2 dimensional tType
array
public tType[][] allocate(Class<tType> c,int row,int column){
tType [][] matrix = (tType[][]) Array.newInstance(c,row);
for (int i = 0; i < column; i++) {
matrix[i] = (tType[]) Array.newInstance(c,column);
}
return matrix;
}
say you want a 2 dimensional String array, then call this function as
String [][] stringArray = allocate(String.class,3,3);
This will give you a two dimensional String array with 3 rows and 3 columns;
Note that in Class<tType> c
-> c
cannot be primitive type like say, int
or char
or double
. It must be non-primitive like, String
or Double
or Integer
and so on.
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
When learning algorithms, the programming language (Java) should not be considered in deciding the representation. Each problem could benefit from a unique representation, and moreover designing it can add a bit of learning. Solve the problem first without relying on a particular language, then the representation for any particular language will flow naturally.
Of course, general representations and libraries are useful in real-world applications. But some of them could benefit from some customization as well. Use the other answers to know the different techniques available, but consider customization when appropriate.
Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:
alert(col.firstChild.value);
Just use
int listCount = data.size();
That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:
int total = 0;
for (List<String> sublist : data) {
// TODO: Null checking
total += sublist.size();
}
// total is now the total number of strings
That is because you have used following line to assign the value which is wrong.
x=&x;
In PL/SQL assignment is done using following.
:=
So your code should be like this.
declare
x number;
begin
x:=&x;
-- Below line will output the number you received as an input
dbms_output.put_line(x);
end;
/
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
You can use findHandlersJS
You can find the handler by doing in the chrome console:
findEventHandlers("click", "img.envio")
You'll get the following information printed in chrome's console:
More info here and you can try it in this example site here.
To avoid warnings, you can:
Set-ExecutionPolicy bypass
You could simply not include the line into the new file instead of doing replace.
for line in infile :
if 'bad' not in line and 'naughty' not in line:
newopen.write(line)
public class ScreenShotActivity extends Activity{
private RelativeLayout relativeLayout;
private Bitmap myBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
relativeLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(relativeLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
}
ADD PERMISSION
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.
"You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden." --- According to @Laurent Russier's comment.
I never got any message from Firebase, until i put my app in the background.
This is true only on usb connection for emulator you get notification in foreground as well
Put your form inside an asp.net panel control and set its defaultButton attribute with your button Id. See the code below:
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Hope this will help you...
If you want to convert the string back into a byte array you will need to use String.getBytes()
(or equivalent Python function) and this will allow you print out the original byte array.
I was recently shown this website for liquid layouts using CSS. http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts (Take a look at the demo pages in the links below).
The author now provides an example for fixed width layouts. Check out; http://matthewjamestaylor.com/blog/how-to-convert-a-liquid-layout-to-fixed-width.
This provides the following example(s), http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm (for two column layout like you are after I think)
http://matthewjamestaylor.com/blog/fixed-width-or-liquid-layout.htm (for three column layout).
Sorry for so many links to this guys site, but I think it is an AWESOME resource.
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
This page on MSDN lists standard DateTime format strings, uncluding strings using the 'Z'.
Update: you will need to make sure that the rest of the date string follows the correct pattern as well (you have not supplied an example of what you send it, so it's hard to say whether you did or not). For the UTC format to work it should look like this:
// yyyy'-'MM'-'dd HH':'mm':'ss'Z'
DateTime utcTime = DateTime.Parse("2009-05-07 08:17:25Z");
add:
margin: 0 0 3px 0;
to your #access li
and move
background: #0f84e8; /* Show a solid color for older browsers */
to the #access a
and take out the border-bottom
. Then it will work
Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.experimental.max.MaxCore;
class BSTNode {
BSTNode left = null;
BSTNode rigth = null;
int data = 0;
public BSTNode() {
super();
}
public BSTNode(int data) {
this.left = null;
this.rigth = null;
this.data = data;
}
@Override
public String toString() {
return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
}
}
class BinarySearchTree {
BSTNode root = null;
public BinarySearchTree() {
}
public void insert(int data) {
BSTNode node = new BSTNode(data);
if (root == null) {
root = node;
return;
}
BSTNode currentNode = root;
BSTNode parentNode = null;
while (true) {
parentNode = currentNode;
if (currentNode.data == data)
throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");
if (currentNode.data > data) {
currentNode = currentNode.left;
if (currentNode == null) {
parentNode.left = node;
return;
}
} else {
currentNode = currentNode.rigth;
if (currentNode == null) {
parentNode.rigth = node;
return;
}
}
}
}
public int countNodes() {
return countNodes(root);
}
private int countNodes(BSTNode node) {
if (node == null) {
return 0;
} else {
int count = 1;
count += countNodes(node.left);
count += countNodes(node.rigth);
return count;
}
}
public boolean searchNode(int data) {
if (empty())
return empty();
return searchNode(data, root);
}
public boolean searchNode(int data, BSTNode node) {
if (node != null) {
if (node.data == data)
return true;
else if (node.data > data)
return searchNode(data, node.left);
else if (node.data < data)
return searchNode(data, node.rigth);
}
return false;
}
public boolean delete(int data) {
if (empty())
throw new NoSuchElementException("Tree is Empty");
BSTNode currentNode = root;
BSTNode parentNode = root;
boolean isLeftChild = false;
while (currentNode.data != data) {
parentNode = currentNode;
if (currentNode.data > data) {
isLeftChild = true;
currentNode = currentNode.left;
} else if (currentNode.data < data) {
isLeftChild = false;
currentNode = currentNode.rigth;
}
if (currentNode == null)
return false;
}
// CASE 1: node with no child
if (currentNode.left == null && currentNode.rigth == null) {
if (currentNode == root)
root = null;
if (isLeftChild)
parentNode.left = null;
else
parentNode.rigth = null;
}
// CASE 2: if node with only one child
else if (currentNode.left != null && currentNode.rigth == null) {
if (root == currentNode) {
root = currentNode.left;
}
if (isLeftChild)
parentNode.left = currentNode.left;
else
parentNode.rigth = currentNode.left;
} else if (currentNode.rigth != null && currentNode.left == null) {
if (root == currentNode)
root = currentNode.rigth;
if (isLeftChild)
parentNode.left = currentNode.rigth;
else
parentNode.rigth = currentNode.rigth;
}
// CASE 3: node with two child
else if (currentNode.left != null && currentNode.rigth != null) {
// Now we have to find minimum element in rigth sub tree
// that is called successor
BSTNode successor = getSuccessor(currentNode);
if (currentNode == root)
root = successor;
if (isLeftChild)
parentNode.left = successor;
else
parentNode.rigth = successor;
successor.left = currentNode.left;
}
return true;
}
private BSTNode getSuccessor(BSTNode deleteNode) {
BSTNode successor = null;
BSTNode parentSuccessor = null;
BSTNode currentNode = deleteNode.left;
while (currentNode != null) {
parentSuccessor = successor;
successor = currentNode;
currentNode = currentNode.left;
}
if (successor != deleteNode.rigth) {
parentSuccessor.left = successor.left;
successor.rigth = deleteNode.rigth;
}
return successor;
}
public int nodeWithMinimumValue() {
return nodeWithMinimumValue(root);
}
private int nodeWithMinimumValue(BSTNode node) {
if (node.left != null)
return nodeWithMinimumValue(node.left);
return node.data;
}
public int nodewithMaximumValue() {
return nodewithMaximumValue(root);
}
private int nodewithMaximumValue(BSTNode node) {
if (node.rigth != null)
return nodewithMaximumValue(node.rigth);
return node.data;
}
public int parent(int data) {
return parent(root, data);
}
private int parent(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode parent = null;
BSTNode current = node;
while (current.data != data) {
parent = current;
if (current.data > data)
current = current.left;
else
current = current.rigth;
if (current == null)
throw new IllegalArgumentException(data + " is not a node in tree");
}
return parent.data;
}
public int sibling(int data) {
return sibling(root, data);
}
private int sibling(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode cureent = node;
BSTNode parent = null;
boolean isLeft = false;
while (cureent.data != data) {
parent = cureent;
if (cureent.data > data) {
cureent = cureent.left;
isLeft = true;
} else {
cureent = cureent.rigth;
isLeft = false;
}
if (cureent == null)
throw new IllegalArgumentException("No Parent node found");
}
if (isLeft) {
if (parent.rigth != null) {
return parent.rigth.data;
} else
throw new IllegalArgumentException("No Sibling is there");
} else {
if (parent.left != null)
return parent.left.data;
else
throw new IllegalArgumentException("No Sibling is there");
}
}
public void leafNodes() {
if (empty())
throw new IllegalArgumentException("Empty");
leafNode(root);
}
private void leafNode(BSTNode node) {
if (node == null)
return;
if (node.rigth == null && node.left == null)
System.out.print(node.data + " ");
leafNode(node.left);
leafNode(node.rigth);
}
public int level(int data) {
if (empty())
throw new IllegalArgumentException("Empty");
return level(root, data, 1);
}
private int level(BSTNode node, int data, int level) {
if (node == null)
return 0;
if (node.data == data)
return level;
int result = level(node.left, data, level + 1);
if (result != 0)
return result;
result = level(node.rigth, data, level + 1);
return result;
}
public int depth() {
return depth(root);
}
private int depth(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(depth(node.left), depth(node.rigth));
}
public int height() {
return height(root);
}
private int height(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(height(node.left), height(node.rigth));
}
public void leftView() {
leftView(root);
}
private void leftView(BSTNode node) {
if (node == null)
return;
int height = height(node);
for (int i = 1; i <= height; i++) {
printLeftView(node, i);
}
}
private boolean printLeftView(BSTNode node, int level) {
if (node == null)
return false;
if (level == 1) {
System.out.print(node.data + " ");
return true;
} else {
boolean left = printLeftView(node.left, level - 1);
if (left)
return true;
else
return printLeftView(node.rigth, level - 1);
}
}
public void mirroeView() {
BSTNode node = mirroeView(root);
preorder(node);
System.out.println();
inorder(node);
System.out.println();
postorder(node);
System.out.println();
}
private BSTNode mirroeView(BSTNode node) {
if (node == null || (node.left == null && node.rigth == null))
return node;
BSTNode temp = node.left;
node.left = node.rigth;
node.rigth = temp;
mirroeView(node.left);
mirroeView(node.rigth);
return node;
}
public void preorder() {
preorder(root);
}
private void preorder(BSTNode node) {
if (node != null) {
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.rigth);
}
}
public void inorder() {
inorder(root);
}
private void inorder(BSTNode node) {
if (node != null) {
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.rigth);
}
}
public void postorder() {
postorder(root);
}
private void postorder(BSTNode node) {
if (node != null) {
postorder(node.left);
postorder(node.rigth);
System.out.print(node.data + " ");
}
}
public boolean empty() {
return root == null;
}
}
public class BinarySearchTreeTest {
public static void main(String[] l) {
System.out.println("Weleome to Binary Search Tree");
Scanner scanner = new Scanner(System.in);
boolean yes = true;
BinarySearchTree tree = new BinarySearchTree();
do {
System.out.println("\n1. Insert");
System.out.println("2. Search Node");
System.out.println("3. Count Node");
System.out.println("4. Empty Status");
System.out.println("5. Delete Node");
System.out.println("6. Node with Minimum Value");
System.out.println("7. Node with Maximum Value");
System.out.println("8. Find Parent node");
System.out.println("9. Count no of links");
System.out.println("10. Get the sibling of any node");
System.out.println("11. Print all the leaf node");
System.out.println("12. Get the level of node");
System.out.println("13. Depth of the tree");
System.out.println("14. Height of Binary Tree");
System.out.println("15. Left View");
System.out.println("16. Mirror Image of Binary Tree");
System.out.println("Enter Your Choice :: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Enter Value");
tree.insert(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 2:
System.out.println("Enter the node");
System.out.println(tree.searchNode(scanner.nextInt()));
break;
case 3:
System.out.println(tree.countNodes());
break;
case 4:
System.out.println(tree.empty());
break;
case 5:
try {
System.out.println("Enter the node");
System.out.println(tree.delete(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 6:
try {
System.out.println(tree.nodeWithMinimumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 7:
try {
System.out.println(tree.nodewithMaximumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 8:
try {
System.out.println("Enter the node");
System.out.println(tree.parent(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 9:
try {
System.out.println(tree.countNodes() - 1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 10:
try {
System.out.println("Enter the node");
System.out.println(tree.sibling(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 11:
try {
tree.leafNodes();
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 12:
try {
System.out.println("Enter the node");
System.out.println("Level is : " + tree.level(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 13:
try {
System.out.println(tree.depth());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 14:
try {
System.out.println(tree.height());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 15:
try {
tree.leftView();
System.out.println();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 16:
try {
tree.mirroeView();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
tree.preorder();
System.out.println();
tree.inorder();
System.out.println();
tree.postorder();
} while (yes);
scanner.close();
}
}
I haven't seen this done before, but this is how it was done for emulating IE 8/7 when using IE 9:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
If not, then try this one:
<meta http-equiv="X-UA-Compatible" content="IE=9">
Add those to your header with the other meta tags. This should force IE10 to render as IE9.
Another option you could do (assuming you are using PHP) is add this to your .htaccess
file:
Header set X-UA-Compatible "IE=9"
This will perform the action universally, rather than having to worry about adding the meta tag to all of your headers.
Create the animation
- (CABasicAnimation *)spinAnimationWithDuration:(CGFloat)duration clockwise:(BOOL)clockwise repeat:(BOOL)repeats
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
anim.toValue = clockwise ? @(M_PI * 2.0) : @(M_PI * -2.0);
anim.duration = duration;
anim.cumulative = YES;
anim.repeatCount = repeats ? CGFLOAT_MAX : 0;
return anim;
}
Add it to a view like this
CABasicAnimation *animation = [self spinAnimationWithDuration:1.0 clockwise:YES repeat:YES];
[self.spinningView.layer addAnimation:animation forKey:@"rotationAnimation"];
How is this answer different? You will have way cleaner code if most of your functions returns objects instead of just manipulating some objects here and there.
A vector is a container class while an array is an allocated memory.
The whole day has gone for me to resolve similar issue.
You must know that built-in serializor and Newtonsoft work differently. Im my case built-in cannot parse JSON number to System.String. But I had no obvious exception or details, just data came as null.
I discovered it only when I logged ModelState like that:
logger.LogInformation($"ModelState = {ModelState.IsValid}");
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
logger.LogInformation($"ModelMessages = {messages}");
And then I saw specific exception in logs:
The JSON value could not be converted to System.String
As a fix I did:
Microsoft.AspNetCore.Mvc.NewtonsoftJson
which is preview
version.services.AddControllers().AddNewtonsoftJson();
Solution taken from https://stackoverflow.com/a/57652537/4871693
If you only want to add Datapoints above the bars, you could easily do it with:
for i in range(len(frequencies)): # your number of bars
plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument
y = y_values[i]+1, #takes your y values as vertical positioning argument
s = data_labels[i], # the labels you want to add to the data
size = 9) # font size of datalabels
You could also ask git to create directory for you:
git init --bare test_repo.git
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
Both @Dorvalla’s answer and this blog post mentioned above pointed me into the right direction to fix the problem for myself; quoting from the latter:
If the table you're trying to create includes a foreign key constraint, and you've provided your own name for that constraint, remember that it must be unique within the database.
I wasn’t aware of that. I have changed my foreign key constraint names according to the following schema which appears to be used by Ruby on Rails applications, too:
<TABLE_NAME>_<FOREIGN_KEY_COLUMN_NAME>_fk
For the OP’s table this would be Link_lession_id_fk
, for example.
int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);
Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:
@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
val cacheFile = File(context.cacheDir, "splash_video")
try {
val inputStream = context.assets.open("splash_video")
val outputStream = FileOutputStream(cacheFile)
try {
inputStream.copyTo(outputStream)
} finally {
inputStream.close()
outputStream.close()
}
} catch (e: IOException) {
throw IOException("Could not open splash_video", e)
}
return cacheFile
}
This is late but this may help someone :) :) For adding the view programmatically try like
LinearLayout rlmain = new LinearLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
LinearLayout ll1 = new LinearLayout (this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);
setContentView(rlmain, llp);
This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)
Read the binary file content like this:
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
then "unpack" binary data using struct.unpack:
The start bytes: struct.unpack("iiiii", fileContent[:20])
The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i'
to create the correct format for the unpack method:
struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])
The end byte: struct.unpack("i", fileContent[-4:])
Try command + t
.
It works for me.
As for your first question: that code is perfectly fine and should work if item
equals one of the elements inside myList
. Maybe you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.
As for your second question: There's actually several possible ways if "finding" things in lists.
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in
operator for that:
3 in [1, 2, 3] # => True
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter
doesn't return a list, but a generator-like object.
If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else
clause as well, which is not really well-known). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration
if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
For lists, there's also the index
method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index
always returns the lowest index:......
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate()
instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.
However, Perl's regex works the same on any machine with Perl installed:
perl -pe 's/\s+/\n/g' file.txt
If you want to save the output:
perl -pe 's/\s+/\n/g' file.txt > newfile.txt
If you want only unique occurrences of words:
perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt
To use the callback style (https://facebook.github.io/react/docs/refs-and-the-dom.html) as recommended on React's documentation you can add a definition for a property on the class:
export class Foo extends React.Component<{}, {}> {
// You don't need to use 'references' as the name
references: {
// If you are using other components be more specific than HTMLInputElement
myRef: HTMLInputElement;
} = {
myRef: null
}
...
myFunction() {
// Use like this
this.references.myRef.focus();
}
...
render() {
return(<input ref={(i: any) => { this.references.myRef = i; }}/>)
}
A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>
You could use
awk '/test_pattern/ {
match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "put here the data to be wriiten";
try
{
FileWriter fw = new FileWriter(write_file);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(Content);
bw.append("hiiiii");
bw.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
`}
Sometimes getBoundingClientRect()
object's property value shows 0 for IE. In that case you have to set display = 'block'
for the element. You can use below code for all browser to get offset.
Extend jQuery functionality :
(function($) {
jQuery.fn.weOffset = function () {
var de = document.documentElement;
$(this).css("display", "block");
var box = $(this).get(0).getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
};
}(jQuery));
Use :
var elementOffset = $("#" + elementId).weOffset();
$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();
while ( $line = fgets($f, 1000) )
{
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
print_r($array);
I've got this exact error, but in my case I was binding values for the LIMIT
clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset;
resulted in LIMIT '10' OFFSET '1';
instead of LIMIT 10 OFFSET 1;
. What helps to correct that is the following:
$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);
Here is my solution for finding n
th occurrance of b
in string a
:
from functools import reduce
def findNth(a, b, n):
return reduce(lambda x, y: -1 if y > x + 1 else a.find(b, x + 1), range(n), -1)
It is pure Python and iterative. For 0 or n
that is too large, it returns -1. It is one-liner and can be used directly. Here is an example:
>>> reduce(lambda x, y: -1 if y > x + 1 else 'bibarbobaobaotang'.find('b', x + 1), range(4), -1)
7
Because Vue props is one way data flow, This prevents child components from accidentally mutating the parent’s state.
From the official Vue document, we will find 2 ways to solve this problems
if child component want use props as local data, it is best to define a local data property.
props: ['list'],
data: function() {
return {
localList: JSON.parse(this.list);
}
}
The prop is passed in as a raw value that needs to be transformed. In this case, it’s best to define a computed property using the prop’s value:
props: ['list'],
computed: {
localList: function() {
return JSON.parse(this.list);
},
//eg: if you want to filter this list
validList: function() {
return this.list.filter(product => product.isValid === true)
}
//...whatever to transform the list
}
You have to do something like:
case 1:
case 2:
case 3:
//do stuff
break;
You are looking for wctomb()
: it's in the ANSI standard, so you can count on it. It works even when the wchar_t
uses a code above 255. You almost certainly do not want to use it.
wchar_t
is an integral type, so your compiler won't complain if you actually do:
char x = (char)wc;
but because it's an integral type, there's absolutely no reason to do this. If you accidentally read Herbert Schildt's C: The Complete Reference, or any C book based on it, then you're completely and grossly misinformed. Characters should be of type int
or better. That means you should be writing this:
int x = getchar();
and not this:
char x = getchar(); /* <- WRONG! */
As far as integral types go, char
is worthless. You shouldn't make functions that take parameters of type char
, and you should not create temporary variables of type char
, and the same advice goes for wchar_t
as well.
char*
may be a convenient typedef for a character string, but it is a novice mistake to think of this as an "array of characters" or a "pointer to an array of characters" - despite what the cdecl tool says. Treating it as an actual array of characters with nonsense like this:
for(int i = 0; s[i]; ++i) {
wchar_t wc = s[i];
char c = doit(wc);
out[i] = c;
}
is absurdly wrong. It will not do what you want; it will break in subtle and serious ways, behave differently on different platforms, and you will most certainly confuse the hell out of your users. If you see this, you are trying to reimplement wctombs()
which is part of ANSI C already, but it's still wrong.
You're really looking for iconv()
, which converts a character string from one encoding (even if it's packed into a wchar_t
array), into a character string of another encoding.
Now go read this, to learn what's wrong with iconv.
I've recently found a lib called ion that brings a little extra to the table.
ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.
I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
the parent element has not to be empty at least put
before the child element.
I got that error message in code line containing SqlConnection.Open()
running my .NET code as x64 application. Running as x86 causing no errors.
Solution was to deactivate the Force protocol encryption
option for TCP/IP in
%windir%\System32\cliconfg.exe
In PowerShell you can use the command Set-Service:
Set-Service -Name Winmgmt -StartupType Manual
I haven't found a PowerShell command to view the startup type though. One would assume that the command Get-Service would provide that, but it doesn't seem to.
There is also a slight difference in the html output for a string data type.
Html.EditorFor:
<input id="Contact_FirstName" class="text-box single-line" type="text" value="Greg" name="Contact.FirstName">
Html.TextBoxFor:
<input id="Contact_FirstName" type="text" value="Greg" name="Contact.FirstName">
for my specific problem I had to replace
if let count = 1
{
// do something ...
}
With
let count = 1
if(count > 0)
{
// do something ...
}
This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.
It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):
Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.
You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.
The chrome developers also do change this periodically. They changed it recently from badidea
to thisisunsafe
so everyone using badidea
, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:
Rotate the interstitial bypass keyword
The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.
I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.
If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN
field in certificates now so if just using the old subject
field then even adding it to the certificate store will not result in a green padlock.
If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.
HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.
There's a Visual Studio Tools for Git by Microsoft. It only supports Visual Studio 2012 (update 2) though.
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
The above suggestions did not work for me. What really worked was the inclusion of the following lines in the application.properties
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 3600000
spring.datasource.validationQuery = SELECT 1
You can find the explanation out here
In order to clean the whole line (2 different ways):
myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.
myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.
However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.
It is unlikely you will be able to tell the difference in speed in most applications.
So if you know you are dealing with a List use the Count property, otherwise if you have a "unknown" IEnumerabl, use the Count() method and let it optimise for you.
It's an very important improvement for npm: guarantee exact same version of every package.
How to make sure your project built with same packages in different environments in a different time? Let's say, you may use ^1.2.3
in your package.json
, or some of your dependencies are using that way, but how can u ensure each time npm install
will pick up same version in your dev machine and in the build server? package-lock.json will ensure that.
npm install
will re-generate the lock file, when on build server or deployment server, do npm ci
(which will read from the lock file, and install the whole package tree)
%j
works for only Node.js. %j
converts a value to a JSON string and inserts it.
console.log('%j new messages for', 7, 'john')
// 7 new messages for john
Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj
file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.
I solved this by adding an entry to the existing ItemGroup
<ItemGroup>
<Compile Remove="Common\**" />
<Content Remove="Common\**" />
<EmbeddedResource Remove="Common\**" />
<None Remove="Common\**" />
<!-- new added item -->
<None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None
allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile
action that usually comes with Assembly Info entry in proj
files.
C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'
Go to your HTTP bindings in IIS (select your website, then on the right click on Bindings...). Delete your SSL and your HTTP binding. Re-Add them.
This usually fixes this for me.
Try this
frame$twohouses <- ifelse(frame$data>1, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
6 2 2
7 3 2
8 1 1
9 4 2
10 3 2
11 2 2
12 4 2
13 0 1
14 1 1
15 2 2
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
echo array_search("car",array_keys($a));
You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )
I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent
(because you are using jQuery
/tagged) method after prepare the object from array
var BODY = {
"recipients": {
"values": []
},
"subject": 'TitleOfSubject',
"body": 'This is the message body.'
}
var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": { "_path": "/people/"+names[ln] }
};
values.push(item1);
}
// Now merge with BODY
$.extend(BODY.recipients.values, values);
If you open the dropdown for the Text
property in Visual Studio, you can use the enter key to split lines. This will obviously only work for static text unless you know the maximum dimensions of dynamic text.
In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.
Sub Demo()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim query As String
Dim Col, Row As Integer
Dim objWS As New clsws_GlobalWeather
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
query = objWS.wsm_GetCitiesByCountry("india")
If Not XDoc.LoadXML(query) Then 'strXML is the string with XML'
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (query)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Worksheets("Sheet3").Cells(1, 1).Value = "Country"
Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
Worksheets("Sheet3").Cells(1, 2).Value = "City"
Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
For Each xChild In xParent.ChildNodes
Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
Col = Col + 1
Next xChild
Row = Row + 1
Col = 1
Next xParent
End Sub
It's a double-edged sword. It is sometimes very useful, but often dangerous.
When is it good? When you want 10 cases all processed the same way...
switch (c) {
case 1:
case 2:
... Do some of the work ...
/* FALLTHROUGH */
case 17:
... Do something ...
break;
case 5:
case 43:
... Do something else ...
break;
}
The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.
With zsh you can do this:
% cat infile
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class
Or you can use AWK:
% awk '!_[$0]++' infile
tar
more than one word
gz
java
class
I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.
With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.
<script type="text/javascript">
$('#memberModal').modal('show');
</script>
JPA was designed to provide an automatic mapping between Objects and a relational database. Since Integer is not a persistant entity, why do you need to use JPA ? A simple JDBC request will work fine.
What version of .NET and Visual Studio are you using?
When you created the new project, you should have a file in your solution called app.config. That is the default configuration file.
I started by using the answers here, but modified it to use YouTube's new iframe
embedding...
$('a.more').on('click', function(event) {
event.preventDefault();
$.fancybox({
'type' : 'iframe',
// hide the related video suggestions and autoplay the video
'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
'overlayShow' : true,
'centerOnScroll' : true,
'speedIn' : 100,
'speedOut' : 50,
'width' : 640,
'height' : 480
});
});
I'd first split the file into few smaller ones like this
$ split --lines=50000 /path/to/large/file /path/to/output/file/prefix
and then grep on the resulting files.
This Code work for me..
//Get Time and Date
private String getTimeMethod(String formate)
{
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(formate);
String formattedDate= dateFormat.format(date);
return formattedDate;
}
//this method is used to refresh Time every Second
private void refreshTime() //Call this method to refresh time
{
new Timer().schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
txtV_Time.setText(getTimeMethod("hh:mm:ss a")); //hours,Min and Second with am/pm
txtV_Date.setText(getTimeMethod("dd-MMM-yy")); //You have to pass your DateFormate in getTimeMethod()
};
});
}
}, 0, 1000);//1000 is a Refreshing Time (1second)
}
Easiest way is to hit up the information_schemas...
SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'
The tr
command could be replaced by //
bashism:
COMMAND=$'\nREBOOT\r \n'
echo "|${COMMAND}|"
|
OOT
|
echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT |
echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|
See Parameter Expansion and QUOTING in bash's man page:
man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash
man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash
As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND
do contain spaces...
COMMAND=$' \n RE BOOT \r \n'
echo "|$COMMAND|"
|
BOOT
|
CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
| RE BOOT |
shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}
CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
| RE BOOT|
CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|
Shortly:
COMMAND=$' \n RE BOOT \r \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|
Note: bash have extglob
option to be enabled (shopt -s extglob
) in order to use *(...)
syntax.
To those having this issue after update to Catalina, just execute this command on your terminal
sudo rm -rf /Library/Developer/CommandLineTools; xcode-select --install;
You should set height
of html, body, .wrapper
to 100%
(in order to inherit full height) and then just set a flex
value greater than 1
to .row3
and not on the others.
.wrapper, html, body {
height: 100%;
margin: 0;
}
.wrapper {
display: flex;
flex-direction: column;
}
#row1 {
background-color: red;
}
#row2 {
background-color: blue;
}
#row3 {
background-color: green;
flex:2;
display: flex;
}
#col1 {
background-color: yellow;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
background-color: orange;
flex: 1 1;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
background-color: purple;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
<div id="row1">this is the header</div>
<div id="row2">this is the second line</div>
<div id="row3">
<div id="col1">col1</div>
<div id="col2">col2</div>
<div id="col3">col3</div>
</div>
</div>
_x000D_
I do something like this:
new_hash = Hash[*original_hash.collect{|key,value| [key,value + 1]}.flatten]
This provides you with the facilities to transform the key or value via any expression also (and it's non-destructive, of course).
If you want to count all the sub-string (including overlapped) then use this method.
import re
def count_substring(string, sub_string):
regex = '(?='+sub_string+')'
# print(regex)
return len(re.findall(regex,string))
You can use Underscore.js. It really makes things simple.
For example, removing elements from an array, you need to do:
_.without([1, 2, 3], 2);
And the result will be [1, 3].
It reduces the code that you write using jQuery.grep, etc. in jQuery.
You can get if from your document_cache folder, subfolder (mine is 1946507). Once there, rename the "content" by adding .pdf to the end of the file, save, and open with any pdf reader.
In my case, force run #notifyDataSetChanged in main ui thread will fix
public void refresh() {
clearSelection();
// notifyDataSetChanged must run in main ui thread, if run in not ui thread, it will not update until manually scroll recyclerview
((Activity) ctx).runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
It works if you remove position:fixed
from #firstdiv
- but @Sj is probably right as well - most likely a z-index layering issue.
I think you're going to need separate lines for each segment:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random(size=(2,10))
for i in range(0, len(x), 2):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
plt.show()
(The numpy
import is just to set up some random 2x10 sample data)
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
for (int i = 0; i < 6; i++)
{
test.ColumnDefinitions.Add(new ColumnDefinition());
Label t1 = new Label();
t1.Content = "Test" + i;
Grid.SetColumn(t1, i);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
}
If your two angles are x and y, then one of the angles between them is abs(x - y). The other angle is (2 * PI) - abs(x - y). So the value of the smallest of the 2 angles is:
min((2 * PI) - abs(x - y), abs(x - y))
This gives you the absolute value of the angle, and it assumes the inputs are normalized (ie: within the range [0, 2p)
).
If you want to preserve the sign (ie: direction) of the angle and also accept angles outside the range [0, 2p)
you can generalize the above. Here's Python code for the generalized version:
PI = math.pi
TAU = 2*PI
def smallestSignedAngleBetween(x, y):
a = (x - y) % TAU
b = (y - x) % TAU
return -a if a < b else b
Note that the %
operator does not behave the same in all languages, particularly when negative values are involved, so if porting some sign adjustments may be necessary.
MSDN has a sample.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
fs.CanWrite
}
return false;
}
catch (IOException ex)
{
return true;
}
}
string filePath = "C:\\Documents And Settings\\yourfilename";
bool isFileInUse;
isFileInUse = FileInUse(filePath);
// Then you can do some checking
if (isFileInUse)
Console.WriteLine("File is in use");
else
Console.WriteLine("File is not in use");
Hope this helps!
You can use single quotes or double quotes.
This enables you for example to easily nest JavaScript content inside HTML attributes, without the need to escape the quotes. The same is when you create JavaScript with PHP.
The general idea is: if it is possible use such quotes that you won't need to escape.
Less escaping = better code.
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.
Now, let's have a draft code...
Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.
Hope it helps!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim oSheet As Excel.Worksheet
'We only want to do something if the changed cell is B6, right?
If Target.Address = "$B$6" Then
'Checks if it's a number...
If IsNumeric(Target.Value) Then
'Let's avoid values out of your bonds, correct?
If Target.Value > 0 And Target.Value < 51 Then
'Let's assign the worksheet we'll show / hide rows to one variable and then
' use only the reference to the variable itself instead of the sheet name.
' It's safer.
'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
' the sheet index within the workbook
Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
'We'll unhide before hide, to ensure we hide the correct ones
oSheet.Range("A7:A56").EntireRow.Hidden = False
oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
End If
End If
End If
End Sub
unzip
doesn't spew files everywhereWhen zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file
So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:
cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;
The ../$(basename $PWD)
is the magic that retains the parent directory.
So now unzip my.zip
will give a folder containing all your files:
parent-directory
+-- file1
+-- file2
+-- dir1
¦ +-- file3
¦ +-- file4
Instead of littering the current directory with the unzipped files:
file1
file2
dir1
+-- file3
+-- file4
I have used a trick to handle the apostrophe special character. When replacing ' for \' you need to place four backslashes before the apostrophe.
str.replaceAll("'","\\\\'");
Those pesky black dots you are referencing to are called bullets.
They are pretty simple to remove, just add this line to your css:
ul {
list-style-type: none;
}
Hope this helps
A one-liner command in Windows PowerShell to delete or rename certain characters will be as below. (here the whitespace is being replaced with underscore)
Dir | Rename-Item –NewName { $_.name –replace " ","_" }
I like the aliases too ... however, I've had issues with MySQLCOM for start ... it fails silently ... My workaround is akin to the others ... ~/.bash_aliases
alias mysqlstart='sudo /usr/local/mysql/support-files/mysql.server start'
alias mysqlstop='sudo /usr/local/mysql/support-files/mysql.server stop'
A simple program shows how to use for loop to find sum of serveral integers.
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
int endnum = 2;
for(int i = 0; i<=endnum; i++){
sum += i;
}
cout<<sum;
}
I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey
instead of ControlBrushKey
:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>
Hope this helps someone out.
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
qsort()
is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.
It does its magic and your array is sorted in-place. An example follows:
#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2)
{
int f = *((int*)elem1);
int s = *((int*)elem2);
if (f > s) return 1;
if (f < s) return -1;
return 0;
}
int main(int argc, char* argv[])
{
int x[] = {4,5,2,3,1,0,9,8,6,7};
qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);
for (int i = 0 ; i < 10 ; i++)
printf ("%d ", x[i]);
return 0;
}
In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:
@media print{
* {
display:inline;
}
script, style {
display:none;
}
div {
page-break-inside:avoid;
}
}
It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.
Maybe someone could expand on this.
This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,
"^-?\\d*(\\.\\d+)?$"
some strings that matches with this:
894
923.21
76876876
.32
-894
-923.21
-76876876
-.32
some strings that doesn't:
hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.
Have you tried: getElementbyId('ID_OF_ID').innerHTML
?
I had very similar errors in the Apache2 log files:
(104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
Premature end of script headers: phpinfo.php
After checking the wrapper scripts and Apache2 settings, I realized that /var/www/ did not have accordant permissions. Thus the FCGId Wrapper scripts could not be read at all.
ls -la /var/www
drwxrws--- 5 www-data www-data 4096 Oct 7 11:17 .
For my scenario chmod -o+rx /var/www
was required of course, since the used SuExec users are not member of www-data
user group - and they should not be member for security reasons of course.
Check out the aq
branch, and rebase from master
.
git checkout aq
git rebase master
The code in elyase's answer https://stackoverflow.com/a/27928411/4240413 does not actually work. Notice that sse is a scalar, and then it tries to iterate through it. The following code is a modified version. Not amazingly clean, but I think it works more or less.
class LinearRegression(linear_model.LinearRegression):
def __init__(self,*args,**kwargs):
# *args is the list of arguments that might go into the LinearRegression object
# that we don't know about and don't want to have to deal with. Similarly, **kwargs
# is a dictionary of key words and values that might also need to go into the orginal
# LinearRegression object. We put *args and **kwargs so that we don't have to look
# these up and write them down explicitly here. Nice and easy.
if not "fit_intercept" in kwargs:
kwargs['fit_intercept'] = False
super(LinearRegression,self).__init__(*args,**kwargs)
# Adding in t-statistics for the coefficients.
def fit(self,x,y):
# This takes in numpy arrays (not matrices). Also assumes you are leaving out the column
# of constants.
# Not totally sure what 'super' does here and why you redefine self...
self = super(LinearRegression, self).fit(x,y)
n, k = x.shape
yHat = np.matrix(self.predict(x)).T
# Change X and Y into numpy matricies. x also has a column of ones added to it.
x = np.hstack((np.ones((n,1)),np.matrix(x)))
y = np.matrix(y).T
# Degrees of freedom.
df = float(n-k-1)
# Sample variance.
sse = np.sum(np.square(yHat - y),axis=0)
self.sampleVariance = sse/df
# Sample variance for x.
self.sampleVarianceX = x.T*x
# Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root. ugly)
self.covarianceMatrix = sc.linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)
# Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
self.se = self.covarianceMatrix.diagonal()[1:]
# T statistic for each beta.
self.betasTStat = np.zeros(len(self.se))
for i in xrange(len(self.se)):
self.betasTStat[i] = self.coef_[0,i]/self.se[i]
# P-value for each beta. This is a two sided t-test, since the betas can be
# positive or negative.
self.betasPValue = 1 - t.cdf(abs(self.betasTStat),df)
center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39
var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
if(expressionDiv.charAt(i) != '"'){
expressionWithoutQuotes += expressionDiv.charAt(i);
}
}
This may work for you.
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.
I dug around and found this article:
Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
To continue your example you could do
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()
The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.
Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
use to .onBackPressed() to back Activity specify
@Override
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
Step 1
My computer > properties > Advance system settings
Step 2
environment variables > click New button under user variables > Enter variable name as 'PATH'
Copy the location of java bin (e.g:C:\Program Files\Java\jdk1.8.0_121\bin)
and paste it in Variable value and click OK Now open the eclipse.
import UIKit
extension CALayer {
func makeSnapshot() -> UIImage? {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
return screenshot
}
}
extension UIView {
func makeSnapshot() -> UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) }
} else {
return layer.makeSnapshot()
}
}
}
let image = view.makeSnapshot()
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
@IBOutlet var viewForScreenShot: UIView!
@IBOutlet var screenShotRenderer: UIImageView!
@IBAction func makeViewScreenShotButtonTapped2(_ sender: UIButton) {
screenShotRenderer.image = viewForScreenShot.makeSnapshot()
}
}
Main.storyboard
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_2214957" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Acg-GO-mMN">
<rect key="frame" x="67" y="28" width="240" height="128"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="4Fr-O3-56t">
<rect key="frame" x="72" y="49" width="96" height="30"/>
<constraints>
<constraint firstAttribute="height" constant="30" id="cLv-es-h7Q"/>
<constraint firstAttribute="width" constant="96" id="ytF-FH-gdm"/>
</constraints>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
</subviews>
<color key="backgroundColor" red="0.0" green="0.47843137250000001" blue="1" alpha="0.49277611300000002" colorSpace="custom" customColorSpace="sRGB"/>
<color key="tintColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerX" secondItem="Acg-GO-mMN" secondAttribute="centerX" id="egj-rT-Gz5"/>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerY" secondItem="Acg-GO-mMN" secondAttribute="centerY" id="ymi-Ll-WIV"/>
</constraints>
</view>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="SQq-IE-pvj">
<rect key="frame" x="109" y="214" width="157" height="30"/>
<state key="normal" title="make view screen shot"/>
<connections>
<action selector="makeViewScreenShotButtonTapped2:" destination="BYZ-38-t0r" eventType="touchUpInside" id="KSY-ec-uvA"/>
</connections>
</button>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="CEZ-Ju-Tpq">
<rect key="frame" x="67" y="269" width="240" height="128"/>
<constraints>
<constraint firstAttribute="width" constant="240" id="STo-iJ-rM4"/>
<constraint firstAttribute="height" constant="128" id="tfi-zF-zdn"/>
</constraints>
</imageView>
</subviews>
<color key="backgroundColor" red="0.95941069162436543" green="0.95941069162436543" blue="0.95941069162436543" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="top" secondItem="SQq-IE-pvj" secondAttribute="bottom" constant="25" id="6x1-iB-gKF"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="leading" secondItem="CEZ-Ju-Tpq" secondAttribute="leading" id="LUp-Be-FiC"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="top" secondItem="Acg-GO-mMN" secondAttribute="bottom" constant="58" id="Qu0-YT-k9O"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="Qze-zd-ajY"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="trailing" secondItem="CEZ-Ju-Tpq" secondAttribute="trailing" id="b1d-sp-GHD"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="centerX" secondItem="CEZ-Ju-Tpq" secondAttribute="centerX" id="qCL-AF-Cro"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="u5Y-eh-oSG"/>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="vkx-JQ-pOF"/>
</constraints>
</view>
<connections>
<outlet property="screenShotRenderer" destination="CEZ-Ju-Tpq" id="8QB-OE-ib6"/>
<outlet property="viewForScreenShot" destination="Acg-GO-mMN" id="jgL-yn-8kk"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="32.799999999999997" y="37.331334332833585"/>
</scene>
</scenes>
</document>
You need to use kill -9 59780
with 59780
replaced with found PID number (use lsof -wni tcp:3000
to see which process used 3000
port and get the process PID).
Or you can just modify your puma config change the tcp port tcp://127.0.0.1:3000
from 3000
to 9292
or other port that not been used.
Or you can start your rails app by using:
bundle exec puma -C config/puma.rb -b tcp://127.0.0.1:3001
Simple like a piece of CAKE!
You can define a new column type like (L
in this case) while maintaining the current alignment (c
, r
or l
):
\documentclass{article}
\usepackage{array}
\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}
\begin{document}
\begin{table}
\begin{tabular}{|c|L|L|}
\hline
Title 1 & Title 2 & Title 3 \\
\hline
one-liner & multi-line and centered & \multicolumn{1}{m{3cm}|}{multi-line piece of text to show case a multi-line and justified cell} \\
\hline
apple & orange & banana \\
\hline
apple & orange & banana \\
\hline
\end{tabular}
\end{table}
\end{document}
It can be used for a simple table, for example in an insert-only audit table, where there is no update to existing row, and no fk to other table. The insert is a simple insert, which has no or little chance of rollback.
Tried and tested approach.
public static ArrayList<String> listToArrayList(List<Object> myList) {
ArrayList<String> arl = new ArrayList<String>();
for (Object object : myList) {
arl.add((String) object);
}
return arl;
}
jQuery also doesn't allow you to call their latest file over SSL, a consideration if you want to use jQuery in a shopping cart etc.
e.g.
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
will give you a security error.
Google's API will let you call over SSL:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.7");
</script>
Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.
Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Here's a one-liner using Streams
Iterator<?> iterator = ...
List<?> list = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false)
.collect(Collectors.toList());
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:
#!/bin/bash
export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost
You might be interested in How to run the sftp command with a password from Bash script?
I just want to add that orderby is way more useful.
Why? Because I can do this:
Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)
Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.
Very easy.
I can't do that with sort. I wonder why. Do fine with orderBy.
As for speed it's always O(n).
I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.
Like this:
int Marylyn[256], Ann[1024];
The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:
#define TWO_FIFTY_SIX 256
#define TEN_TWENTY_FOUR 1024
int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];
On the following Monday afternoon I was called in and accused of having passive defiant tendencies.
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
InvalidOperationException- An InvalidOperationException has occurred. It reports a "collection was modified" in a foreach-loop
Use break statement, Once the object is removed.
ex:
ArrayList list = new ArrayList();
foreach (var item in list)
{
if(condition)
{
list.remove(item);
break;
}
}
Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...
return new System.Web.Http.Results.ResponseMessageResult(
new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
});
See nashawn's answer for JsonContent.
(For those coming to this question from a search engine), check that your stored procedures declare a custom delimiter, as this is the error that you might see when the engine can't figure out how to terminate a statement:
ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line…
If you have a database dump and see:
DROP PROCEDURE IF EXISTS prc_test;
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE', test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
SELECT @sqlstr;
PREPARE stmt FROM @sqlstr;
EXECUTE stmt;
END;
Try wrapping with a custom DELIMITER
:
DROP PROCEDURE IF EXISTS prc_test;
DELIMITER $$
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE', test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
SELECT @sqlstr;
PREPARE stmt FROM @sqlstr;
EXECUTE stmt;
END;
$$
DELIMITER ;
I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:
If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.
I had problems with viewport, specific layouts to different user agents and this is what solved my problem:
<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>
<script language="javascript" type="text/javascript">
function windowSize() {
let gist = document.querySelector('#gist92442763');
let isMobile = {
Android: function() {
return /Android/i.test(navigator.userAgent)
},
BlackBerry: function() {
return /BlackBerry/i.test(navigator.userAgent)
},
iOS: function() {
return /iPhone|iPod/i.test(navigator.userAgent)
},
Opera: function() {
return /Opera Mini/i.test(navigator.userAgent)
},
Windows: function() {
return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if(isMobile.any()) {
gist.style.width = "36%";
gist.style.WebkitOverflowScrolling = "touch"
gist.style.position = "absolute"
} else {
gist.style.width = "auto !important";
}
}
windowSize();
window.addEventListener('onresize', function() {
windowSize();
});
</script>
<style type="text/css">
.gist-data {
max-height: 300px;
}
.gist-meta {
display: none;
}
</style>
The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.
Use .lower()
- For example:
s = "Kilometer"
print(s.lower())
The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()
i++ is post increment. The increment takes place after the value is returned.
Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.
For me this works best:
class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
You can also use sprintf:
char str[1024];
sprintf(str, "somtext %s sometext %s", somevar, somevar);
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
This questions appears in quite a few SO discussions:
Different solutions are proposed, but none are optimal. Luckily, science comes to the rescue
Arbitrary N
The last 2 will be free via most university libraries / proxies.
N is finite and relatively small
In this case, one could go for a list solution. A very interesting article in the subject is freely available:
There are several color lists to consider:
I also ran into this Palette by an MIT student. Lastly, The following links may be useful in converting between different color systems / coordinates (some colors in the articles are not specified in RGB, for instance):
For Kelly's and Boynton's list, I've already made the conversion to RGB (with the exception of white and black, which should be obvious). Some C# code:
public static ReadOnlyCollection<Color> KellysMaxContrastSet
{
get { return _kellysMaxContrastSet.AsReadOnly(); }
}
private static readonly List<Color> _kellysMaxContrastSet = new List<Color>
{
UIntToColor(0xFFFFB300), //Vivid Yellow
UIntToColor(0xFF803E75), //Strong Purple
UIntToColor(0xFFFF6800), //Vivid Orange
UIntToColor(0xFFA6BDD7), //Very Light Blue
UIntToColor(0xFFC10020), //Vivid Red
UIntToColor(0xFFCEA262), //Grayish Yellow
UIntToColor(0xFF817066), //Medium Gray
//The following will not be good for people with defective color vision
UIntToColor(0xFF007D34), //Vivid Green
UIntToColor(0xFFF6768E), //Strong Purplish Pink
UIntToColor(0xFF00538A), //Strong Blue
UIntToColor(0xFFFF7A5C), //Strong Yellowish Pink
UIntToColor(0xFF53377A), //Strong Violet
UIntToColor(0xFFFF8E00), //Vivid Orange Yellow
UIntToColor(0xFFB32851), //Strong Purplish Red
UIntToColor(0xFFF4C800), //Vivid Greenish Yellow
UIntToColor(0xFF7F180D), //Strong Reddish Brown
UIntToColor(0xFF93AA00), //Vivid Yellowish Green
UIntToColor(0xFF593315), //Deep Yellowish Brown
UIntToColor(0xFFF13A13), //Vivid Reddish Orange
UIntToColor(0xFF232C16), //Dark Olive Green
};
public static ReadOnlyCollection<Color> BoyntonOptimized
{
get { return _boyntonOptimized.AsReadOnly(); }
}
private static readonly List<Color> _boyntonOptimized = new List<Color>
{
Color.FromArgb(0, 0, 255), //Blue
Color.FromArgb(255, 0, 0), //Red
Color.FromArgb(0, 255, 0), //Green
Color.FromArgb(255, 255, 0), //Yellow
Color.FromArgb(255, 0, 255), //Magenta
Color.FromArgb(255, 128, 128), //Pink
Color.FromArgb(128, 128, 128), //Gray
Color.FromArgb(128, 0, 0), //Brown
Color.FromArgb(255, 128, 0), //Orange
};
static public Color UIntToColor(uint color)
{
var a = (byte)(color >> 24);
var r = (byte)(color >> 16);
var g = (byte)(color >> 8);
var b = (byte)(color >> 0);
return Color.FromArgb(a, r, g, b);
}
And here are the RGB values in hex and 8-bit-per-channel representations:
kelly_colors_hex = [
0xFFB300, # Vivid Yellow
0x803E75, # Strong Purple
0xFF6800, # Vivid Orange
0xA6BDD7, # Very Light Blue
0xC10020, # Vivid Red
0xCEA262, # Grayish Yellow
0x817066, # Medium Gray
# The following don't work well for people with defective color vision
0x007D34, # Vivid Green
0xF6768E, # Strong Purplish Pink
0x00538A, # Strong Blue
0xFF7A5C, # Strong Yellowish Pink
0x53377A, # Strong Violet
0xFF8E00, # Vivid Orange Yellow
0xB32851, # Strong Purplish Red
0xF4C800, # Vivid Greenish Yellow
0x7F180D, # Strong Reddish Brown
0x93AA00, # Vivid Yellowish Green
0x593315, # Deep Yellowish Brown
0xF13A13, # Vivid Reddish Orange
0x232C16, # Dark Olive Green
]
kelly_colors = dict(vivid_yellow=(255, 179, 0),
strong_purple=(128, 62, 117),
vivid_orange=(255, 104, 0),
very_light_blue=(166, 189, 215),
vivid_red=(193, 0, 32),
grayish_yellow=(206, 162, 98),
medium_gray=(129, 112, 102),
# these aren't good for people with defective color vision:
vivid_green=(0, 125, 52),
strong_purplish_pink=(246, 118, 142),
strong_blue=(0, 83, 138),
strong_yellowish_pink=(255, 122, 92),
strong_violet=(83, 55, 122),
vivid_orange_yellow=(255, 142, 0),
strong_purplish_red=(179, 40, 81),
vivid_greenish_yellow=(244, 200, 0),
strong_reddish_brown=(127, 24, 13),
vivid_yellowish_green=(147, 170, 0),
deep_yellowish_brown=(89, 51, 21),
vivid_reddish_orange=(241, 58, 19),
dark_olive_green=(35, 44, 22))
For all you Java developers, here are the JavaFX colors:
// Don't forget to import javafx.scene.paint.Color;
private static final Color[] KELLY_COLORS = {
Color.web("0xFFB300"), // Vivid Yellow
Color.web("0x803E75"), // Strong Purple
Color.web("0xFF6800"), // Vivid Orange
Color.web("0xA6BDD7"), // Very Light Blue
Color.web("0xC10020"), // Vivid Red
Color.web("0xCEA262"), // Grayish Yellow
Color.web("0x817066"), // Medium Gray
Color.web("0x007D34"), // Vivid Green
Color.web("0xF6768E"), // Strong Purplish Pink
Color.web("0x00538A"), // Strong Blue
Color.web("0xFF7A5C"), // Strong Yellowish Pink
Color.web("0x53377A"), // Strong Violet
Color.web("0xFF8E00"), // Vivid Orange Yellow
Color.web("0xB32851"), // Strong Purplish Red
Color.web("0xF4C800"), // Vivid Greenish Yellow
Color.web("0x7F180D"), // Strong Reddish Brown
Color.web("0x93AA00"), // Vivid Yellowish Green
Color.web("0x593315"), // Deep Yellowish Brown
Color.web("0xF13A13"), // Vivid Reddish Orange
Color.web("0x232C16"), // Dark Olive Green
};
the following is the unsorted kelly colors according to the order above.
the following is the sorted kelly colors according to hues (note that some yellows are not very contrasting)
As you know the display
property cannot be animated BUT just by having it in your CSS it overrides the visibility
and opacity
transitions.
The solution...just removed the display
properties.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a>_x000D_
</li>_x000D_
<li><a href="">Dolor</a>_x000D_
</li>_x000D_
<li><a href="">Sit</a>_x000D_
</li>_x000D_
<li><a href="">Amet</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.
It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".
Swift 2
Using Trailing Closures this becomes:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.
In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t)
since dispatch_block_t
is type alias for () -> Void
- A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async
.
The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.
{{ Request::segment(1) }}
Having javascript:
in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).
A better practice would be the second way, to put your javascript into the onclick
attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.
If you're happy not not supporting IE or pre-Chromium Edge (which might be fine if you are using this for progressive enhancement), you can use :placeholder-shown
as Berend has said. Note that for Chrome and Safari you actually need a non-empty placeholder for this to work, though a space works.
*,_x000D_
::after,_x000D_
::before {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
label.floating-label {_x000D_
display: block;_x000D_
position: relative;_x000D_
height: 2.2em;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input {_x000D_
font-size: 1em;_x000D_
height: 2.2em;_x000D_
padding-top: 0.7em;_x000D_
line-height: 1.5;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: 0.25rem;_x000D_
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:focus {_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
border-color: #80bdff;_x000D_
outline: 0;_x000D_
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);_x000D_
}_x000D_
_x000D_
label.floating-label input+span {_x000D_
position: absolute;_x000D_
top: 0em;_x000D_
left: 0;_x000D_
display: block;_x000D_
width: 100%;_x000D_
font-size: 0.66em;_x000D_
line-height: 1.5;_x000D_
color: #495057;_x000D_
border: 1px solid transparent;_x000D_
border-radius: 0.25rem;_x000D_
transition: font-size 0.1s ease-in-out, top 0.1s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown {_x000D_
padding-top: 0;_x000D_
font-size: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown+span {_x000D_
top: 0.3em;_x000D_
font-size: 1em;_x000D_
}
_x000D_
<fieldset>_x000D_
<legend>_x000D_
Floating labels example (no-JS)_x000D_
</legend>_x000D_
<label class="floating-label">_x000D_
<input type="text" placeholder=" ">_x000D_
<span>Username</span>_x000D_
</label>_x000D_
<label class="floating-label">_x000D_
<input type="Password" placeholder=" ">_x000D_
<span>Password</span>_x000D_
</label>_x000D_
</fieldset>_x000D_
<p>_x000D_
Inspired by Bootstrap's <a href="https://getbootstrap.com/docs/4.0/examples/floating-labels/">floating labels</a>._x000D_
</p>
_x000D_
I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:
/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle
If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.
Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version
Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.
output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`
if(output == null){// if you fetched null value then initialize output with blank string
output= "";
}
UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);
Like for example, if I want to replace all occurrences of John by Mark I will use below,
UPDATE student SET student_name = replace(student_name, 'John', 'Mark');
I can't really comment on specific libraries, but in principle there's little reason for such operations to be slower in Java. Hotspot generally does the kinds of things you'd expect a compiler to do: it compiles basic math operations on Java variables to corresponding machine instructions (it uses SSE instructions, but only one per operation); accesses to elements of an array are compiled to use "raw" MOV instructions as you'd expect; it makes decisions on how to allocate variables to registers when it can; it re-orders instructions to take advantage of processor architecture... A possible exception is that as I mentioned, Hotspot will only perform one operation per SSE instruction; in principle you could have a fantastically optimised matrix library that performed multiple operations per instruction, although I don't know if, say, your particular FORTRAN library does so or if such a library even exists. If it does, there's currently no way for Java (or at least, Hotspot) to compete with that (though you could of course write your own native library with those optimisations to call from Java).
So what does all this mean? Well:
A hindrance to matrix operations is often data locality issues that arise when you need to traverse both row by row and column by column, e.g. in matrix multiplication, since you have to store the data in an order that optimises one or the other. But if you hand-write the code, you can sometimes combine operations to optimise data locality (e.g. if you're multiplying a matrix by its transformation, you can turn a column traversal into a row traversal if you write a dedicated function instead of combining two library functions). As usual in life, a library will give you non-optimal performance in exchange for faster development; you need to decide just how important performance is to you.
I needed to clear focus from all fields programmatically. I just added the following two statements to my main layout definition.
myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);
That's it. Fixed my problem instantly. Thanks, Silver, for pointing me in the right direction.
here is more detailed information -> [1]: https://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
Thank you all for your help.
This is what I have used in the end:
SELECT *,
CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%'
THEN 'Valid'
ELSE 'No valid'
END [Validate]
FROM
*table*
ORDER BY [Validate]
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
If the problem domain has some kind of string header concept, this could be modelled as an enum.
switch(GetStringHeader(s))
{
case StringHeader.ABC: ...
case StringHeader.QWERTY: ...
...
}
StringHeader GetStringHeader(string s)
{
if (s.StartsWith("ABC")) return StringHeader.ABC;
...
}
enum StringHeader { ABC, QWERTY, ... }
All of the information you are looking for can be found here and here (thanks Reed Copsey):
From the first link:
Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
...
The access level for class members and struct members, including nested classes and structs, is private by default.
...
interfaces default to internal access.
...
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
From the second link:
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.
And for nested types:
Members of Default member accessibility ---------- ---------------------------- enum public class private interface public struct private
The installation procedure creates a user account called postgres
that is associated with the default Postgres role. In order to use Postgres, you can log into that account. But if not explicitly specified the rails app looks for a different role, more particularly the role having your unix username which might not be created in the postgres roles.
To overcome that, you can create a new role, first by switching over to the default role postgres which was created during installation
sudo -i -u postgres
After you are logged in to the postgres account, you can create a new user by the command:
createuser --interactive
This will prompt you with some choices and, based on your responses, execute the correct Postgres commands to create a user.
Pass over a role name and some permissions and the role is created, you can then migrate your db
It depends upon the context. Some possible contexts in HTML:
See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.
While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess
module. For simple commands its equivalent, but it offers more options if you want to do something complicated.
Example for your case:
import subprocess
subprocess.Popen(["rm","-r","some.file"])
This will run rm -r some.file
in the background. Note that calling .communicate()
on the object returned from Popen
will block until it completes, so don't do that if you want it to run in the background:
import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate() # Will block for 30 seconds
See the documentation here.
Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.
use box-shadow
with no horizontal offset.
http://www.css3.info/preview/box-shadow/
eg.
div {_x000D_
-webkit-box-shadow: 0 10px 5px #888888;_x000D_
-moz-box-shadow: 0 10px 5px #888888;_x000D_
box-shadow: 0 10px 5px #888888;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
There will be a slight shadow on the sides with a large blur radius (5px in above example)
If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :
I think this is the more simpler approach:
Switching to SQL mode... Commands end with ;
Go forth and do great things! :)
Add the following dependency in your pom.xml file and if you are using IntelliJ then add the same jars to WEB-INF->lib folder.... path is Project Structure -> Atrifacts -> Select jar from Available Elements pane and double click. It will add to respective folder
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .
When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'
You could do the following
Remove @Component from your Service and depend on mapping via XML - Easiest
Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.
Use @Resource instead of @Autowired to pick the bean by its name .
@Resource(name="suggestionService")
private SuggestionService service;
or
@Resource(name="SuggestionService")
private SuggestionService service;
both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.
If none of the answers helps, you might need to adjust the project properties. Check this other StackOverflow answer on how to do that:
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.