There is a hook that's fairly common called useIsMounted
that solves this problem (for functional components)...
import { useRef, useEffect } from 'react';
export function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
return isMounted;
}
then in your functional component
function Book() {
const isMounted = useIsMounted();
...
useEffect(() => {
asyncOperation().then(data => {
if (isMounted.current) { setState(data); }
})
});
...
}
This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.
export interface ISearchResult {
title: string;
listTitle:string;
entityName?: string,
lookupName?:string,
lookupId?:string
}
That data:image/png;base64
URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.
Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
One way would be to inherit a new class,EntryWithSet
, and defining set
method that makes use of delete
and insert
methods of the Entry
class objects:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
class EntryWithSet(tk.Entry):
"""
A subclass to Entry that has a set method for setting its text to
a given string, much like a Variable class.
"""
def __init__(self, master, *args, **kwargs):
tk.Entry.__init__(self, master, *args, **kwargs)
def set(self, text_string):
"""
Sets the object's text to text_string.
"""
self.delete('0', 'end')
self.insert('0', text_string)
def on_button_click():
import random, string
rand_str = ''.join(random.choice(string.ascii_letters) for _ in range(19))
entry.set(rand_str)
if __name__ == '__main__':
root = tk.Tk()
entry = EntryWithSet(root)
entry.pack()
tk.Button(root, text="Set", command=on_button_click).pack()
tk.mainloop()
We can prevent a thread from execution by using any of the 3 methods of Thread class:
yield()
method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
join()
If any executing thread t1 calls join()
on t2 (i.e. t2.join()
) immediately t1 will enter into waiting state until t2 completes its execution.
sleep()
Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).
No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass)
constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.
The code you posted using as
will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass
will evaluate to null
, since it's not an instance of DerivedClass
.
Using .net
[int]$b = $null #used after as refence
$b
0
[int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable
True
$b
10
$b.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
note this (powershell coercing feature)
$a = "10"
$a + 1 #second value is evaluated as [string]
101
11 + $a # second value is evaluated as [int]
21
Quoting the iPhone OS Technology Overview:
iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:
- H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- Numerous audio formats, including the ones listed in “Audio Technologies”
For information about the classes of the Media Player framework, see Media Player Framework Reference.
Another option is using the overloaded + operator
:
>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
If you don't want to use OutlineButton
and want to stick to normal RaisedButton
, you can wrap your button in ClipRRect
or ClipOval
like:
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
child: Text("Button"),
onPressed: () {},
),
),
I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.
Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY
You should not rely on a hash code being equal to a specific value. Just that it will return consistent results within the same execution. The API docs say the following :
The general contract of hashCode is:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
EDIT Since the javadoc for String.hashCode() specifies how a String's hash code is computed, any violation of this would violate the public API specification.
Instead of calling the substring
function you could use .slice()
imageIndex = parseInt(id.slice(-1)) - 1;
Here, -1 in slice indicates that to start slice from the last index.
Thanks.
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
You do not have to move the mouse to get the cursor's location. The location is also reported on events other than mousemove. Here's a click-event as an example:
document.body.addEventListener('click',function(e)
{
console.log("cursor-location: " + e.clientX + ',' + e.clientY);
});
The source code for clear()
:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
The source code for removeAll()
(As defined in AbstractCollection
):
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> e = iterator();
while (e.hasNext()) {
if (c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}
clear()
is much faster since it doesn't have to deal with all those extra method calls.
And as Atrey points out, c.contains(..)
increases the time complexity of removeAll
to O(n2) as opposed to clear
's O(n).
The hamcrest-core-1.3.jar available on maven repository is deprecated.
Download working hamcrest-core-1.3.jar
from official Junit4 github link .
If you want to download from maven repository, use latest hamcrest-XX.jar
.
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note
then #textid
you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Arrays.sort(yourarray, new Comparator() {
public int compare(Object o1, Object o2) {
String[] elt1 = (String[])o1;
String[] elt2 = (String[])o2;
return elt1[0].compareTo(elt2[0]);
}
});
You can define sScrollX : "100%"
to force dataTables to keep the column widths :
..
sScrollX: "100%", //<-- here
aoColumns : [
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
],
...
you can play with this fiddle -> http://jsfiddle.net/vuAEx/
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.
Below the more general templated solution to which Ian referred...
#include <map>
template<typename Key, typename Value>
using Map = std::map<Key, Value>;
template<typename Key, typename Value>
using MapIterator = typename Map<Key, Value>::iterator;
template<typename Key, typename Value>
class MapKeyIterator : public MapIterator<Key, Value> {
public:
MapKeyIterator ( ) : MapIterator<Key, Value> ( ) { };
MapKeyIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Key *operator -> ( ) { return ( Key * const ) &( MapIterator<Key, Value>::operator -> ( )->first ); }
Key operator * ( ) { return MapIterator<Key, Value>::operator * ( ).first; }
};
template<typename Key, typename Value>
class MapValueIterator : public MapIterator<Key, Value> {
public:
MapValueIterator ( ) : MapIterator<Key, Value> ( ) { };
MapValueIterator ( MapIterator<Key, Value> it_ ) : MapIterator<Key, Value> ( it_ ) { };
Value *operator -> ( ) { return ( Value * const ) &( MapIterator<Key, Value>::operator -> ( )->second ); }
Value operator * ( ) { return MapIterator<Key, Value>::operator * ( ).second; }
};
All credits go to Ian... Thanks Ian.
In case of a very large stream length there is the hazard of memory leak due to Large Object Heap. i.e. The byte buffer created by stream.ToArray creates a copy of memory stream in Heap memory leading to duplication of reserved memory. I would suggest to use a StreamReader
, a TextWriter
and read the stream in chunks of char
buffers.
In netstandard2.0 System.IO.StreamReader
has a method ReadBlock
you can use this method in order to read the instance of a Stream (a MemoryStream instance as well since Stream is the super of MemoryStream):
private static string ReadStreamInChunks(Stream stream, int chunkLength)
{
stream.Seek(0, SeekOrigin.Begin);
string result;
using(var textWriter = new StringWriter())
using (var reader = new StreamReader(stream))
{
var readChunk = new char[chunkLength];
int readChunkLength;
//do while: is useful for the last iteration in case readChunkLength < chunkLength
do
{
readChunkLength = reader.ReadBlock(readChunk, 0, chunkLength);
textWriter.Write(readChunk,0,readChunkLength);
} while (readChunkLength > 0);
result = textWriter.ToString();
}
return result;
}
NB. The hazard of memory leak is not fully eradicated, due to the usage of MemoryStream, that can lead to memory leak for large memory stream instance (memoryStreamInstance.Size >85000 bytes). You can use Recyclable Memory stream, in order to avoid LOH. This is the relevant library
This is how I did it, I hope it brings a new perspective how this works on Swift.
In this example below I will get the any string between []
var sample = "this is an [hello] amazing [world]"
var regex = NSRegularExpression(pattern: "\\[.+?\\]"
, options: NSRegularExpressionOptions.CaseInsensitive
, error: nil)
var matches = regex?.matchesInString(sample, options: nil
, range: NSMakeRange(0, countElements(sample))) as Array<NSTextCheckingResult>
for match in matches {
let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
println("found= \(r)")
}
Ahem, because 22 is the port number for ssh and has been for ages?
Here is an answer using object-scan.
When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.
Here is how you could interact with a single field
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, needle) => objectScan([needle], {
abort: true,
rtn: 'value'
})(haystack);
const set = (haystack, needle, value) => objectScan([needle], {
abort: true,
rtn: 'bool',
filterFn: ({ parent, property }) => {
parent[property] = value;
return true;
}
})(haystack);
console.log(get(data, 'items[1].name'));
// => bar
console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
and here is how you could interact with multiple fields at the same time
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, ...needles) => objectScan(needles, {
joined: true,
rtn: 'entry'
})(haystack);
const set = (haystack, actions) => objectScan(Object.keys(actions), {
rtn: 'count',
filterFn: ({ matchedBy, parent, property }) => {
matchedBy.forEach((m) => {
parent[property] = actions[m];
})
return true;
}
})(haystack);
console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]
console.log(set(data, {
'items[0].name': 'foo1',
'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)
// const objectScan = require('object-scan');
const myData = { code: 42, items: [{ id: 1, name: 'aaa', items: [{ id: 3, name: 'ccc' }, { id: 4, name: 'ddd' }] }, { id: 2, name: 'bbb', items: [{ id: 5, name: 'eee' }, { id: 6, name: 'fff' }] }] };
const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
abort: true,
useArraySelector: false,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(haystack);
console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
You can use Iterator<String>
to iterate the elements of the ArrayList<String>
:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Now you can retrive elements from String[]
using any Loop.
I'd just use an if statement. In this case:
Type nodeType = node.GetType();
if (nodeType == typeof(CasusNodeDTO))
{
}
else ...
The other way to do this is:
if (node is CasusNodeDTO)
{
}
else ...
The first example is true for exact types only, where the latter checks for inheritance too.
You can need to pass in the string 'int64'
:
>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]}) # some test dataframe
>>> df['a'].astype('int64')
0 1
1 2
Name: a, dtype: int64
There are some alternative ways to specify 64-bit integers:
>>> df['a'].astype('i8') # integer with 8 bytes (64 bit)
0 1
1 2
Name: a, dtype: int64
>>> import numpy as np
>>> df['a'].astype(np.int64) # native numpy 64 bit integer
0 1
1 2
Name: a, dtype: int64
Or use np.int64
directly on your column (but it returns a numpy.array
):
>>> np.int64(df['a'])
array([1, 2], dtype=int64)
I stumbled across this question to my self and I feel that a forked stream has some use cases that could prove valid. I wrote the code below as a consumer so that it does not do anything but you could apply it to functions and anything else you might come across.
class PredicateSplitterConsumer<T> implements Consumer<T>
{
private Predicate<T> predicate;
private Consumer<T> positiveConsumer;
private Consumer<T> negativeConsumer;
public PredicateSplitterConsumer(Predicate<T> predicate, Consumer<T> positive, Consumer<T> negative)
{
this.predicate = predicate;
this.positiveConsumer = positive;
this.negativeConsumer = negative;
}
@Override
public void accept(T t)
{
if (predicate.test(t))
{
positiveConsumer.accept(t);
}
else
{
negativeConsumer.accept(t);
}
}
}
Now your code implementation could be something like this:
personsArray.forEach(
new PredicateSplitterConsumer<>(
person -> person.getDateOfBirth().isPresent(),
person -> System.out.println(person.getName()),
person -> System.out.println(person.getName() + " does not have Date of birth")));
As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.
I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:
unzip zip_name.zip && chmod +x script_name.sh
If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh
as follows:
#!/bin/bash
# file: grant_perms.sh
chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh
(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)
And now your unzip one-liner becomes:
unzip zip_name.zip && source grant_perms.sh
Note that since you are using source
to run grant_perms.sh
, it doesn't need execute permission
To access "Host Manager" you have to configure "admin-gui" user inside the tomcat-users.xml
Just add the below lines[change username & pwd] :
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="admin-gui"/>
Restart tomcat 7 server and you are done.
You can also use class TextParser(HTMLParser, object):
. This makes TextParser
a new-style class, and super()
can be used.
First you need an object
public class MyObject {
public string Id {get;set;}
public string Text {get;set;}
...
}
Then in here
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.
JavaScriptSerializer System.Web.Script.Serialization
My handler class for request multiple permissions. You can check the full using here
public class RequestPermissionHandler {
private Activity mActivity;
private RequestPermissionListener mRequestPermissionListener;
private int mRequestCode;
public void requestPermission(Activity activity, @NonNull String[] permissions, int requestCode,
RequestPermissionListener listener) {
mActivity = activity;
mRequestCode = requestCode;
mRequestPermissionListener = listener;
if (!needRequestRuntimePermissions()) {
mRequestPermissionListener.onSuccess();
return;
}
requestUnGrantedPermissions(permissions, requestCode);
}
private boolean needRequestRuntimePermissions() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
private void requestUnGrantedPermissions(String[] permissions, int requestCode) {
String[] unGrantedPermissions = findUnGrantedPermissions(permissions);
if (unGrantedPermissions.length == 0) {
mRequestPermissionListener.onSuccess();
return;
}
ActivityCompat.requestPermissions(mActivity, unGrantedPermissions, requestCode);
}
private boolean isPermissionGranted(String permission) {
return ActivityCompat.checkSelfPermission(mActivity, permission)
== PackageManager.PERMISSION_GRANTED;
}
private String[] findUnGrantedPermissions(String[] permissions) {
List<String> unGrantedPermissionList = new ArrayList<>();
for (String permission : permissions) {
if (!isPermissionGranted(permission)) {
unGrantedPermissionList.add(permission);
}
}
return unGrantedPermissionList.toArray(new String[0]);
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == mRequestCode) {
if (grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
mRequestPermissionListener.onFailed();
return;
}
}
mRequestPermissionListener.onSuccess();
} else {
mRequestPermissionListener.onFailed();
}
}
}
public interface RequestPermissionListener {
void onSuccess();
void onFailed();
}
}
It's called String#start_with?
, not String#startswith
: In Ruby, the names of boolean-ish methods end with ?
and the words in method names are separated with an _
. Not sure where the s
went, personally, I'd prefer String#starts_with?
over the actual String#start_with?
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
You mean that want to get status codes?
VolleyError
has a member variable type of NetworkResponse
and it is public.
You can access error.networkResponse.statusCode
for http error code.
I hope it is helpful for you.
In your form tag, rather than
name="booking.php"
use
action="booking.php"
And then, in booking.php use
$checkValue = $_POST['booking-check'];
Also, you'll need a submit button in there
<input type='submit'>
You wrote:
var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);
Why not this?
var styleNode = document.createElement("style");
document.head.appendChild(styleNode);
Henceforward you can append CSS rules easily to the HTML code:
styleNode.innerHTML = "h1 { background: red; }\n";
styleNode.innerHTML += "h2 { background: green; }\n";
...or directly to the DOM:
styleNode.sheet.insertRule("h1 { background: red; }");
styleNode.sheet.insertRule("h2 { background: green; }");
I expect this to work everywhere except archaic browsers.
Definitely works in Chrome in year 2019.
The following would work:
myarray: [
String1, String2, String3,
String4, String5, String5, String7
]
I tested it using the snakeyaml implementation, I am not sure about other implementations though.
You want to use BigInteger.toByteArray()
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
And you want the reverse:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
Note that you probably want to use overloads of String.getBytes()
and String(byte[])
that specifies an explicit encoding, otherwise you may run into encoding issues.
And what about trying not to delete but hide that row?
I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:
sudo vi /etc/apt/sources.list
and added the following lines:
deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main
If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:
sudo apt-get update
sudo apt-get install build-essential
Hopefully this will help someone who had the same problem that I did.
I am currently using Android Studio 1.4.
For importing and adding libraries, I used the following flow ->
1. Press **Alt+Ctr+Shift+S** or Go to **File --> Project** Structure to open up the Project Structure Dialog Box.
2. Click on **Modules** to which you want to link the JAR to and Go to the Dependency Tab.
3. Click on "**+**" Button to pop up Choose Library Dependency.
4. Search/Select the dependency and rebuild the project.
I used the above approach to import support v4 and v13 libraries.
I hope this is helpful and clears up the flow.
In C++ you are supposed to declare functions before you can use them. In your code integrate
is not declared before the point of the first call to integrate
. The same applies to sum
. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.
Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable
, getSkewNormal
, integrate
etc. have no business being in header file.
Also SkewNormalEvalutatable e();
declaration in C++ declares a function e
, not an object e
as you seem to assume. The simple SkewNormalEvalutatable e;
will declare an object initialized by default constructor.
Also, you receive the last parameter of integrate
(and of sum
) by value as an object of Evaluatable
type. That means that attempting to pass SkewNormalEvalutatable
as last argument of integrate
will result in SkewNormalEvalutatable
getting sliced to Evaluatable
. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.
You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See Create a dictionary with list comprehension in Python
d = {k : v for k in blah blah blah}
If you run SHOW VARIABLES
from a mysql console you can look for basedir.
When I run the following:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';
on my system I get /usr/local/mysql
as the Value returned.
(I am not using MAMP - I installed MySQL with homebrew.
mysqld
on my machine is in /usr/local/mysql/bin
so the basedir is where most everything will be installed to.
Also util:
mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir';
To find where the DBs are stored.
For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html
and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
In a Firebird database the AFTER myOtherColumn
does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.
If you want to assign a long str to variable, you can do it as below:
net_weights_pathname = (
'/home/acgtyrant/BigDatas/'
'model_configs/lenet_iter_10000.caffemodel')
Do not add any comma, or you will get a tuple which contains many strs!
open looks in the current working directory, which in your case is ~
, since you are calling your script from the ~
directory.
You can fix the problem by either
cd
ing to the directory containing data.csv
before executing the script, or
by using the full path to data.csv
in your script, or
open
and os.listdir
) may be affected by this.I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.
To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:
Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.
In your snippet, button
is an instance of NodeList
, to which you can't attach an event listener directly, nor can you change the elements' className
properties directly.
Your best bet is to delegate the event:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
}
},false);
Of course, my guess is that the active
class needs to be removed once the mouseout
event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active
class:
document.body.addEventListener('mouseover',function(e)
{
e = e || window.event;
var oldSrc, target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
{
target.className += ' active';//set class
oldSrc = target.getAttribute('src');
target.setAttribute('src', 'images/arrows/top_o.png');
target.onmouseout = function()
{
target.onmouseout = null;//remove this event handler, we don't need it anymore
target.className = target.className.replace(/\bactive\b/,'').trim();
target.setAttribute('src', oldSrc);
};
}
},false);
There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).
2.3.5 did not have input tap
, just input keyevent
and input text
You can use the monkeyrunner for it: (this is a copy of the answer at https://stackoverflow.com/a/18959385/1587329):
You might want to use monkeyrunner like this:
$ monkeyrunner
>>> from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
>>> device = MonkeyRunner.waitForConnection()
>>> device.touch(200, 400, MonkeyDevice.DOWN_AND_UP)
You can also do a drag, start activies etc. Have a look at the api for MonkeyDevice.
It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.
The script package does exactly what you're looking for: https://atom.io/packages/script
The package's documentation also contains the key mappings, which you can easily customize.
You can use VLOOKUP, but this requires a wrapper function to return True
or False
. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.
Fill down this formula in column K next to the existing values in column I (from I1
to I2691
):
=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0
You can also use MATCH:
=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))
I have used the statement below on debian 10
apt-get install iputils-ping
Fist of all make sure your SQL server is running. Actually I'm working on windows and I have installed a nice tool which is called MySQL workbench (you can find it here for almost any platform ).
Thus I just create a new database to test the connection, let's call it stackoverflow, with one table called user.
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP SCHEMA IF EXISTS `stackoverflow` ;
CREATE SCHEMA IF NOT EXISTS `stackoverflow` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `stackoverflow` ;
-- -----------------------------------------------------
-- Table `stackoverflow`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `stackoverflow`.`user` ;
CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
`iduser` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(75) NOT NULL,
`email` VARCHAR(150) NOT NULL,
PRIMARY KEY (`iduser`),
UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
You can reduce important part to
CREATE SCHEMA IF NOT EXISTS `stackoverflow`
CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
`iduser` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(75) NOT NULL,
`email` VARCHAR(150) NOT NULL,
PRIMARY KEY (`iduser`),
UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
So now I have my brand new stackoverflow database. Let's connect to it throught Netbeans. Launch netbeans and go to the services panel
Now right click on databases: new connection.. Choose MySql connector, they already come packed with netbeans.
Then fill in the gaps the data you need. As shown in the picture add the database name and remove from the connection url the optional parameters as l?zeroDateTimeBehaviour=convertToNull
. Use the right user name and password and test the connection.
As you can see connection is successful.
Click FINISH.
You will have your connection successfully working and available under the services.
I was experiencing this same symptom - 404 on woff files in Chrome - and was running an application on a Windows Server with IIS 6.
If you are in the same situation you can fix it by doing the following:
"Simply add the following MIME type declarations via IIS Manager (HTTP Headers tab of website properties): .woff application/x-woff"
Update: according to MIME Types for woff fonts and Grsmto the actual MIME type is application/x-font-woff (for Chrome at least). x-woff will fix Chrome 404s, x-font-woff will fix Chrome warnings.
As of 2017: Woff fonts have now been standardised as part of the RFC8081 specification to the mime type font/woff
and font/woff2
.
Thanks to Seb Duggan: http://sebduggan.com/posts/serving-web-fonts-from-iis
You can also add the MIME types in the web config:
<system.webServer>
<staticContent>
<remove fileExtension=".woff" /> <!-- In case IIS already has this mime type -->
<mimeMap fileExtension=".woff" mimeType="font/woff" />
</staticContent>
</system.webServer>
the name attribute is used for posting to e.g. a webserver. The id is primarily used for css (and javascript). Suppose you have this setup:
<input id="message_id" name="message_name" type="text" />
in order to get the value with PHP when posting your form, it will use the name-attribute, like this:
$_POST["message_name"];
The id is used for styling, as said before, for when you want to use specific css.
#message_id
{
background-color: #cccccc;
}
Of course, you can use the same denomination for your id and name-attribute. These two will not interfere with each other.
also, name can be used for more items, like when you are using radiobuttons. Name is then used to group your radiobuttons, so you can only select one of those options.
<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />
And in this very specific case, I can further say how id is used, because you will probably want a label with your radiobutton. Label has a for-attribute, which uses the id of your input to link this label to your input (when you click the label, the button is checked). Example can be found below
<input id="button_1" type="radio" name="option" /><label for="button_1">Text for button 1</label>
<input id="button_2" type="radio" name="option" /><label for="button_2">Text for button 2</label>
Use java.util.Calendar
if you have extensive date related processing.
Date has before()
, after()
methods. you could use them as well.
Yet another usage of th:class, same as @NewbLeech and @Charles have posted, but simplified to maximum if there is no "else" case:
<input th:class="${#fields.hasErrors('password')} ? formFieldHasError" />
Does not include class attribute if #fields.hasErrors('password') is false.
Surprisingly no one told about this, which provides some !clarity:
style={{
backgroundColor: 'white',
opacity: 0.7
}}
You don't cast the result of malloc
, because doing so adds pointless clutter to your code.
The most common reason why people cast the result of malloc
is because they are unsure about how the C language works. That's a warning sign: if you don't know how a particular language mechanism works, then don't take a guess. Look it up or ask on Stack Overflow.
Some comments:
A void pointer can be converted to/from any other pointer type without an explicit cast (C11 6.3.2.3 and 6.5.16.1).
C++ will however not allow an implicit cast between void*
and another pointer type. So in C++, the cast would have been correct. But if you program in C++, you should use new
and not malloc()
. And you should never compile C code using a C++ compiler.
If you need to support both C and C++ with the same source code, use compiler switches to mark the differences. Do not attempt to sate both language standards with the same code, because they are not compatible.
If a C compiler cannot find a function because you forgot to include the header, you will get a compiler/linker error about that. So if you forgot to include <stdlib.h>
that's no biggie, you won't be able to build your program.
On ancient compilers that follow a version of the standard which is more than 25 years old, forgetting to include <stdlib.h>
would result in dangerous behavior. Because in that ancient standard, functions without a visible prototype implicitly converted the return type to int
. Casting the result from malloc
explicitly would then hide away this bug.
But that is really a non-issue. You aren't using a 25 years old computer, so why would you use a 25 years old compiler?
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.
$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0
git-status
on the parent repository will now report a dirty tree:
# On branch dev [...]
#
# modified: submodule (new commits)
Add the submodule directory and commit to store the new pointer.
You need to write() the read() data into the new file:
ssize_t nrd;
int fd;
int fd1;
fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
Update: added the proper opens...
Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.
Swift4:
let key = "ccC2H19lDDbQDfakxcrtNMQdd0FloLGG" // length == 32
let iv = "ggGGHUiDD0Qjhuvv" // length == 16
func encryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let encodedData = try data.aesEncrypt(key: key, iv: iv)
try encodedData.write(to: path)
return true
}catch{
return false
}
}
func decryptFile(_ path: URL) -> Bool{
do{
let data = try Data.init(contentsOf: path)
let decodedData = try data.aesDecrypt(key: key, iv: iv)
try decodedData.write(to: path)
return true
}catch{
return false
}
}
Install CryptoSwift
import CryptoSwift
extension Data {
func aesEncrypt(key: String, iv: String) throws -> Data{
let encypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(self.bytes)
return Data(bytes: encypted)
}
func aesDecrypt(key: String, iv: String) throws -> Data {
let decrypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(self.bytes)
return Data(bytes: decrypted)
}
}
If you don't mind the boolean being converted to a number (that is either 0 or 1), you can use the Bitwise XOR Assignment Operator. Like so:
bool ^= true; //- toggle value.
This is especially good if you use long, descriptive boolean names, EG:
var inDynamicEditMode = true; // Value is: true (boolean)
inDynamicEditMode ^= true; // Value is: 0 (number)
inDynamicEditMode ^= true; // Value is: 1 (number)
inDynamicEditMode ^= true; // Value is: 0 (number)
This is easier for me to scan than repeating the variable in each line.
This method works in all (major) browsers (and most programming languages).
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
You can try doing
<p>
<a href="MY WEBSITE LINK" target="_blank">
<img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
</a>
</p>
This should scale your image if in a fluid layout.
For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media
queries in CSS to change the width of the image.
Note that changing the height of the image will mess with the ratio.
Not sure if this answers the question, but this is what I needed.
Maps.iterate.sorted = function (o, callback) {
var keys = Object.keys(o), sorted = keys.sort(), k;
if ( callback ) {
var i = -1;
while( ++i < sorted.length ) {
callback(k = sorted[i], o[k] );
}
}
return sorted;
}
Called as :
Maps.iterate.sorted({c:1, b:2, a:100}, function(k, v) { ... } )
Pandas will recognise a value as null if it is a np.nan
object, which will print as NaN
in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan
objects using replace()
, and then call dropna()
on your DataFrame to delete rows with null tenants.
To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants
column:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
Now we replace any empty strings in the Tenants
column with np.nan
objects, like so:
>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
Now we can drop the null values:
>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
I was able to use
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
I don't know if it's because I am using PHP 5.5 it works great :)
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}
Could it be that your file is not ISO-8859-15 encoded? You should be able to check with the file command:
file YourFile.txt
Also, you can use iconv without providing the encoding of the original file:
iconv -t UTF-8 YourFile.txt
You can use literal quoting:
stmt := q'[insert into MY_TBL (Col) values('ER0002')]';
Documentation for literals can be found here.
Alternatively, you can use two quotes to denote a single quote:
stmt := 'insert into MY_TBL (Col) values(''ER0002'')';
The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
If you added JComponent
to already visible Container, then you have call
frame.getContentPane().validate();
frame.getContentPane().repaint();
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(460, 500);
frame.setTitle("Circles generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
String input = JOptionPane.showInputDialog("Enter n:");
CustomComponents0 component = new CustomComponents0();
frame.add(component);
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
static class CustomComponents0 extends JLabel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(200, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
}
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository.
And you get a lot of beneficial side-effects! (:-)
Came across this issue after I merged a pull request on Bitbucket.
Had to do
git fetch
and that was it.
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
Add the following namespace,
using System.IO;
and use the Directory
class to reach on the specific folder:
string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
File.Delete(fileName);
I had the same problem, fixed it by removing the directory sessions of php
rm -rf /var/lib/php/sessions/
It may be under /var/lib/php5
if you are using a older php version.
Recreate it with the following permission
mkdir /var/lib/php/sessions/ && chmod 1733 /var/lib/php/sessions/
Permission by default for directory on Debian showed drwx-wx-wt
(1733)
This is a pretty old question but i think still relevant. Also the accepted answer works only for String. Meanwhile there is Mockito 2.1 and some imports have changed, so i would like to share my current answer:
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@Mock
private MyClass myClass;
// this will return anything you pass, but it's pretty unrealistic
when(myClass.myFunction(any())).then(returnsFirstArg());
// it is more "life-like" to accept only the right type
when(myClass.myFunction(any(ClassOfArgument.class))).then(returnsFirstArg());
The myClass.myFunction would look like:
public class MyClass {
public ClassOfArgument myFunction(ClassOfArgument argument){
return argument;
}
}
There is no such feature in markdown, however you can always use HTML inside markdown:
<a href="http://example.com/" target="_blank">example</a>
Here's my webpack 4 + font awesome 5 solution:
webpack plugin:
new CopyWebpackPlugin([
{ from: 'node_modules/font-awesome/fonts', to: 'font-awesome' }
]),
global css style:
@font-face {
font-family: 'FontAwesome';
src: url('/font-awesome/fontawesome-webfont.eot');
src: url('/font-awesome/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
url('/font-awesome/fontawesome-webfont.woff2') format('woff2'),
url('/font-awesome/fontawesome-webfont.woff') format('woff'),
url('/font-awesome/fontawesome-webfont.ttf') format('truetype'),
url('/font-awesome/fontawesome-webfont.svgfontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
i {
font-family: "FontAwesome";
}
met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
This one worked for me:
(?P<value>[-+]*\d+\.\d+|[-+]*\d+)
You can also use this one (without named parameter):
([-+]*\d+\.\d+|[-+]*\d+)
Use some online regex tester to test it (e.g. regex101 )
curl
's -w
option and the sub variable url_effective
is what you are
looking for.
Something like
curl -Ls -o /dev/null -w %{url_effective} http://google.com
More info
-L Follow redirects -s Silent mode. Don't output anything -o FILE Write output to <file> instead of stdout -w FORMAT What to output after completion
More
You might want to add -I
(that is an uppercase i
) as well, which will make the command not download any "body", but it then also uses the HEAD method, which is not what the question included and risk changing what the server does. Sometimes servers don't respond well to HEAD even when they respond fine to GET.
Per a comment by Daniel Neel above :
version 1.0.3 of the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package works for me, but version 1.0.6 causes the error in this question
Downgrading to 1.0.3 resolved this issue for me.
ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString()
method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.
For your use, I would suggest that you use the constructor:
ArrayAdapter(Context context, int resource, T[] objects).
In your case, this would be:
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)
and it should be fine. This will bind each string to the default TextView display - plain and simple white background.
So to answer your question, you do not have to use the textViewResourceId.
If you have commons-io
included in your project, you can do it without creating unecessary objects with org.apache.commons.io.FilenameUtils
String uri = "http://base_path/some_segment/id";
String fileName = FilenameUtils.getName(uri);
System.out.println(fileName);
Will give you the last part of the path, which is the id
Using the GNU datamash
util:
seq 10 | datamash sum 1
Output:
55
If the input data is irregular, with spaces and tabs at odd places, this may confuse datamash
, then either use the -W
switch:
<commands...> | datamash -W sum 1
...or use tr
to clean up the whitespace:
<commands...> | tr -d '[[:blank:]]' | datamash sum 1
try these too if just autocomplete="off"
doesn't work:
autocorrect="off" autocapitalize="off" autocomplete="off"
This works:
for i,r in data[::-1].iterrows():
print(r['Odd'], r['Even'])
This answer also contains a standard solution using only the jstl redirect tag:
<c:redirect url="/home.html"/>
maybe ZSI which implements SOAP. I used the stub generator and It worked properly. The only problem I encountered is about doing SOAP throught HTTPS.
If you want to create a temp table after check exist table.You can use the following code
DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
(
SiteName NVARCHAR(50),
BillingMonth varchar(10),
Consumption INT,
)
After creating the temporary table, you can insert data into this table as a regular table:
INSERT INTO #temptable
SELECT COLUMN1,...
FROM
(...)
or
INSERT INTO #temptable
VALUES (value1, value2, value3, ...);
The SELECT statement is used to select data from a temp table.
SELECT * FROM #temptable
you can manually remove the temporary table by using the DROP TABLE statement:
DROP TABLE #temptable;
Here is a simpler solution to list all files in a directory and to download it.
In your index.php file
<?php
$dir = "./";
$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and ..
foreach($files as $file){
echo "<a href='download.php?file=".$file."'>".$file."</a><br>";
}
The scandir() function list all files and directories inside the specified path. It works with both PHP 5 and PHP 7.
Now in the download.php
<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file = $path.$filename;
if(!empty($filename)){
// Check file is exists on given path.
if(file_exists($download_file))
{
header('Content-Disposition: attachment; filename=' . $filename);
readfile($download_file);
exit;
}
else
{
echo 'File does not exists on given path';
}
}
@DavidG's answer is correct, but I would like to add that if you're building from the command line, the equivalent solution is to make sure that you're using the appropriate version of msbuild
(in this particular case, it needs to be version 15).
Run msbuild /?
to see which version you're using or where msbuild
to check which location the environment takes the executable from and update (or point to the right location of) the tools if necessary.
Download the latest MSBuild tool from here.
I found simple solution to get current date without any parsing error.
Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
try this:
.button input, .button a {
//css here
}
That will apply the style to all a tags nested inside of <p class="button"></p>
Rather than thinking of the indices in the [a:]
-, [:b]
- and [a:b]
-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0
before the element indexed as 0
.
Looking at just the blue numbers, it's much easier to see what is going on: [0:3]
encloses everything, [3:3]
is empty and [1:2]
would yield {"B"}
. Then [a:]
is just the short version of [a:len(arrayOrSlice)]
, [:b]
the short version of [0:b]
and [:]
the short version of [0:len(arrayOrSlice)]
. The latter is commonly used to turn an array into a slice when needed.
With urlsearchparams:
const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`
First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"
You don't have to have a method for that. You could create a property like this instead:
class SalesPerson
{
string firstName, lastName;
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
public string FullName { get { return this.FirstName + " " + this.LastName; } }
}
The class could even be shortened to:
class SalesPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get { return this.FirstName + " " + this.LastName; }
}
}
The property could then be accessed like any other property:
class Program
{
static void Main(string[] args)
{
SalesPerson x = new SalesPerson("John", "Doe");
Console.WriteLine(x.FullName); // Will print John Doe
}
}
"How can this be improved?"
Well, you need to look at every method in your class and consider what would happen if another thread was simultaneously calling that method or any other method. For example, you put a lock in the Remove method, but not in the Add method. What happens if one thread Adds at the same time as another thread Removes? Bad things.
Also consider that a method can return a second object that provides access to the first object's internal data - for example, GetEnumerator. Imagine one thread is going through that enumerator, another thread is modifying the list at the same time. Not good.
A good rule of thumb is to make this simpler to get right by cutting down the number of methods in the class to the absolute minimum.
In particular, don't inherit another container class, because you will expose all of that class's methods, providing a way for the caller to corrupt the internal data, or to see partially complete changes to the data (just as bad, because the data appears corrupted at that moment). Hide all the details and be completely ruthless about how you allow access to them.
I'd strongly advise you to use off-the-shelf solutions - get a book about threading or use 3rd party library. Otherwise, given what you're attempting, you're going to be debugging your code for a long time.
Also, wouldn't it make more sense for Remove to return an item (say, the one that was added first, as it's a queue), rather than the caller choosing a specific item? And when the queue is empty, perhaps Remove should also block.
Update: Marc's answer actually implements all these suggestions! :) But I'll leave this here as it may be helpful to understand why his version is such an improvement.
If you just want to check if that item exists:
IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0)
{
// Not Found
}
else
{
// Found
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:nil //or self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert autorelease];
-(void)saveToUserDefaults:(NSString*)string_to_store keys:(NSString *)key_for_the_String
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:string_to_store forKey:key_for_the_String];
[standardUserDefaults synchronize];
}
}
And call it by:
[self saveToUserDefaults:@"string_to_store" : @"key_for_the_string"];
Retrieve the string by using:
NSString * stored_string = [[NSUserDefaults standardUserDefaults] stringforkey:key_for_the_String]
You can use reflections
return Class.forName(className).getConstructor(String.class).newInstance(arg);
Thanks for posting the question. I'd also like to add the script that helped me.
awk '{ $1=""; print $0 }' file
According to the website, sizeof()
is an alias of count()
, so they should be running the same code. Perhaps sizeof()
has a little bit of overhead because it needs to resolve it to count()
? It should be very minimal though.
Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.
Then you can just review the contents pre-update and write a SQL script to do the update.
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Okay, here are the explanations.
e.keyCode - used to get the number that represents the key on the keyboard
e.charCode - a number that represents the unicode character of the key on keyboard
e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)
Below is the code snippet to get the keyCode and charCode
<script>
// get key code
function getKey(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
alert(keyCode);
}
// get char code
function getChar(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
var typedChar = String.fromCharCode(keyCode);
alert(typedChar);
}
</script>
Live example of Getting keyCode and charCode in JavaScript.
The two methods are 100% equivalent.
I’m not sure why Microsoft felt the need to include this extra Clear
method but since it’s there, I recommend using it, as it clearly expresses its purpose.
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
Maybe you could find that out by looking at the query log.
Just set your java_home property with java home (eg:C:\Program Files\Java\jdk1.7.0_25) directory. Close command prompt and reopen it. Then error relating to tools.jar will be solved. For the second one("build.xml not found ") you should have to ensure your command line also at the directory where your build.xml file resides.
I have this sample Java Code:
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
public class TestClass {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(8081);
Socket accept = socket.accept();
InputStream inputStream = accept.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char readChar;
while ((readChar = (char) inputStreamReader.read()) != -1) {
System.out.print(readChar);
}
inputStream.close();
accept.close();
System.exit(1);
}
}
and I have this test.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit">
</form>
</body>
</html>
and finally the file I will be using for testing purposes, named a.dat has the following content:
0x39 0x69 0x65
if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:
9ie
So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat
and submit the form and see what our server receives:
POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF
------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream
9ie
------WebKitFormBoundary06f6g54NVbSieT6y--
Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF
is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.
While working on a WordPress theme, I got the same ELIFECYCLE
error with slightly different output:
npm ERR! Darwin 14.5.0 npm ERR! argv "/usr/local/Cellar/node/7.6.0/bin/node" "/usr/local/bin/npm" "install" npm ERR! node v7.6.0 npm ERR! npm v3.7.3 npm ERR! code ELIFECYCLE npm ERR! [email protected] postinstall: `bower install && gulp build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] postinstall script 'bower install && gulp build'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the foundationsix package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! bower install && gulp build
After trying npm install
one more time with the same result, I tried bower install
. When that was successful I tried gulp build
and that also worked.
Everything is working just fine now. No idea why running each command separately worked when &&
failed but maybe someone else will find this answer useful.
from __future__ import print_function
import csv
import MySQLdb
print("Enter File To Be Export")
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
cursor = conn.cursor()
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 (policyID int, statecode varchar(255), county varchar(255))'''
cursor.execute(sql)
with open('C:/Users/Desktop/Code/python/sample.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter = ',')
for row in reader:
print(row['policyID'], row['statecode'], row['county'])
# insert
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
sql_statement = "INSERT INTO test1(policyID ,statecode,county) VALUES (%s,%s,%s)"
cur = conn.cursor()
cur.executemany(sql_statement,[(row['policyID'], row['statecode'], row['county'])])
conn.escape_string(sql_statement)
conn.commit()
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
If you are ok with manually selecting the column, you could be very fast using pick:
svn st | pick | xargs rm
Just go to any cell of the 2nd column, press c
and then hit enter
MySQL is different from most DBMSs use of +
or ||
for concatenation. It uses the CONCAT
function:
SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student
As @eggyal pointed out in comments, you can enable string concatenation with the ||
operator in MySQL by setting the PIPES_AS_CONCAT
SQL mode.
Strangely enough,
package main
func main () {
var sessions = map[string] chan int{};
delete(sessions, "moo");
}
seems to work. This seems a poor use of resources though!
Another way is to check for existence and use the value itself:
package main
func main () {
var sessions = map[string] chan int{};
sessions["moo"] = make (chan int);
_, ok := sessions["moo"];
if ok {
delete(sessions, "moo");
}
}
Try to encode backslash between domain and user
pip --proxy https://domain%5Cuser:password@proxy:port install -r requirements.txt
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
I have one generic log4j.xml file for you:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<appender name="default.console" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="default.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/mylogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="another.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/anotherlogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<logger name="com.yourcompany.SomeClass" additivity="false">
<level value="debug" />
<appender-ref ref="another.file" />
</logger>
<root>
<priority value="info" />
<appender-ref ref="default.console" />
<appender-ref ref="default.file" />
</root>
</log4j:configuration>
with one console, two file appender and one logger poiting to the second file appender instead of the first.
EDIT
In one of the older projects I have found a simple log4j.properties file:
# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.
# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file
# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n
log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n
For the description of all the layout arguments look here: log4j PatternLayout arguments
www.bitvise.com - sftpc is a good command line client also.
When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.
By default, Web API uses the following rules to bind parameters:
If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
For complex types, Web API tries to read the value from the message body, using a media-type formatter.
So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri]
attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody]
attribute to the parameter.
So, to answer your question, the need of the [FromBody]
and [FromUri]
attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.
There is a lot more information on the web if you google "web api parameter binding".
String[] token=s.split("[.-]");
I had the same problem, this is the solution i came up with, which is much easier!
Make a little 1px x 1px transparent image and save it as a .png file.
In the CSS for your DIV, use this code:
background:transparent url('/images/trans-bg.png') repeat center top;
Remember to change the file path to your transparent image.
I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).
To my knowledge your trivial implementation is the easiest way to get such an behaviour.
You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.
http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori
Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link
function of the directive.
There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls
Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.
EDIT: Rather than using $(element)
, you can make use of angular.element(element)
when using AngularJS with jQuery
Providing both JAVA_HOME and JDK_HOME with identical Path without \bin helped for me! My settings:
\Program Files\Java\jdk1.8.0_05
%JAVA_HOME%
...%JAVA_HOME%\bin
Warning invalid argument supplied for foreach()
display tweets.
go to /wp-content/plugins/display-tweets-php
.
Then insert this code on line number 591, It will run perfectly.
if (is_array($tweets)) {
foreach ($tweets as $tweet)
{
...
}
}
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
It can be accomplished with a simple one-liner.
Having this array:
$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');
You can do:
$arr = array_diff($arr, array('remove_me', 'remove_me_also'));
And the value of $arr
will be:
array('nice_item', 'another_liked_item')
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
With Android Studio 2.3(AS) the project works fine and i can able to run the App. After updating the AS to Android Studio 3.0. i too got the error as below for libraries and build types.
Unable to resolve dependency for ':app@dexOptions/compileClasspath': Could not resolve project : library_Name.
Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve project : library_Name.
To Solve the issue, simply.
What ever the
buildTypes{
debug{ ... }
release{ ... }
}
you have in your (app) build.gradle file, You have to include all the buildTypes{ }
with same names as like
buildTypes{
debug{ ... }
release{ ... }
}
in to build.gradle
files of All libraries/modules included in project.
clean and rebuild the project, the issue will be fixed.
Still issue not fixed, update the gradle-wrapper.properties to
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS
Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideID
For Each curShape In curSlide.Shapes
If curShape.TextFrame.HasText Then
Debug.Print curShape.Id
End If
Next curShape
Next curSlide
End Sub
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
This is not the recommended solution as I am going in android apis here but as my application requires to change the theme dynmically on conditions xml not possible here, So I need to do this. But This solution is working very nice.
/**
*
* @author Kailash Dabhi
* @email [email protected]
*
*/
public static void setActionbarTextColor(Activity activity, int color) {
Field mActionViewField;
try {
mActionViewField = activity.getActionBar().getClass()
.getDeclaredField("mActionView");
mActionViewField.setAccessible(true);
Object mActionViewObj = mActionViewField.get(activity
.getActionBar());
Field mTitleViewField = mActionViewObj.getClass().getDeclaredField(
"mTitleView");
mTitleViewField.setAccessible(true);
Object mTitleViewObj = mTitleViewField.get(mActionViewObj);
TextView mActionBarTitle = (TextView) mTitleViewObj;
mActionBarTitle.setTextColor(color);
// Log.i("field", mActionViewObj.getClass().getName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
My solution
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1
Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value
<select name="gender">
<option value="default">Select </option>
<option value="male"> Male </option>
<option value="female"> Female </option>
</select>
OR
<select name="gender">
<option value="male" selected="selected"> Male </option>
<option value="female"> Female </option>
</select>
When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.
Most important thing, AVOID SQL INJECTIONS:
//....
$fname = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$email = mysql_real_escape_string($_POST['email']);
}
else
{
//die ('invalid email address');
// or whatever, a default value? $email = '';
}
$paswod = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';
$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
echo 'userid is already there';
}
else
{
$sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';
Here's a simpler method, that requires neither events or timeouts. It does require jQuery, however.
Use jQuery.holdReady()
(docs)
So, immediately after your jQuery script, delay the ready event.
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$.holdReady( true ); // don't fire ready until told (ie when FB loaded)
</script>
Then, in your Facebook init function, release it:
window.fbAsyncInit = function() {
FB.init({
appId: '11111111111111',
cookie: true,
xfbml: false,
version: 'v2.4'
});
// release the ready event to execute
$.holdReady( false );
};
Then you can use the ready event as normal:
$(document).ready( myApp.init );
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
protected void setMenuBackground() {
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView (String name, Context context, AttributeSet attrs) {
if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
try {
// Ask our inflater to create the view
LayoutInflater f = getLayoutInflater();
final View view = f.createView(name, null, attrs);
// Kind of apply our own background
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundResource(R.drawable.gray_gradient_background);
}
});
return view;
}
catch (InflateException e) {
}
catch (ClassNotFoundException e) {
}
}
return null;
}
});
}
this is XML file
gradient
android:startColor="#AFAFAF"
android:endColor="#000000"
android:angle="270"
shape
Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:
Copy the whole document and create a .html file you'll be able to figure out on your own from that!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The Divs Case</title>
<style type="text/css">
* {margin:0px auto;
padding:0px;}
.container {width:800px;
height:600px;
background:#FFC;
border:solid #F3F3F3 1px;}
.div01 {float:right;
background:#000;
height:200px;
width:200px;
display:none;}
.div02 {float:right;
background:#FF0;
height:150px;
width:150px;
display:none;}
.div03 {float:right;
background:#FFF;
height:100px;
width:100px;
display:none;}
div.container:hover div.div01 {display:block;}
div.container div.div01:hover div.div02 {display:block;}
div.container div.div01 div.div02:hover div.div03 {display:block;}
</style>
</head>
<body>
<div class="container">
<div class="div01">
<div class="div02">
<div class="div03">
</div>
</div>
</div>
</div>
</body>
</html>
In my case the problem occured from php
file.
It gave unwanted characters.That is why a json parsing
problem occured.
Then I paste my php code
in Notepad++
and select Encode in utf-8 without BOM
from Encoding
tab and running this code-
My problem gone away.
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
Delete the working copy from the OS and check it out again is simplest, but obviously not a single command.
I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.
Also, my templating engine is smarty, but I'm sure you get the idea.
The meat...
Updating the indicators:
<ol class="carousel-indicators">
{assign var='walker' value=0}
{foreach from=$item["imagearray"] key="key" item="value"}
<li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
<img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
</li>
{assign var='walker' value=1 + $walker}
{/foreach}
</ol>
Changing the CSS related to the indicators:
.carousel-indicators {
bottom:-50px;
height: 36px;
overflow-x: hidden;
white-space: nowrap;
}
.carousel-indicators li {
text-indent: 0;
width: 34px !important;
height: 34px !important;
border-radius: 0;
}
.carousel-indicators li img {
width: 32px;
height: 32px;
opacity: 0.5;
}
.carousel-indicators li:hover img, .carousel-indicators li.active img {
opacity: 1;
}
.carousel-indicators .active {
border-color: #337ab7;
}
When the carousel has slid, update the list of thumbnails:
$('#myCarousel').on('slid.bs.carousel', function() {
var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width();
var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
var toScroll = newIndicatorPosition + indicatorPosition;
var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
if (adjustedScroll < 0)
adjustedScroll = 0;
if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
adjustedScroll = widthEstimate - $(".carousel-indicators").width();
$('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);
indicatorPosition = adjustedScroll;
});
And, when your page loads, set the initial scroll position of the thumbnails:
var indicatorPosition = 0;
An object that is a boolean will either have a class of TrueClass or FalseClass so the following one-liner should do the trick
mybool = true
mybool.class == TrueClass || mybool.class == FalseClass
=> true
The following would also give you true/false boolean type check result
mybool = true
[TrueClass, FalseClass].include?(mybool.class)
=> true
I was facing the same issue when integrating Firebase Cloud Store in my project. Inside the project level gradle, I added
classpath 'com.google.gms:google-services:4.0.1'
that fixed the issue.
Considere the case that Java is Multiplatform:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}
Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "
Ex:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
Another very simple yet noobish mistake of mine: I simply forgot to add a message -m
modifier in my commit. So I wrote:
git commit 'My message'
Instead of correct:
git commit -m 'My message'
NOTE: It does NOT throw any errors! But you will not be able to push your commits and always get Everything up to date
instead
An ES6 implementation based on biziclops great answer:
root = {_x000D_
text: "root",_x000D_
children: [{_x000D_
text: "c1",_x000D_
children: [{_x000D_
text: "c11"_x000D_
}, {_x000D_
text: "c12"_x000D_
}]_x000D_
}, {_x000D_
text: "c2",_x000D_
children: [{_x000D_
text: "c21"_x000D_
}, {_x000D_
text: "c22"_x000D_
}]_x000D_
}, ]_x000D_
}_x000D_
_x000D_
console.log("DFS:")_x000D_
DFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
console.log("BFS:")_x000D_
BFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
function BFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...nodesToVisit,_x000D_
...(getChildren(currentNode) || []),_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}_x000D_
_x000D_
function DFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...(getChildren(currentNode) || []),_x000D_
...nodesToVisit,_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}
_x000D_
In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")
Change
if [ -s "p1"]; #line 13
into
if [ -s "p1" ]; #line 13
note the space.
To get the actual access_token
, you can also do pro grammatically via the following PHP code:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Key class:
@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {
public EntryKey() {
}
public EntryKey(final Long id, final Long version) {
this.id = id;
this.version = version;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
this.version = version;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof EntryKey))
return false;
EntryKey castOther = (EntryKey) other;
return id.equals(castOther.id) && version.equals(castOther.version);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.id.hashCode();
hash = hash * prime + this.version.hashCode();
return hash;
}
@Column (name = "ID")
private Long id;
@Column (name = "VERSION")
private Long operatorId;
}
Entity class:
@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {
@EmbeddedId
public EntryKey getKey() {
return this.key;
}
public void setKey(EntryKey id) {
this.id = id;
}
...
private EntryKey key;
...
}
How can I duplicate it with another Version?
You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.
The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.
You can access web references via the advanced options in add service reference (if I recall correctly).
I'd use service reference because as I understand it, it's the newer mechanism of the two.
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
Use this.getClass().getCanonicalName()
to get the full class name.
Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.
You can do this by adding a parameter &hd=1
to the video URL. That forces the video to start in the highest resolution available for the video. However you cannot specifically set it to 720p, because not every video has that hd ish.
http://code.google.com/apis/youtube/player_parameters.html
UPDATE: as of 2014, hd is deprecated https://developers.google.com/youtube/player_parameters?csw=1#Deprecated_Parameters
Try this:
private void txtEntry_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string trimText;
trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
this.txtEntry.Text = trimText;
btnEnter.PerformClick();
}
}
SwiftMailer can send E-Mail using external servers.
here is an example that shows how to use a Gmail server:
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
"smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).
You could just use window.location.hash
to grab the id.
var id = window.location.hash;
I don't think you will need that much code to achieve this.
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
<img src="/images/yourfile.png">
Store your files in public/images directory.
I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.
Found this plugin, it's a clean way to add external scripts both via CDN and from static files https://www.npmjs.com/package/vue-plugin-load-script
// local files
// you have to put your scripts into the public folder.
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")
// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")
window.open('your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')
What you could do is something like this (pseudocode):
<container table>
<tr>
<td>
<"300px" table>
<td>
<fixed layout table>
Basically, split up the table into two tables and have it contained by another table.
Try innerText property:
var content = document.getElementById("one").innerText;
alert(content);
See also this fiddle http://fiddle.jshell.net/4g8vb/
Please have a look
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.box{ width:500px; height:200px; background:#000; border:2px solid #ccc;}
.inner-border {
border: 20px solid black;
box-shadow: inset 0px 0px 0px 10px red;
box-sizing: border-box; /* Include padding and border in element's width and height */
}
/* CSS3 solution only for rectangular shape */
.inner-outline {
outline: 10px solid red;
outline-offset: -30px;
}
</style>
</head>
<body>
<div class="box inner-border inner-outline"></div>
</body>
</html>
Using management studio the procedure can be done as follows
You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.
Click option menu and tick Overwrite the existing database(With replace)
@doc_180 had the right concept, except he is focused on numbers, whereas the original poster had issues with strings.
The solution is to change the mx.rpc.xml.XMLEncoder
file. This is line 121:
if (content != null)
result += content;
(I looked at Flex 4.5.1 SDK; line numbers may differ in other versions.)
Basically, the validation fails because 'content is null' and therefore your argument is not added to the outgoing SOAP Packet; thus causing the missing parameter error.
You have to extend this class to remove the validation. Then there is a big snowball up the chain, modifying SOAPEncoder to use your modified XMLEncoder, and then modifying Operation to use your modified SOAPEncoder, and then moidfying WebService to use your alternate Operation class.
I spent a few hours on it, but I need to move on. It'll probably take a day or two.
You may be able to just fix the XMLEncoder line and do some monkey patching to use your own class.
I'll also add that if you switch to using RemoteObject/AMF with ColdFusion, the null is passed without problems.
11/16/2013 update:
I have one more recent addition to my last comment about RemoteObject/AMF. If you are using ColdFusion 10; then properties with a null value on an object are removed from the server-side object. So, you have to check for the properties existence before accessing it or you will get a runtime error.
Check like this:
<cfif (structKeyExists(arguments.myObject,'propertyName')>
<!--- no property code --->
<cfelse>
<!--- handle property normally --->
</cfif>
This is a change in behavior from ColdFusion 9; where the null properties would turn into empty strings.
Edit 12/6/2013
Since there was a question about how nulls are treated, here is a quick sample application to demonstrate how a string "null" will relate to the reserved word null.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="application1_initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function application1_initializeHandler(event:FlexEvent):void
{
var s :String = "null";
if(s != null){
trace('null string is not equal to null reserved word using the != condition');
} else {
trace('null string is equal to null reserved word using the != condition');
}
if(s == null){
trace('null string is equal to null reserved word using the == condition');
} else {
trace('null string is not equal to null reserved word using the == condition');
}
if(s === null){
trace('null string is equal to null reserved word using the === condition');
} else {
trace('null string is not equal to null reserved word using the === condition');
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>
The trace output is:
null string is not equal to null reserved word using the != condition
null string is not equal to null reserved word using the == condition
null string is not equal to null reserved word using the === condition
jQuery offers $.inArray
:
Note that inArray returns the index of the element found, so 0
indicates the element is the first in the array. -1
indicates the element was not found.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Edit 3.5 years later
$.inArray
is effectively a wrapper for Array.prototype.indexOf
in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype
, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Edit another 3 years later
Gosh, 6.5 years?!
The best option for this in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
No comparisons and no confusing -1
results. It does what we want: it returns true
or false
. For older browsers it's polyfillable using the code at MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
Run git fetch --all
before git pull
. That should solve the problem.