First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
I don't think this is your case, but I'll post it if it helps anyone. I had the same issue and the problem was that Node didn't respond at all (I had a condition that when failed didn't do anything - so no response) - So if increasing all your timeouts didn't solve it, make sure all scenarios get a response.
The problem is that readlines
is a list of strings, each of which is a line of filename
. Perhaps you meant:
for line in readlines:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
JSONArray
has a constructor which takes a String
source (presumed to be an array).
So something like this
JSONArray array = new JSONArray(yourJSONArrayAsString);
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
Ruby
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
While the answer from @alessioalex works, there's another way as stated in the Express behind proxies section of Express - guide.
app.set('trust proxy', true)
to your express initialization code.req.ip
or req.ips
in the usual way (as if there isn't a reverse proxy)Optional reading:
req.ip
or req.ips
. req.connection.remoteAddress
does't work with this solution.'trust proxy'
are available if you need something more sophisticated than trusting everything passed through in x-forwarded-for
header (for example, when your proxy doesn't remove preexisting x-forwarded-for header from untrusted sources). See the linked guide for more details.x-forwarded-for
header, there are two possibilities.
proxy_set_header X-Forwarded-For $remote_addr;
to your configuration.To solve this in programing way for interview
def reverse_a_string(string: str) -> str:
"""
This method is used to reverse a string.
Args:
string: a string to reverse
Returns: a reversed string
"""
if type(string) != str:
raise TypeError("{0} This not a string, Please provide a string!".format(type(string)))
string_place_holder = ""
start = 0
end = len(string) - 1
if end >= 1:
while start <= end:
string_place_holder = string_place_holder + string[end]
end -= 1
return string_place_holder
else:
return string
a = "hello world"
rev = reverse_a_string(a)
print(rev)
Output:
dlrow olleh
Do you want something like the given fiddle!
HTML
<div class="button">
<input type="button" value="TELL ME MORE" onClick="document.location.reload(true)">
</div>
CSS
.button input[type="button"] {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
display:block;
width:100%;
}
.button input[type="button"]:hover {
background-color:rgba(255,204,0,0.8);
}
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
How to print on the same line:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
Try something like this onclick="return self.close()"
I had the same problem when adding react-native-palette
to my project, here is my dependencies tree:
./gradlew app:dependencies
+--- project :react-native-palette
| +--- com.facebook.react:react-native:0.20.+ -> 0.44.2
| | +--- javax.inject:javax.inject:1
| | +--- com.android.support:appcompat-v7:23.0.1
| | | \--- com.android.support:support-v4:23.0.1
| | | \--- com.android.support:support-annotations:23.0.1 -> 24.2.1
...
| \--- com.android.support:palette-v7:24.+ -> 24.2.1
| +--- com.android.support:support-compat:24.2.1
| | \--- com.android.support:support-annotations:24.2.1
| \--- com.android.support:support-core-utils:24.2.1
| \--- com.android.support:support-compat:24.2.1 (*)
+--- com.android.support:appcompat-v7:23.0.1 (*)
\--- com.facebook.react:react-native:+ -> 0.44.2 (*)
I tried many solutons and could not fix it, until changing the com.android.support:appcompat
version in android/app/build.gradle
, I wish this can help:
dependencies {
compile project(':react-native-palette')
compile project(':react-native-image-picker')
compile project(':react-native-camera')
compile fileTree(dir: "libs", include: ["*.jar"])
// compile "com.android.support:appcompat-v7:23.0.1"
compile "com.android.support:appcompat-v7:24.2.1"
compile "com.facebook.react:react-native:+"
}
it seems that multiple entries is not a big problem, version mismatch is
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
If you're using PHP and none of the above worked (as it was my case), you need to set the locale with utf-8 encoding.
Like this
setlocale(LC_ALL, 'fr_CA.utf-8');
Use delete-keyword.
delete obj[1];
EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.
You can also use a "here document" to do the same thing:
VARIABLE=SOMEVALUE
sqlplus connectioninfo << HERE
start file1.sql
start file2.sql $VARIABLE
quit
HERE
If you happened to run npm install
command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.
You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call. So the best way:
$("#mylist li").length
If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
This is what worked for me (Updated for VS 2013, see revision history for 2010, for VS 2015 see this: https://stackoverflow.com/a/32744234/218971):
Right-click your Web Application Project ? Properties
? Web
, then configure the Servers
section as follows:
http://localhost
http://dev.example.com
Default Site
to anything but port :80
, make sure Skype isn't using port 80, etc.)Optionally: Set the Start URL
to http://dev.example.com
Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config
(Windows XP, Vista, and 7) and edit the site definition in the <sites>
config block to be along the lines of the following:
<site name="DevExample" id="997005936">
<application path="/" applicationPool="Clr2IntegratedAppPool">
<virtualDirectory
path="/"
physicalPath="C:\path\to\application\root" />
</application>
<bindings>
<binding
protocol="http"
bindingInformation=":80:dev.example.com" />
</bindings>
<applicationDefaults applicationPool="Clr2IntegratedAppPool" />
</site>
If running MVC: make sure the applicationPool
is set to one of the "Integrated" options (like "Clr2IntegratedAppPool").
Open your hosts
file and add the line 127.0.0.1 dev.example.com
.
? Start your application!
Some great advice from the comments:
- You may need to run Visual Studio as Administrator.
- If you want to make other devs see your IIS run
netsh http add urlacl url=http://dev.example.com:80/ user=everyone
- If you want the site to resolve for all hosts set
bindingInformation="*:80:"
. Use any port you want, 80 is just convenient. To resolve all hosts you'll need to run Visual Studio as an administrator
Do you have Egit installed yet? If not, go to Window->Preferences->Install/Updates->Available Software Sites. Click on add and paste this link http://download.eclipse.org/egit/updates
For Name, you can just put "EGit". After you have EGit installed, follow this tutorial. It helped me a lot!
If you are using HTML 5, you need to specify that in your DOCTYPE
declaration.
For a valid HTML 5 document, it should start with:
<!DOCTYPE html>
Before HTML 5, the textarea
element did not have a maxlength
attribute.
You can see this in the DTD/spec:
<!ELEMENT TEXTAREA - - (#PCDATA) -- multi-line text field -->
<!ATTLIST TEXTAREA
%attrs; -- %coreattrs, %i18n, %events --
name CDATA #IMPLIED
rows NUMBER #REQUIRED
cols NUMBER #REQUIRED
disabled (disabled) #IMPLIED -- unavailable in this context --
readonly (readonly) #IMPLIED
tabindex NUMBER #IMPLIED -- position in tabbing order --
accesskey %Character; #IMPLIED -- accessibility key character --
onfocus %Script; #IMPLIED -- the element got the focus --
onblur %Script; #IMPLIED -- the element lost the focus --
onselect %Script; #IMPLIED -- some text was selected --
onchange %Script; #IMPLIED -- the element value was changed --
%reserved; -- reserved for possible future use --
>
In order to limit the number of characters typed into a textarea
, you will need to use javascript with the onChange
event. You can then count the number of characters and disallow further typing.
Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.
Here is another sample.
I used this solution: in TableRow
, I created for every cell LinearLayout
with vertical line and actual cell in it, and after every TableRow
, I added a horizontal line.
Look at the code below:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:shrinkColumns="1">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_height="match_parent"
android:layout_width="1dp"
android:background="#BDCAD2"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
</TableRow>
<View
android:layout_height="1dip"
android:background="#BDCAD2" />
<!-- More TableRows -->
</TableLayout>
Hope it will help.
Running .NET core
(3.1.4) on IIS
behind a Load balancer did not work with other suggested solutions.
Manually reading the X-Forwarded-For
header does.
IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
// when running behind a load balancer you can expect this header
var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
ip = IPAddress.Parse(header);
}
else
{
// this will always have a value (running locally in development won't have the header)
ip = Request.HttpContext.Connection.RemoteIpAddress;
}
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
lblVersion.text = "Version \(version)"
}
mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
As everyone else has noted, you can use semicolons to separate statements. You don't have to, and it's not the usual style.
As for why this is useful, some people like to put two or more really trivial short statements on a single line (personally I think this turns several trivial easily skimmed lines into one complex-looking line and makes it harder to see that it's trivial).
But it's almost a requirement when you're invoking Python one liners from the shell using python -c '<some python code>'
. Here you can't use indentation to separate statements, so if your one-liner is really a two-liner, you'll need to use a semicolon. And if you want to use other arguments in your one-liner, you'll have to import sys
to get at sys.argv
, which requires a separate import
statement. e.g.
python -c "import sys; print ' '.join(sorted(sys.argv[1:]))" 5 2 3 1 4
1 2 3 4 5
Check if the columns contain Nan
using .isnull()
and check for empty strings using .eq('')
, then join the two together using the bitwise OR operator |
.
Sum along axis 0
to find columns with missing data, then sum along axis 1
to the index locations for rows with missing data.
missing_cols, missing_rows = (
(df2.isnull().sum(x) | df2.eq('').sum(x))
.loc[lambda x: x.gt(0)].index
for x in (0, 1)
)
>>> df2.loc[missing_rows, missing_cols]
A2 A3
2 1.10035
5 -0.508501
6 NaN NaN
7 NaN NaN
There is now a great plugin for Firebug that clones this nice feature in chrome. Check out:
https://addons.mozilla.org/en-US/firefox/addon/firestorage-plus/
It's developed by Nick Belhomme and updated regularly
int main() {
using namespace std;
fstream input ("input.txt");
if (!input) return 1;
vector<double> v;
for (double d; input >> d;) {
v.push_back(d);
}
if (v.empty()) return 1;
double total = std::accumulate(v.begin(), v.end(), 0.0);
double mean = total / v.size();
cout << "The values in the file input.txt are:\n";
for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
cout << *x << '\n';
}
cout << "The sum of the values is: " << total << '\n';
cout << "The mean value is: " << mean << '\n';
cout << "After subtracting the mean, The values are:\n";
for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
cout << *x - mean << '\n'; // outputs without changing
*x -= mean; // changes the values in the vector
}
return 0;
}
You can use the SpreadOpeator and the map() function to create an array with the same element repeated multiple times.
function fillArray(value,len){
return [...Array(len).keys()].map(x=> value);
}
ComponentWillReceiveProps()
is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate()
and ShouldComponentUpdate()
.
ComponentDidUpdate()
is called whenever the component updates AND if ShouldComponentUpdate()
returns true (If ShouldComponentUpdate()
is not defined it returns true
by default).
shouldComponentUpdate(nextProps){
return nextProps.changedProp !== this.state.changedProp;
}
componentDidUpdate(props){
// Desired operations: ex setting state
}
This same behavior can be accomplished using only the ComponentDidUpdate()
method by including the conditional statement inside of it.
componentDidUpdate(prevProps){
if(prevProps.changedProp !== this.props.changedProp){
this.setState({
changedProp: this.props.changedProp
});
}
}
If one attempts to set the state without a conditional or without defining ShouldComponentUpdate()
the component will infinitely re-render
As of today Nov 4, 2018 all the following methods works, install the zsh with:
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
Not recommending brew installation for zsh:
brew install zsh zsh-completions
P.S: Tried with with brew and brew install under the root and is not an wise idea to do so due the security and all time anything related will need to be started under sudo so better is to stick with curl or wget.
to make work conda in OS X with oh-my-zsh installed is to add path as following and will work.
Find the python paths so can see if you installed Anaconda2 or Anaconda3:
where python
orwhich python
will result in similar output:
/usr/bin/python
/Users/"username"/anaconda3/bin/python
/usr/bin/python
Finding your Anaconda Python interpreter path
vi ~/.zshrc or gedit ~/.zshrc
For Anaconda: at field
# User configuration
add:
PATH="$HOME/anaconda/bin:$PATH"
For Anaconda2 at field
# User configuration
add:
PATH="$HOME/anaconda/bin:$PATH"
For Anaconda3 at field
# User configuration
add:
PATH="$HOME/anaconda3/bin:$PATH"
or replace "username" with your username:
PATH="/Users/"username"/anaconda3/bin:$PATH
According to documentation Installing on macOS we add add in
~/.zshrc
instead of.bashrc or .bash_profile
Add export
PATH="/<path to anaconda>/bin:$PATH"
in ~/.zshrcOr set the PATH variable:
export PATH="/<path to anaconda>/bin:$PATH"
Replace
“<path to anaconda>”
with the actual path to your Anaconda installation.This methods are working on ubuntu/Centos7/MacOS as well (just close/reset the terminal once you are completing the changes) than just type conda to test.
Per @truongnm comment just source after adding the path: "I pasted the path from my bash_profile, and don't forget to
source ~/.zshrc
"
I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.
The following code works lately:
string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";
using (MySqlConnection cn = new MySqlConnection(connetionString))
{
try
{
string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
cn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, cn))
{
cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
cmd.ExecuteNonQuery();
}
}
catch (MySqlException ex)
{
MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
}
}
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
/*arrayname is an array of 5 integer*/
int[] arrayname = new int[5];
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
children()
only looks at the immediate children of the node, while find()
traverses the entire DOM below the node, so children()
should be faster given equivalent implementations. However, find()
uses native browser methods, while children()
uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.
Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).
Got it working! I should have been building a JSONArray
of JSONObject
s and then add the array to a final "Addresses" JSONObject
. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
After much trial and error, I found that if I increase the output_buffering
value in the php.ini file, this error goes away
I think the best that's possible in cross-browser JavaScript is window.print()
, which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.
FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...
You can do this very easily with the [].filter
method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You will need to add a shim for browsers that don't support the [].filter
method: this MDN page gives such code.
Using plain javascript:
element.parentNode
In jQuery:
element.parent()
Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
since basestring
isn't defined in Python3, this little trick might help to make the code compatible:
try: # check whether python knows about 'basestring'
basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
basestring=str
after that you can run the following test on both Python2 and Python3
isinstance(myvar, basestring)
Here's a function that acts as a thin wrapper around MutationObserver. The only requirement is that the browser support MutationObserver; there is no dependency on JQuery. Run the snippet below to see a working example.
function waitForMutation(parentNode, isMatchFunc, handlerFunc, observeSubtree, disconnectAfterMatch) {_x000D_
var defaultIfUndefined = function(val, defaultVal) {_x000D_
return (typeof val === "undefined") ? defaultVal : val;_x000D_
};_x000D_
_x000D_
observeSubtree = defaultIfUndefined(observeSubtree, false);_x000D_
disconnectAfterMatch = defaultIfUndefined(disconnectAfterMatch, false);_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
mutations.forEach(function(mutation) {_x000D_
if (mutation.addedNodes) {_x000D_
for (var i = 0; i < mutation.addedNodes.length; i++) {_x000D_
var node = mutation.addedNodes[i];_x000D_
if (isMatchFunc(node)) {_x000D_
handlerFunc(node);_x000D_
if (disconnectAfterMatch) observer.disconnect();_x000D_
};_x000D_
}_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
observer.observe(parentNode, {_x000D_
childList: true,_x000D_
attributes: false,_x000D_
characterData: false,_x000D_
subtree: observeSubtree_x000D_
});_x000D_
}_x000D_
_x000D_
// Example_x000D_
waitForMutation(_x000D_
// parentNode: Root node to observe. If the mutation you're looking for_x000D_
// might not occur directly below parentNode, pass 'true' to the_x000D_
// observeSubtree parameter._x000D_
document.getElementById("outerContent"),_x000D_
// isMatchFunc: Function to identify a match. If it returns true,_x000D_
// handlerFunc will run._x000D_
// MutationObserver only fires once per mutation, not once for every node_x000D_
// inside the mutation. If the element we're looking for is a child of_x000D_
// the newly-added element, we need to use something like_x000D_
// node.querySelector() to find it._x000D_
function(node) {_x000D_
return node.querySelector(".foo") !== null;_x000D_
},_x000D_
// handlerFunc: Handler._x000D_
function(node) {_x000D_
var elem = document.createElement("div");_x000D_
elem.appendChild(document.createTextNode("Added node (" + node.innerText + ")"));_x000D_
document.getElementById("log").appendChild(elem);_x000D_
},_x000D_
// observeSubtree_x000D_
true,_x000D_
// disconnectAfterMatch: If this is true the hanlerFunc will only run on_x000D_
// the first time that isMatchFunc returns true. If it's false, the handler_x000D_
// will continue to fire on matches._x000D_
false);_x000D_
_x000D_
// Set up UI. Using JQuery here for convenience._x000D_
_x000D_
$outerContent = $("#outerContent");_x000D_
$innerContent = $("#innerContent");_x000D_
_x000D_
$("#addOuter").on("click", function() {_x000D_
var newNode = $("<div><span class='foo'>Outer</span></div>");_x000D_
$outerContent.append(newNode);_x000D_
});_x000D_
$("#addInner").on("click", function() {_x000D_
var newNode = $("<div><span class='foo'>Inner</span></div>");_x000D_
$innerContent.append(newNode);_x000D_
});
_x000D_
.content {_x000D_
padding: 1em;_x000D_
border: solid 1px black;_x000D_
overflow-y: auto;_x000D_
}_x000D_
#innerContent {_x000D_
height: 100px;_x000D_
}_x000D_
#outerContent {_x000D_
height: 200px;_x000D_
}_x000D_
#log {_x000D_
font-family: Courier;_x000D_
font-size: 10pt;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h2>Create some mutations</h2>_x000D_
<div id="main">_x000D_
<button id="addOuter">Add outer node</button>_x000D_
<button id="addInner">Add inner node</button>_x000D_
<div class="content" id="outerContent">_x000D_
<div class="content" id="innerContent"></div>_x000D_
</div>_x000D_
</div>_x000D_
<h2>Log</h2>_x000D_
<div id="log"></div>
_x000D_
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
C# - serialData is ReceivedEventHandler
in TextBox
.
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));
Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.
Serial:
Serial.print(rnd);
Serial.( '\n' ); //carriage return
Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:
Sub ARRAYER()
Dim Number_of_Sims As Long
Dim rng As Range
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Number_of_Sims = 100000
Set rng = Range("C4:G4")
rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
You can't do it with the layout alone, I've tried. I ended up writing a very simple class to handle it, you can check it out on github. SquareImage.java Its part of a larger project but nothing a little copy and paste can't fix (licensed under Apache 2.0)
Essentially you just need to set the height/width equal to the other dimension (depending on which way you want to scale it)
Note: You can make it square without a custom class using the scaleType
attribute but the view's bounds extend beyond the visible image, which makes it an issue if you are placing other views near it.
I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.
It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await
or Wait()
the call to Foo
.
public async Task Foo()
{
var x = await DoSomethingAsync();
}
public async void DoFoo()
{
try
{
await Foo();
}
catch (ProtocolException ex)
{
// The exception will be caught because you've awaited
// the call in an async method.
}
}
//or//
public void DoFoo()
{
try
{
Foo().Wait();
}
catch (ProtocolException ex)
{
/* The exception will be caught because you've
waited for the completion of the call. */
}
}
Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.
This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.
Use the regular expression:
/^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/
Example:
function validateEmail(email) {
var re = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/;
return re.test(email);
}
It should allow only @ , . , _
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Center</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div style="text-align: center;">_x000D_
<div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).
Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.
Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.
If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:
Markup:
<a href="#" id="link1" >click</a>
Javascript:
$(document).ready(function(){
$("#link1").click(clickWithEvent); //Bind the click event to the link
});
function clickWithEvent(evt){
myFunc('p1', 'p2', 'p3');
function myFunc(p1,p2,p3){ //Defined as local function, but has access to evt
alert(evt.type);
}
}
Since the event ob
I got this error while deploying to Virgo. The solution was to add this to my bundle imports:
org.springframework.transaction.config;version="[3.1,3.2)",
I noticed in the Spring jars under META-INF there is a spring.schemas and a spring.handlers section, and the class that they point to (in this case org.springframework.transaction.config.TxNamespaceHandler) must be imported.
How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.
/**
* @param {domElement} input - The input element
* @param {string} typeData - The type of data to be return in the event object.
*/
function loadFileFromInput(input,typeData) {
var reader,
fileLoadedEvent,
files = input.files;
if (files && files[0]) {
reader = new FileReader();
reader.onload = function (e) {
fileLoadedEvent = new CustomEvent('fileLoaded',{
detail:{
data:reader.result,
file:files[0]
},
bubbles:true,
cancelable:true
});
input.dispatchEvent(fileLoadedEvent);
}
switch(typeData) {
case 'arraybuffer':
reader.readAsArrayBuffer(files[0]);
break;
case 'dataurl':
reader.readAsDataURL(files[0]);
break;
case 'binarystring':
reader.readAsBinaryString(files[0]);
break;
case 'text':
reader.readAsText(files[0]);
break;
}
}
}
function fileHandler (e) {
var data = e.detail.data,
fileInfo = e.detail.file;
img.src = data;
}
var input = document.getElementById('inputId'),
img = document.getElementById('imgId');
input.onchange = function (e) {
loadFileFromInput(e.target,'dataurl');
};
input.addEventListener('fileLoaded',fileHandler)
Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example
node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js
To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?
. In order to tell Vim to also look inside ~/.vim/vim-haml
you'll want to add
set runtimepath+=$HOME/.vim/vim-haml
to your ~/.vimrc
. You'll likely also want the following in your ~/.vimrc
to enable all the functionality provided by vim-haml.
filetype plugin indent on
syntax on
You can refer to the 'runtimepath'
and :filetype
help topics in Vim for more information.
This works for me:
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
var file = $('#YOURID > input[type="file"]');
file.value; // filename will be,
In Chrome, it will be something like C:\fakepath\FILE_NAME
or undefined
if no file was selected.
It is a limitation or intention that the browser does not reveal the file structure of the local machine.
Use re.sub
import re
regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'
Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)
regex = re.compile('[,\.!?]') #etc.
For anyone needing just top or left position, slight modifications to @Nickf's readable code does the trick.
function getTopPos(el) {
for (var topPos = 0;
el != null;
topPos += el.offsetTop, el = el.offsetParent);
return topPos;
}
and
function getLeftPos(el) {
for (var leftPos = 0;
el != null;
leftPos += el.offsetLeft, el = el.offsetParent);
return leftPos;
}
$("input[name='btnsubmit']").attr('disabled', true);
$('input[name="filphoto"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext)
{
case 'jpg':
case 'jpeg':
case 'png':
case 'bmp':
$("input[name='btnsubmit']").attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
$("input[name='btnsubmit']").attr('disabled', true);
this.value = '';
You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).
You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.
If you're going to use IDs, just try:
return $('#test2').attr('checked');
You don't have to add you own click
event handler at all. Just initialize the element with fancybox:
$(function() {
$('a[href="#modalMine"]').fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true // as MattBall already said, remove the comma
});
});
Done. Fancybox already binds a click
handler that opens the box. Have a look at the HowTo section.
Later if you want to open the box programmatically, raise the click
event on that element:
$('a[href="#modalMine"]').click();
Update: Ms SQL Server 2017+, Azure SQL Database
You can use: STRING_AGG
.
Usage is pretty simple for OP's request:
SELECT id, STRING_AGG(name, ', ') AS names
FROM some_table
GROUP BY id
Well my old non-answer got rightfully deleted (left in-tact below), but if anyone happens to land here in the future, there is good news. They have implimented STRING_AGG() in Azure SQL Database as well. That should provide the exact functionality originally requested in this post with native and built in support. @hrobky mentioned this previously as a SQL Server 2016 feature at the time.
--- Old Post: Not enough reputation here to reply to @hrobky directly, but STRING_AGG looks great, however it is only available in SQL Server 2016 vNext currently. Hopefully it will follow to Azure SQL Datababse soon as well..
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
same as a normal modulo 3.14 % 6.28 = 3.14
, just like 3.14%4 =3.14
3.14%2 = 1.14
(the remainder...)
You may start with Titanium for desktop dev. Also you may have a look at Chromium Embedded Framework. It's basically a web browser control based on chromium.
It's written in C++ so you can do all the low level OS stuff you want(Growl, tray icons, local file access, com ports, etc) in your container app, and then all the application logic and gui in html/javascript. It allows you to intercept any http request to either serve local resources or perform some custom action. For example, a request to http://localapp.com/SetTrayIconState?state=active could be intercepted by the container and then call the C++ function to update the tray icon.
It also allows you to create functions that can be called directly from JavaScript.
It's very difficult to debug JavaScript directly in CEF. There's no support for anything like Firebug.
You may also try AppJS.com (Helps to build Desktop Applications. for Linux, Windows and Mac using HTML, CSS and JavaScript)
Also, as pointed out by @Clint, the team at brackets.io (Adobe) created an awesome shell using Chromium Embedded Framework that makes it much easier to get started. It is called the brackets shell: github.com/adobe/brackets-shell Find out more about it here: clintberry.com/2013/html5-desktop-apps-with-brackets-shell
From API version 19 it is possible to call ActivityManager.clearApplicationUserData().
((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
Single elements of a tuple a
can be accessed -in an indexed array-like fashion-
via a[0]
, a[1]
, ... depending on the number of elements in the tuple.
If your tuple is a=(3,"a")
a[0]
yields 3
,a[1]
yields "a"
def tup():
return (3, "hello")
tup()
returns a 2-tuple.
In order to "solve"
i = 5 + tup() # I want to add just the three
you select the 3 by
tup()[0| #first element
so in total
i = 5 + tup()[0]
Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple
>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
You want to loop on the .Rows, and access the column for the row like q("column")
Just:
For Each q In dtDataTable.Rows
strDetail = q("Detail")
Next
Also make sure to check msdn doc for any class you are using + use intellisense
Try to set more reasonable logging level. Setting logging level to info
means that only log event at info
or higher level (warn
, error
and fatal
) are logged, that is debug
logging events are ignored.
log4j.logger.org.hibernate=info
or in XML version of log4j config file:
<logger name="org.hibernate">
<level value="info"/>
</logger>
See also log4j manual.
printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).
So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.
For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.
(This goes for everyone else reading this too.)
first of all you should define an .xml file and make keyboard UI in it:
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="12.50%p"
android:keyHeight="7%p">
<!--
android:horizontalGap="0.50%p"
android:verticalGap="0.50%p"
NOTE When we add a horizontalGap in pixels, this interferes with keyWidth in percentages adding up to 100%
NOTE When we have a horizontalGap (on Keyboard level) of 0, this make the horizontalGap (on Key level) to move from after the key to before the key... (I consider this a bug)
-->
<Row>
<Key android:codes="-5" android:keyLabel="remove" android:keyEdgeFlags="left" />
<Key android:codes="48" android:keyLabel="0" />
<Key android:codes="55006" android:keyLabel="clear" />
</Row>
<Row>
<Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left" />
<Key android:codes="50" android:keyLabel="2" />
<Key android:codes="51" android:keyLabel="3" />
</Row>
<Row>
<Key android:codes="52" android:keyLabel="4" android:keyEdgeFlags="left" />
<Key android:codes="53" android:keyLabel="5" />
<Key android:codes="54" android:keyLabel="6" />
</Row>
<Row>
<Key android:codes="55" android:keyLabel="7" android:keyEdgeFlags="left" />
<Key android:codes="56" android:keyLabel="8" />
<Key android:codes="57" android:keyLabel="9" />
</Row>
In this example you have 4 rows and in each row you have 3 keys. also you can put an icon in each key you want.
Then you should add xml tag in your activity UI like this:
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboardview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/white"
android:focusable="true"
android:focusableInTouchMode="true"
android:visibility="visible" />
Also in your .java activity file you should define the keyboard and assign it to a EditText:
CustomKeyboard mCustomKeyboard1 = new CustomKeyboard(this,
R.id.keyboardview1, R.xml.horizontal_keyboard);
mCustomKeyboard1.registerEditText(R.id.inputSearch);
This code asign inputSearch (which is a EditText) to your keyboard.
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class CustomKeyboard {
/** A link to the KeyboardView that is used to render this CustomKeyboard. */
private KeyboardView mKeyboardView;
/** A link to the activity that hosts the {@link #mKeyboardView}. */
private Activity mHostActivity;
/** The key (code) handler. */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
public final static int CodePrev = 55000;
public final static int CodeAllLeft = 55001;
public final static int CodeLeft = 55002;
public final static int CodeRight = 55003;
public final static int CodeAllRight = 55004;
public final static int CodeNext = 55005;
public final static int CodeClear = 55006;
@Override
public void onKey(int primaryCode, int[] keyCodes) {
// NOTE We can say '<Key android:codes="49,50" ... >' in the xml
// file; all codes come in keyCodes, the first in this list in
// primaryCode
// Get the EditText and its Editable
View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
if (focusCurrent == null
|| focusCurrent.getClass() != EditText.class)
return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
int start = edittext.getSelectionStart();
// Apply the key to the edittext
if (primaryCode == CodeCancel) {
hideCustomKeyboard();
} else if (primaryCode == CodeDelete) {
if (editable != null && start > 0)
editable.delete(start - 1, start);
} else if (primaryCode == CodeClear) {
if (editable != null)
editable.clear();
} else if (primaryCode == CodeLeft) {
if (start > 0)
edittext.setSelection(start - 1);
} else if (primaryCode == CodeRight) {
if (start < edittext.length())
edittext.setSelection(start + 1);
} else if (primaryCode == CodeAllLeft) {
edittext.setSelection(0);
} else if (primaryCode == CodeAllRight) {
edittext.setSelection(edittext.length());
} else if (primaryCode == CodePrev) {
View focusNew = edittext.focusSearch(View.FOCUS_BACKWARD);
if (focusNew != null)
focusNew.requestFocus();
} else if (primaryCode == CodeNext) {
View focusNew = edittext.focusSearch(View.FOCUS_FORWARD);
if (focusNew != null)
focusNew.requestFocus();
} else { // insert character
editable.insert(start, Character.toString((char) primaryCode));
}
}
@Override
public void onPress(int arg0) {
}
@Override
public void onRelease(int primaryCode) {
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeDown() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeUp() {
}
};
/**
* Create a custom keyboard, that uses the KeyboardView (with resource id
* <var>viewid</var>) of the <var>host</var> activity, and load the keyboard
* layout from xml file <var>layoutid</var> (see {@link Keyboard} for
* description). Note that the <var>host</var> activity must have a
* <var>KeyboardView</var> in its layout (typically aligned with the bottom
* of the activity). Note that the keyboard layout xml file may include key
* codes for navigation; see the constants in this class for their values.
* Note that to enable EditText's to use this custom keyboard, call the
* {@link #registerEditText(int)}.
*
* @param host
* The hosting activity.
* @param viewid
* The id of the KeyboardView.
* @param layoutid
* The id of the xml file containing the keyboard layout.
*/
public CustomKeyboard(Activity host, int viewid, int layoutid) {
mHostActivity = host;
mKeyboardView = (KeyboardView) mHostActivity.findViewById(viewid);
mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview
// balloons
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
// Hide the standard keyboard initially
mHostActivity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
return mKeyboardView.getVisibility() == View.VISIBLE;
}
/**
* Make the CustomKeyboard visible, and hide the system keyboard for view v.
*/
public void showCustomKeyboard(View v) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if (v != null)
((InputMethodManager) mHostActivity
.getSystemService(Activity.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {
mKeyboardView.setVisibility(View.GONE);
mKeyboardView.setEnabled(false);
}
/**
* Register <var>EditText<var> with resource id <var>resid</var> (on the
* hosting activity) for using this custom keyboard.
*
* @param resid
* The resource id of the EditText that registers to the custom
* keyboard.
*/
public void registerEditText(int resid) {
// Find the EditText 'resid'
EditText edittext = (EditText) mHostActivity.findViewById(resid);
// Make the custom keyboard appear
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
// NOTE By setting the on focus listener, we can show the custom
// keyboard when the edit box gets focus, but also hide it when the
// edit box loses focus
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
showCustomKeyboard(v);
else
hideCustomKeyboard();
}
});
edittext.setOnClickListener(new OnClickListener() {
// NOTE By setting the on click listener, we can show the custom
// keyboard again, by tapping on an edit box that already had focus
// (but that had the keyboard hidden).
@Override
public void onClick(View v) {
showCustomKeyboard(v);
}
});
// Disable standard keyboard hard way
// NOTE There is also an easy way:
// 'edittext.setInputType(InputType.TYPE_NULL)' (but you will not have a
// cursor, and no 'edittext.setCursorVisible(true)' doesn't work )
edittext.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
EditText edittext = (EditText) v;
int inType = edittext.getInputType(); // Backup the input type
edittext.setInputType(InputType.TYPE_NULL); // Disable standard
// keyboard
edittext.onTouchEvent(event); // Call native handler
edittext.setInputType(inType); // Restore input type
return true; // Consume touch event
}
});
// Disable spell check (hex strings look like words to Android)
edittext.setInputType(edittext.getInputType()
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
}
// NOTE How can we change the background color of some keys (like the
// shift/ctrl/alt)?
// NOTE What does android:keyEdgeFlags do/mean
Here's another solution that avoids the use of jObject.CreateReader()
, and instead creates a new JsonTextReader
(which is the behavior used by the default JsonCreate.Deserialze
method:
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
StringWriter writer = new StringWriter();
serializer.Serialize(writer, jObject);
using (JsonTextReader newReader = new JsonTextReader(new StringReader(writer.ToString())))
{
newReader.Culture = reader.Culture;
newReader.DateParseHandling = reader.DateParseHandling;
newReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
newReader.FloatParseHandling = reader.FloatParseHandling;
serializer.Populate(newReader, target);
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
I have looked at software protection in general for my own projects and the general philosophy is that complete protection is impossible. The only thing that you can hope to achieve is to add protection to a level that would cost your customer more to bypass than it would to purchase another license.
With that said I was just checking google for python obsfucation and not turning up a lot of anything. In a .Net solution, obsfucation would be a first approach to your problem on a windows platform, but I am not sure if anyone has solutions on Linux that work with Mono.
The next thing would be to write your code in a compiled language, or if you really want to go all the way, then in assembler. A stripped out executable would be a lot harder to decompile than an interpreted language.
It all comes down to tradeoffs. On one end you have ease of software development in python, in which it is also very hard to hide secrets. On the other end you have software written in assembler which is much harder to write, but is much easier to hide secrets.
Your boss has to choose a point somewhere along that continuum that supports his requirements. And then he has to give you the tools and time so you can build what he wants. However my bet is that he will object to real development costs versus potential monetary losses.
Just to show yet another option (for SQL Server 2008 and above):
($)
allows functions to be chained together without adding parentheses to control evaluation order:
Prelude> head (tail "asdf")
's'
Prelude> head $ tail "asdf"
's'
The compose operator (.)
creates a new function without specifying the arguments:
Prelude> let second x = head $ tail x
Prelude> second "asdf"
's'
Prelude> let second = head . tail
Prelude> second "asdf"
's'
The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:
Prelude> let third x = head $ tail $ tail x
Prelude> map third ["asdf", "qwer", "1234"]
"de3"
If we only use third once, we can avoid naming it by using a lambda:
Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
"de3"
Finally, composition lets us avoid the lambda:
Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
"de3"
There is additionally collections’ stream() util with Java 8
collection.forEach((temp) -> {
System.out.println(temp);
});
or
collection.forEach(System.out::println);
More information about Java 8 stream and collections for wonderers link
After Login
private void getFbInfo() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
Log.d(LOG_TAG, "fb json object: " + object);
Log.d(LOG_TAG, "fb graph response: " + response);
String id = object.getString("id");
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
String image_url = "http://graph.facebook.com/" + id + "/picture?type=large";
String email;
if (object.has("email")) {
email = object.getString("email");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender,birthday"); // id,first_name,last_name,email,gender,birthday,cover,picture.type(large)
request.setParameters(parameters);
request.executeAsync();
}
>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>>
You want to use a 'raw' string (denoted by the 'r' prefixing the replacement string), since raw strings to not treat the backslash specially.
If you are reading that text from a file or from the network.
You can achieve it by adding HTML tags to your text like mentioned
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
and then you can use the HTML class that processes HTML strings into displayable styled text.
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
Be careful with nulls and checking for inequality in sql server.
For example
select * from foo where bla <> 'something'
will NOT return records where bla is null. Even though logically it should.
So the right way to check would be
select * from foo where isnull(bla,'') <> 'something'
Which of course people often forget and then get weird bugs.
Through JavaScript
document.getElementById("test").style.display="none";
Through Jquery
$('#test').hide();
You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.
however it is not very well documented. I am trying something similar right now.
Put the APK file into the tools folder in the Android SDK and give the path to tools in the command prompt and use the command:
adb install "name".apk file
if you need a straight line shadow (like in bottom of toolbar) you can also use gradient xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="-90"
android:startColor="#19000000" <!-- black transparent -->
android:endColor="#00000000" /> <!-- full transparent -->
</shape>
hope this help some one
It's probably worth noting that Powershell v3 and up, contains a cmdlet called Invoke-WebRequest that has some curl-ish capabilities. The New-WebServiceProxy and Invoke-RestMethod cmdlets are probably worth mentioning too.
I'm not sure they will fit your needs or not, but although I'm not a Windows guy, I have to say I find the object approach PS takes, a lot easier to work with than utilities such as curl, wget etc. They may be worth taking a look at
You can also set background is transparent. So the button looks like fit your icon.
<ImageButton
android:id="@+id/Button01"
android:scaleType="fitcenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:background="@android:color/transparent"
android:src="@drawable/eye" />
Having my tslint
rules configuration here always replacing the line Object["values"](myObject)
with Object.values(myObject)
.
Two options if you have same issue:
(Object as any).values(myObject)
or
/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`
I had this issue after converting my Write-Host
cmdlets to Write-Information
and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.
Write-Host this is a good idea $here
Write-Information this is a good idea $here
<=BAD
This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...
Write-Information ("this is a good idea $here")
<=GOOD
SELECT DISTINCT OBJECT_NAME([id]),[text]
FROM syscomments
WHERE [id] IN (SELECT [id] FROM sysobjects WHERE xtype IN
('TF','FN','V','P') AND status >= 0) AND
([text] LIKE '%text to be search%' )
OBJECT_NAME([id]) --> Object Name (View,Store Procedure,Scalar Function,Table function name)
id (int) = Object identification number
xtype char(2) Object type. Can be one of the following object types:
FN = Scalar function
P = Stored procedure
V = View
TF = Table function
You are mixing pointers and arrays. If what you want is an array, then use an array:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
It's simpler if you modify your HTML a little bit:
<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />
<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />
then it's relatively simple
$(document).ready(function() {
$('#name').change(function() {
$('#firstname').val($('#name').val());
});
});
One reason could be that the chosen ABI does not fit to your system. For me, only arm64 is working.
tl;dr: REM
is the documented and supported way to embed comments in batch files.
::
is essentially a blank label that can never be jumped to, whereas REM
is an actual command that just does nothing. In neither case (at least on Windows 7) does the presence of redirection operators cause a problem.
However, ::
is known to misbehave in blocks under certain circumstances, being parsed not as a label but as some sort of drive letter. I'm a little fuzzy on where exactly but that alone is enough to make me use REM
exclusively. It's the documented and supported way to embed comments in batch files whereas ::
is merely an artifact of a particular implementation.
Here is an example where ::
produces a problem in a FOR
loop.
This example will not work in a file called test.bat
on your desktop:
@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
::echo hello>C:\Users\%username%\Desktop\text.txt
)
pause
While this example will work as a comment correctly:
@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
REM echo hello>C:\Users\%username%\Desktop\text.txt
)
pause
The problem appears to be when trying to redirect output into a file. My best guess is that it is interpreting ::
as an escaped label called :echo
.
You can try
$("your_div_id").remove();
or
$("your_div_id").html("");
"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"
You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.
Finally you'll need to add it as a using statement in whatever files you want to use it in.
<a href="http://www.google.com" class="ignore-click">Test</a>
with jQuery:
<script>
$(".ignore-click").click(function(){
return false;
})
</script>
with JavaScript
<script>
for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
event.preventDefault();
return false;
});
}
</script>
You assign class .ignore-click
to as many elements you like and clicks on those elements will be ignored
Another suggestion that helped me:
Here is what happent to me => My script was working once in 3 time I was loading the page and the error was the «google is not defined».
My function using the google map was in my jQuery document's ready function
$(function(){
//Here was my logic
})
I simply added this code to make sure it works:
$(function(){
$(window).load(function(){
//Here is my logic now
});
});
It works like a charm. If you want more details on difference between document ready and window load, here is a great post about it: window.onload vs $(document).ready()
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
Instead of Creating New Application Pool,You can go to your Existing application Pool->Right click Advance setting->Enable 32-bit Application-----Set to TRUE
I faced a similar issue and this is how I fixed it,
The problem is due to the conversion process from JSON to Java, one need to have the right run time jackson libraries for the conversion to happen correctly.
Add the following jars (through dependency or by downloading and adding to the classpath.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
This should fix the problem.
Complete Code:
function() {
$.ajax({
type: "POST",
url: "saveUserDetails.do",
data: JSON.stringify({
name: "Gerry",
ity: "Sydney"
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data) {
if (data.status == 'OK')
alert('Person has been added');
else
alert('Failed adding person: ' + data.status + ', ' + data.errorMessage);
}
and the controller signature looks like this:
@RequestMapping(value = "/saveUserDetails.do", method = RequestMethod.POST)
public @ResponseBody Person addPerson( @RequestBody final Person person) {
Hope this helps
The more efficient way I found in dealing with millions of folders and files is to capture directory listing through DOS command in some file and parse it. Once you have parsed data then you can do analysis and compute statistics.
Since no one mentioned, here is another one: Feign, which is used by Spring Cloud.
$http is a promise too, you can make it simpler:
return $q.all(tasks.map(function(d){
return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
}));
public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
A valid reason for wanting to free memory from any programm (java or not ) is to make more memory available to other programms on operating system level. If my java application is using 250MB I may want to force it down to 1MB and make the 249MB available to other apps.
Simply run:
ifconfig | grep ether | cut -d " " -f10
OR
ip a | grep ether | cut -d " " -f6
These two example commands will grep all lines with "ether" string and cut the mac address (that we need) following the number spaces (specified in the -f option) of the grepped portion.
Tested on different Linux flavors
In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date
, java.text.SimpleDateFormat
, it's a simple solution.
public static void main(String[] args) throws ParseException {
String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
Date f = new Date(fecha);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
fecha = sdf.format(f);
System.out.println(fecha);
}
If you want to bind to another property on the object:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
If you want to get a property on an ancestor:
{Binding Path=PathToProperty,
RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
or, shorter (this only works for OneWay bindings):
{TemplateBinding Path=PathToProperty}
I've spent 2 days attempting to convert layouts to ConstraintLayout
in the so-called "stable" release Android Studio 2.2 and I've not got ScrollView
to work in the designer. I'm not going to start down the route of adding constraints in XML for Views
that are further down the scroll. After all this is supposed to be a visual design tool.
And the number of rendering errors, stack overflows and theme issues I've had has led me to conclude that the whole ConstraintLayout
implementation is still riddled with bugs. Unless you are developing simple layouts then I'd leave it well alone until it's had a few more iterations at least.
That's 2 days I'm not going to get back.
Git has nothing to do with how you open/edit files in your project. Configuring the editor in git is only so that git internal things that require an editor (commit messages for example) can use your preferred editor.
If you just want to open files from the command line (cmd.exe) as if they were double clicked in the windows explorer, I think you can use start <filename>
.
std::string s(v.begin(), v.end());
Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)
For Mul, this was also helpful documentation to me - http://grokbase.com/t/mysql/mysql/9987k2ew41/key-field-mul-newbie-question
"MUL means that the key allows multiple rows to have the same value. That is, it's not a UNIque key."
For example, let's say you have two models, Post and Comment. Post has a has_many relationship with Comment. It would make sense then for the Comment table to have a MUL key(Post id) because many comments can be attributed to the same Post.
Try:
SELECT A.id FROM
(
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one IS NULL
) A
JOIN (
SELECT table1.id FROM table1
LEFT JOIN table2 ON table1.id = table2.user_two
WHERE table2.user_two IS NULL
) B
ON A.id = B.id
See Demo
Or you could use two LEFT JOINS
with aliases like:
SELECT table1.id FROM table1
LEFT JOIN table2 A ON table1.id = A.user_one
LEFT JOIN table2 B ON table1.id = B.user_two
WHERE A.user_one IS NULL
AND B.user_two IS NULL
See 2nd Demo
Note: I don't know the correct answer, but the below is just my personal speculation!
As has been mentioned a 0 before a number means it's octal:
04524 // octal, leading 0
Imagine needing to come up with a system to denote hexadecimal numbers, and note we're working in a C style environment. How about ending with h like assembly? Unfortunately you can't - it would allow you to make tokens which are valid identifiers (eg. you could name a variable the same thing) which would make for some nasty ambiguities.
8000h // hex
FF00h // oops - valid identifier! Hex or a variable or type named FF00h?
You can't lead with a character for the same reason:
xFF00 // also valid identifier
Using a hash was probably thrown out because it conflicts with the preprocessor:
#define ...
#FF00 // invalid preprocessor token?
In the end, for whatever reason, they decided to put an x after a leading 0 to denote hexadecimal. It is unambiguous since it still starts with a number character so can't be a valid identifier, and is probably based off the octal convention of a leading 0.
0xFF00 // definitely not an identifier!
The specific format is:
git commit --author="John Doe <[email protected]>" -m "Impersonation is evil."
Alt+enter is a 'fast solving problems option'. If you try it over class name after writing 'implements XXXX' it will suggest you to autoimplemnt that methods.
The correct shortcut for 'Organice imports' is Ctrl+Alt+O
You can find a really good Android Studio/IntellyJ shortcuts cheatsheet here: IntellyJ shortcut cheatsheet
------Hint-----
Give a try to Live Templates in Android Studio (It's like magic). Just press Ctrl+J
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
In Swift 3.0 :
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300));
imageView.image = UIImage(named:"Test.jpeg")
self.view.addSubview(imageView)
I've used below command to copy from local linux Centos 7 to AWS EC2.
scp -i user_key.pem file.txt [email protected]:/home/ec2-user
I believe the Number::Phone::US and Regexp::Common (particularly the source of Regexp::Common::URI::RFC2806) Perl modules could help.
The question should probably be specified in a bit more detail to explain the purpose of validating the numbers. For instance, 911 is a valid number in the US, but 911x isn't for any value of x. That's so that the phone company can calculate when you are done dialing. There are several variations on this issue. But your regex doesn't check the area code portion, so that doesn't seem to be a concern.
Like validating email addresses, even if you have a valid result you can't know if it's assigned to someone until you try it.
If you are trying to validate user input, why not normalize the result and be done with it? If the user puts in a number you can't recognize as a valid number, either save it as inputted or strip out undailable characters. The Number::Phone::Normalize Perl module could be a source of inspiration.
Right. Better to use a function:
CREATE OR REPLACE FUNCTION yyyymm() RETURNS text
LANGUAGE 'plpgsql' AS $$
DECLARE
retval text;
m integer;
BEGIN
retval := EXTRACT(year from current_timestamp);
m := EXTRACT(month from current_timestamp);
IF m < 10 THEN retval := retval || '0'; END IF;
RETURN retval || m;
END $$;
SELECT yyyymm();
DROP TABLE foo;
CREATE TABLE foo (
key int PRIMARY KEY,
colname text DEFAULT yyyymm()
);
INSERT INTO foo (key) VALUES (0);
SELECT * FROM FOO;
This gives me
key | colname
-----+---------
0 | 200905
Make sure you run createlang plpgsql
from the Unix command line, if necessary.
declare this
var intro;
outside of $(document).ready()
because, $(document).ready()
will hide your variable from global scope.
Code
var intro;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
Another way:
window.intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
window.intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
window.intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
window.intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
outside of DOM ready function (currently you've) will log undefined
, but within DOM ready it will give you true/ false.
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.I need to use it outside of DOM ready function
You can use following approach:
var intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
introCheck();
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function() {
if (this.checked) {
intro = true;
} else {
intro = false;
}
introCheck();
});
});
function introCheck() {
console.log(intro);
}
After change the value of intro
I called a function that will fire with new value of intro
.
Not sure if it's good approach but I just call this each time:
setContentView(R.layout.mainscreen);
my css
TR.gray-t {background:#949494;}
h3{
padding-top:3px;
font:bold 12px/2px Arial;
}
my html
<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>
I decrease the 2nd size in font.
padding-top
is used to fix the size in IE7.
The best "Pythonic" way to do this, exploiting the with
statement, is listed as Example #6 in PEP 343, which gives the background of the statement.
@contextmanager
def opened_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
Used as follows:
with opened_w_error("/etc/passwd", "a") as (f, err):
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")
I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:
home = System.getenv('HOME')
It helps to keep in mind that anything that works in pure Java will work in Gradle too.
How to total up used memory by process name:
Sometimes even looking at the biggest single processes there is still a lot of used memory unaccounted for. To check if there are a lot of the same smaller processes using the memory you can use a command like the following which uses awk to sum up the total memory used by processes of the same name:
ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n
e.g. output
9344 docker 1
9948 nginx: 4
22500 /usr/sbin/NetworkManager 1
24704 sleep 69
26436 /usr/sbin/sshd 15
34828 -bash 19
39268 sshd: 10
58384 /bin/su 28
59876 /bin/ksh 29
73408 /usr/bin/python 2
78176 /usr/bin/dockerd 1
134396 /bin/sh 84
5407132 bin/naughty_small_proc 1432
28061916 /usr/local/jdk/bin/java 7
Selenium doesn't currently offer API for this, but there are several ways to initiate an HTTP request in your test. It just depends what language you are writing in.
In Java for example, it might look like this:
// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
// continue with test
if (response.toString().equals("expected response"){
// do selenium
}
I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:
npm install @angular/fire firebase --save
In my app/app.module.ts:
...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule
],
providers: [
{ provide: SETTINGS, useValue: {} }
],
bootstrap: [AppComponent]
})
Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)
In my app/services/myService.ts I imported as:
import { AngularFirestore } from "@angular/fire/firestore";
For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!
So you want to:
Inspired by this answer, here's the adapted version of your script:
#!/usr/bin/env bash
different_user=deploy
useradd -m -s /bin/bash "$different_user"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo
echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
echo "Current user: $(id)"
echo "Current directory: $(pwd)"
EOF
echo
echo "Switched back to $(whoami)"
different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"
When you run it, you should get the following:
Current user: root
Current directory: /root
Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy
Switched back to root
deploy home directory: /home/deploy
To copy a sheet to a workbook called TARGET:
Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")
This will put the copied sheet xyz in the TARGET workbook after the sheet abc Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.
To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:
Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")
However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.
Hopefully this will give you something to go on though.
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
i know a way ny which you can call you private function to test in mockito
@Test
public void commandEndHandlerTest() throws Exception
{
Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
retryClientDetail_privateMethod.setAccessible(true);
retryClientDetail_privateMethod.invoke(yourclass.class, null);
}
If you really need then you can use i.e.
entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
Create your partial view something like:
@model YourModelType
<div>
<!-- HTML to render your object -->
</div>
Then in your view use:
@Html.Partial("YourPartialViewName", Model)
If you do not want a strongly typed partial view remove the @model YourModelType
from the top of the partial view and it will default to a dynamic
type.
Update
The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/
in the path below.
@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
I tried the solution of PowerAktar, but the AlertDialog and the Builder always kept seperate parts. So how to get the "true" AlertDialog?
I found my solutions in the show-Dialog: You write
ad.show();
to display the dialog. In the help of show it says "Creates a AlertDialog with the arguments supplied to this builder and Dialog.show()'s the dialog." So the dialog is finally created here. The result of the show()-Command is the AlertDialog itself. So you can use this result:
AlertDialog adTrueDialog;
adTrueDialog = ad.show();
With this adTrueDialog it is possible to cancel() ...
adTrueDialog.cancel()
or to execute a buttons command within the dialog:
Button buttonPositive = adTrueDialog.getButton(Dialog.BUTTON_POSITIVE);
buttonPositive.performClick();
The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your question about performance:
Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an optimization anecdote in which the array module comes out to be the winner (long read, but worth it).
On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.
TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use pyrex).
Everything that other solutions have, but with a little validation
// value = '675-805-714'
const validateNumberInput = (value) => {
let numberPattern = /\d+/g
let numbers = value.match(numberPattern)
if (numbers === null) {
return 0
}
return parseInt(numbers.join([]))
}
// 675805714
I was having "(...) unable to handle this request. http error 500" and found out it was from a require_once that was working locally, on a windows machine, with backslash (\) as separator for directories but when i uploaded to my server it stopped working. I changed it to forward slash (/) and now is ok.
require_once ( 'cards\cards.php' ); // **http error 500**
require_once ( 'cards/cards.php' ); // OK
Above answer's code need a slight change to remove the list complete, please check this piece of code.
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length;) {
select.options[i] = null;
length = select.options.length;
}
refresh the length and it will remove all the data from drop down list. Hope this will help someone.
ui router make your life easier! You can add it to you AngularJS application via injecting it into your applications...
ng-route
comes as part of the core AngularJS, so it's simpler and gives you fewer options...
Look at here to understand ng-route better: https://docs.angularjs.org/api/ngRoute
Also when using it, don't forget to use: ngView ..
ng-ui-router is different but:
https://github.com/angular-ui/ui-router but gives you more options....
many ways of getting this done, but finally it all depends on PHP version you are using. Here is summary of all solutions:
get PHP version:
echo phpinfo();
PHP 5.3+
$period = new DatePeriod(
new DateTime('2010-10-01'),
new DateInterval('P1D'),
new DateTime('2010-10-05')
);
PHP 4+
/**
* creating between two date
* @param string since
* @param string until
* @param string step
* @param string date format
* @return array
* @author Ali OYGUR <[email protected]>
*/
function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
PHP < 4
you should upgrade :)
Try this method. It is working for me.
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
TextView textView = (TextView) view;
((TextView) adapterView.getChildAt(0)).setTextColor(Color.RED);
((TextView) adapterView.getChildAt(0)).setTextSize(20);
Toast.makeText(this, textView.getText()+" Selected", Toast.LENGTH_SHORT).show();
}
Google has open sourced its excellent PDF rendering engine - PDFium - that it wrote with Foxit Software.
There is a C# nuget package called PdfiumViewer which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.
I have used it and was very impressed with the quality of the rendering.
PDFium works directly with streams so it doesn't require any data to be written to disk.
This is my example from a WinForms app
public void LoadPdf(byte[] pdfBytes)
{
var stream = new MemoryStream(pdfBytes);
LoadPdf(stream)
}
public void LoadPdf(Stream stream)
{
// Create PDF Document
var pdfDocument = PdfDocument.Load(stream);
// Load PDF Document into WinForms Control
pdfRenderer.Load(pdfDocument);
}
Edit: To get the pdfRenderer control in WinForm: Add the PdfiumViewer
NuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dll
file onto the Toolbox
window; A control called PdfRenderer
will be available to add:
There's two options:
Log Navigator (command-7 or view|navigators|log) and select your debug session.
"View | Show Debug Area" to view the NSLog output and interact with the debugger.
Here's a pic with both on. You wouldn't normally have both on, but I can only link one image per post! http://i.stack.imgur.com/4gG4P.png
Have a look at this jsfiddle.
The idea is to filter rows with function which will loop through words.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
EDIT: Note that case insensitive filtering cannot be achieved using :contains()
selector but luckily there's text()
function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1)
. Look at this jsfiddle.
The idea here is to install multiple ipython
kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs.
Since version 4.1.0, anaconda includes a special package nb_conda_kernels
that detects conda environments with notebook kernels and automatically registers them. This makes using a new python version as easy as creating new conda environments:
conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel
After a restart of jupyter notebook, the new kernels are available over the graphical interface. Please note that new packages have to be explicitly installed into the new environments. The Managing environments section in conda's docs provides further information.
Users who do not want to use nb_conda_kernels
or still use older versions of anaconda can use the following steps to manually register ipython kernels.
configure the python2.7
environment:
conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user
configure the python3.6
environment:
conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user
After that you should be able to choose between python2
and python3
when creating a new notebook in the interface.
Additionally you can pass the --name
and --display-name
options to ipython kernel install
if you want to change the names of your kernels. See ipython kernel install --help
for more informations.
conio.h
is a C
header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.
The #include <curses.h>
will give you almost all the functionalities that was provided in conio.h
nucurses need to be installed at the first place
In deb based Distros use
sudo apt-get install libncurses5-dev libncursesw5-dev
And in rpm based distros use
sudo yum install ncurses-devel ncurses
For getch()
class of functions, you can try this
fwrite($handle, "<br>"."\r\n");
Add this under
$password = $_POST['password'].PHP_EOL;
this. .
For JSON Post:
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
Non-JSON:
var stringContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("field1", "value1"),
new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
If you still have problems and are using nvm make sure to set the nvm node environment.
To select the latest version installed. To see versions use nvm list
.
nvm use node
sudo npm remove -g @angular/cli
sudo npm install -g @angular/cli
Or to install a specific version use:
sudo npm install -g @angular/[email protected]
If you dir permission errors use:
sudo npm install -g @angular/[email protected] --unsafe-perm
While Loop example in T-SQL which list current month's beginning to end date.
DECLARE @Today DATE= GETDATE() ,
@StartOfMonth DATE ,
@EndOfMonth DATE;
DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
SET @EndOfMonth = EOMONTH(GETDATE());
SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);
WHILE @StartOfMonth <= @EndOfMonth
BEGIN
INSERT INTO @DateList
VALUES ( @StartOfMonth );
SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
END;
SELECT DateLabel
FROM @DateList;
No need for jquery here, just a for
loop works:
var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
alert(substr[i]);
}
Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.
Two important pieces that are needed are:
$scope.entities = [{
"title": "foo",
"id": 1
}, {
"title": "bar",
"id": 2
}, {
"title": "baz",
"id": 3
}];
$scope.selected = [];
@datenstation had the correct concept. Here is a working example that uses CTE to cache variable's names:
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Here it goes an example:
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Hope it helps.
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
Aside from @Verhás István answer (which I like), I was expecting a one-liner for the question:
${project.reporting.outputDirectory}
resolves to target/site
in your project.
As stated above, something else is holding the files. Thing is that program doesnt look suspicious for us. I was trying to do a git pull from console, while having GitKraken opened. Closing GitKraken fixed the problem.
this is a solution using mshtml
IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);
Short version:
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar
If the conflict is about directories instead of files then replace touch
with mkdir
and rm
with rm -r
.
Note: the same procedure also work for the following situation:
$ svn st
! C foo
> local delete, incoming delete upon update
! C bar
> local delete, incoming delete upon update
Long version:
This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.
Should svn resolve
not work, for whatever reason, you can do the following:
Initial situation: Local files are missing, update is conflicting.
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
Recreate the conflicting files:
$ touch foo bar
If the conflict is about directories then replace touch
with mkdir
.
New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.
$ svn st
A + C foo
> local edit, incoming delete upon update
A + C bar
> local edit, incoming delete upon update
Revert the files to the state svn likes them (that means deleted):
$ svn revert foo bar
New situation: Local files not known to svn, update no longer conflicting.
$ svn st
? foo
? bar
Now we can delete the files:
$ rm foo bar
If the conflict is about directories then replace rm
with rm -r
.
svn no longer complains:
$ svn st
Done.
It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.
You can learn more about modules, handlers and IIS modes in the following blog post:
IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions
For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.
Here is a wget script in Python:
# From python cookbook, 2nd edition, page 487
import sys, urllib
def reporthook(a, b, c):
print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print url, "->", file
urllib.urlretrieve(url, file, reporthook)
print
/**
* Since swift 4 There is also native count, But it doesn't return Int
* NOTE: was: var count:Int { return self.characters.count }
* EXAMPLE: "abc".count//Output: 4
*/
extension String{
var count:Int {
return self.distance(from: self.startIndex, to: self.endIndex)
}
}
The proper way to install an MSI silently is via the msiexec.exe command line
as follows:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"
Quick explanation:
/L*V "C:\Temp\msilog.log"= verbose logging
/QN = run completely silently
/i = run install sequence
There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
I made a small modification on @jonathan.cone's one liner ( by adding .getFile()
) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
Change this:
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Content-Type, Last-Modified</param-value>
</init-param>
To this
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
I had to do this to get anything to work.
This is because of lack of Capability .... If you see the Inner Exception you will see this message
"Access is denied.
Access to speech functionality requires ID_CAP_SPEECH_RECOGNITION to be defined in the manifest."
So to get rid of this exception. turn on the capability for Speech Recognition from the Manifest file.
I had the same problem, and It solved my Problem. :)
You have downloaded Jersey 2 (which RI of JAX-RS 2). The tutorial you're referring to uses Jersey 1. Download Jersey 1.17.1 from (here), should be sufficient for you.
Jersey 1 uses com.sun.jersey
, and Jersey 2 uses org.glassfish.jersey
hence the exception.
Also note that also init-param
starting with com.sun.jersey
won't be recognized by Jersey 2.
Registering Resources and Providers in Jersey 2 contains additional info on how to register classes/instances in Jersey 2.
var divs = $("div[class*='alert-box']");
you can do it in mysql command instead of linux command.
1.login your mysql.
2.excute this in mysql command:
use DATABASE_NAME;
SET autocommit=0 ; source ABSOLUTE_PATH/TABLE_SQL_FILE.sql ; COMMIT ;
Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:
buttons: {
"Ja": function() {
$.post(a.href);
$(a). // code to remove the table row
$("#dialog").dialog("close");
},
"Nej": function() { $(this).dialog("close"); }
},
The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.
Only this way works for me as i have authorization in my request:
exports.hello = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true'); // vital
if (request.method === 'OPTIONS') {
// Send response to OPTIONS requests
response.set('Access-Control-Allow-Methods', 'GET');
response.set('Access-Control-Allow-Headers', 'Content-Type');
response.set('Access-Control-Max-Age', '3600');
response.status(204).send('');
} else {
const params = request.body;
const html = 'some html';
response.send(html)
} )};
String FILE_NAME = "C:\\Ajay\\TEST\\data_996KB.json";
File file = new File(FILE_NAME);
if((file.length()) <= (1048576)) {
System.out.println("file size is less than 1 mb");
}else {
System.out.println("file size is More than 1 mb");
}
Note: 1048576= (1024*1024)=1MB output : file size is less than 1 mb
TLDR: ssh-add ~/.ssh/yourkey
I've just worked through this problem.
And none of the other answers helped.
I did have a ./ssh/config with all the right stuff, also an earlier repository working fine (same bitbucket account, same key). Then I generated a deploy_key, and after that created a new repository.
After that could not clone the new repo.
I wish I knew how/why ssh agent was messing this up, but adding the key solved it. I mean adding the key in my local Ubuntu, not in bitbucket admin. The command is just
~/.ssh$ ssh-add myregualrkey
Hope this helps someone.
I got the same error and for the issue was that I was on VPN and I didn't realize that. After disconnecting the VPN and reconnecting the wifi resolved it.
You can use these links to download Visual Studio 2015
Community Edition:
And for anyone in the future who might be looking for the other editions here are the links for them as well:
Professional Edition:
Enterprise Edition:
I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).
Wikipedia points to the term Canonicalization.
A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.
The Unicode example made the most sense to me:
Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.
In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.
Though you have solved the problem, I just post the reason here for some others with the similar problem.
The reason is there's an space in your path(directory name VirtualBox VMs
) which will separate the command. So the error appears.
I installed mysql5 and mysql55 over macports. For me the mentioned files here are located at the following places:
(mysql55-server) /opt/local/etc/LaunchDaemons/org.macports.mysql55-server/org.macports.mysql55-server.plist
(mysql5) /opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist
So stopping for these works like this:
mysql55-server:
sudo launchctl unload -w /opt/local/etc/LaunchDaemons/org.macports.mysql55-server/org.macports.mysql55-server.plist
mysql5:
sudo launchctl unload -w /opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist
You can check if the service is still running with:
ps ax | grep mysql
Further you can check the log files in my case here:
mysql55-server
sudo tail -n 100 /opt/local/var/db/mysql55/<MyName>-MacBook-Pro.local.err
...
130213 08:56:41 mysqld_safe mysqld from pid file /opt/local/var/db/mysql55/<MyName>-MacBook-Pro.local.pid ended
mysql5:
sudo tail -n 100 /opt/local/var/db/mysql5/<MyName>-MacBook-Pro.local.err
...
130213 09:23:57 mysqld ended
So I ran into this problem recently. The issue was in the build/run configuration. Apparently android studio had chosen an activity in my project as the launch activity thus disregarding my choice in the manifest file.
Click on the module name just to the left of the run button and click on "Edit configurations..." Now make sure "Launch default Activity" is selected.
The funny thing when I got this error was that I could still launch the app with from the device and it starts with the preferred Activity. But launching from the IDE seemed impossible.
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
Legacy. List was originally defined to be functional-languages-looking:
1 :: 2 :: Nil // a list
list1 ::: list2 // concatenation of two lists
list match {
case head :: tail => "non-empty"
case Nil => "empty"
}
Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++
to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
Workaround: This is a problem we have observed too, in Windows Server 2012 R2. I haven't found a reason or solution yet. Here is my work around.
During installation while error is shown, go to Services.msc. Find the service which throws the error, then re-enter the password in the service's log-in information. Then, hit "retry" in setup. It works.
The error will not be shown for same user again. But will be shown for a different user.
So I need mkdirp()
today, and found the solutions on this page overly complicated.
Hence I wrote a fairly short snippet, that easily be copied in for others who
stumble upon this thread an wonder why we need so many lines of code.
mkdirp.h
#ifndef MKDIRP_H
#define MKDIRP_H
#include <sys/stat.h>
#define DEFAULT_MODE S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
/** Utility function to create directory tree */
bool mkdirp(const char* path, mode_t mode = DEFAULT_MODE);
#endif // MKDIRP_H
mkdirp.cpp
#include <errno.h>
bool mkdirp(const char* path, mode_t mode) {
// const cast for hack
char* p = const_cast<char*>(path);
// Do mkdir for each slash until end of string or error
while (*p != '\0') {
// Skip first character
p++;
// Find first slash or end
while(*p != '\0' && *p != '/') p++;
// Remember value from p
char v = *p;
// Write end of string at p
*p = '\0';
// Create folder from path to '\0' inserted at p
if(mkdir(path, mode) == -1 && errno != EEXIST) {
*p = v;
return false;
}
// Restore path to it's former glory
*p = v;
}
return true;
}
If you don't like const casting and temporarily modifying the string, just do a strdup()
and free()
it afterwards.
Try this:-
private String getWhoozitYs(){
StringBuffer sb = new StringBuffer();
boolean stop = generator.nextBoolean();
if(stop)
{
sb.append("y");
getWhoozitYs();
}
return sb.toString();
}
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()
# if you want to return run itself to be used later
return theclass.run
Change the end of comm system to:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}