This is because you have added a library and given its dependency on a module more than once.
In my case, I had added a library as a module and as a gradle dependency both.
Removing one source of adding library (I removed gradle dependency) solved my problem.
2016 Update
Use the Sharing Debugger to figure out what your problems are.
Make sure you're following the Facebook Sharing Best Practices.
Make sure you're using the Open Graph Markup correctly.
Original Answer
I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.
I recommend unlist
, which keeps the names.
unlist(df[1,])
a b c
1.0 2.0 2.6
is.vector(unlist(df[1,]))
[1] TRUE
If you don't want a named vector:
unname(unlist(df[1,]))
[1] 1.0 2.0 2.6
Just for completeness - it's worth noting that with Bootstrap 3, as per the docs, ensure the following structure in your page. It solved issues I was having with IE9 and v3.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- content -->
</body>
</html>
add below code to activity_main.xml file:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="@string/button" />
and just add the below method to the MainActivity.java file:
public void buttonClick(View view){
Intent i = new Intent(getApplicationContext()SendPhotos.class);
startActivity(i);
}
I'm aware to the fact that in the original question Jenkins pipeline was not mentioned, but if it is still applicable (using it), I find this solution easy to maintain and convenient.
This approach describe the settings required to compose a Jenkins pipeline that "polls" (list) dynamically all branches of a particular repository, which then lets the user run the pipeline with some specific branch when running a build of this job.
The assumptions here are:
First thing to do is to provide Jenkins credentials to connect (and "fetch") to the private repository in BitBucket. This can be done by creating an SSH key pair to "link" between the Jenkins (!!) user on the machine that hosts the Jenkins server and the (private) BitBucket repository.
First thing is to create an SSH key to the Jenkins user (which is the user that runs the Jenkins server - it is most likely created by default upon the installation):
guya@ubuntu_jenkins:~$ sudo su jenkins
[sudo] password for guya:
jenkins@ubuntu_jenkins:/home/guya$ ssh-keygen
The output should look similar to the following:
Generating public/private rsa key pair. Enter file in which to save the key
(/var/lib/jenkins/.ssh/id_rsa): Created directory '/var/lib/jenkins/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa. Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub. The key fingerprint is: SHA256:q6PfEthg+74QFwO+esLbOtKbwLG1dhtMLfxIVSN8fQY jenkins@ubuntu_jenkins The key's randomart image is: +---[RSA 2048]----+ | . .. o.E. | | . . .o... o | | . o.. o | | +.oo | | . ooX..S | |..+.Bo* . | |.++oo* o. | |..+*..*o | | .=+o==+. | +----[SHA256]-----+ jenkins@ubuntu_jenkins:/home/guya$
Settings --> Access keys --> Add key
.cat /var/lib/jenkins/.ssh/id_rsa.pub
jenkins
this "privilege".This can be done by adding a new SSH User name with private key to the Jenkins --> Credentials --> System --> Global Credentials --> Add credentials
.
jenkins
.~/.ssh/id_rsa
. This is the private key which start with the string:-----BEGIN RSA PRIVATE KEY-----
and ends with the string: -----END RSA PRIVATE KEY-----
. Note that this entire "block" should be copied-paste into the above section.Install the Git Parameter plugin that can be found in its official page here
The very minimum pipeline that is required to list (dynamically) all the branches of a given repository is as follows:
pipeline
{
agent any parameters
{
gitParameter branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH'
}
stages
{
stage("list all branches")
{
steps
{
git branch: "${params.BRANCH}", credentialsId: "SSH_user_name_with_private_key", url: "ssh://[email protected]:port/myRepository.git"
}
}
}
}
NOTES:
defaultValue
is set to master
so that if no branches exist - it will be displayed in the "drop list" of the pipeline.credentialsId
has the name of the credentials configured earlier.These days, everyone uses Pillow, a friendly PIL fork, over PIL.
Instead of: sudo pip install pil
Do: sudo pip install pillow
$ sudo apt-get install python-imaging
$ sudo -H pip install pillow
1.You don't need the @
prefix for attribute names any more:
http://api.jquery.com/category/selectors/attribute-selectors/:
Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.
2.Your selector queries radio buttons by name
, but that attribute is not defined in your HTML structure.
With the new Add-Ons for Google Drive, you can get code highlighting with the Code Pretty add-on.
I found this solution. If you go to a new view the function gets executed.
var app = angular.module('hoofdModule', ['ngRoute']);
app.controller('indexController', function ($scope, $window) {
$scope.$on('$viewContentLoaded', function () {
$window.scrollTo(0, 0);
});
});
for i, row in df.iterrows():
if <something>:
df.at[i, 'ifor'] = x
else:
df.at[i, 'ifor'] = y
uniqueId is custom attribute.
<a {...{ "uniqueId": `${item.File.UniqueId}` }} href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>
This should work
<option *ngFor="let title of titleArray"
[value]="title.Value"
[attr.selected]="passenger.Title==title.Text ? true : null">
{{title.Text}}
</option>
I'm not sure the attr.
part is necessary.
You are doing it right, so I guess something else is at fault (not export-ing COLUMNS ?).
A trick to debug these cases is to make a specialized command (a closure for programming language guys). Create a shell script named diff-columns doing:
exec /usr/bin/diff -x -y -w -p -W "$COLUMNS" "$@"
and just use
svn diff "$@" --diff-cmd diff-columns
This way your code is cleaner to read and more modular (top-down approach), and you can test the diff-columns code thouroughly separately (bottom-up approach).
$( document ).ready(function() {
$('#cmd').click(function() {
var options = {
pagesplit: true //include this in your code
};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
pdf.save('Menu.pdf');
});
});
});
Actually, You can achieve this with current typescript:
type Grow<T, A extends Array<T>> = ((x: T, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type GrowToSize<T, A extends Array<T>, N extends number> = { 0: A, 1: GrowToSize<T, Grow<T, A>, N> }[A['length'] extends N ? 0 : 1];
export type FixedArray<T, N extends number> = GrowToSize<T, [], N>;
Examples:
// OK
const fixedArr3: FixedArray<string, 3> = ['a', 'b', 'c'];
// Error:
// Type '[string, string, string]' is not assignable to type '[string, string]'.
// Types of property 'length' are incompatible.
// Type '3' is not assignable to type '2'.ts(2322)
const fixedArr2: FixedArray<string, 2> = ['a', 'b', 'c'];
// Error:
// Property '3' is missing in type '[string, string, string]' but required in type
// '[string, string, string, string]'.ts(2741)
const fixedArr4: FixedArray<string, 4> = ['a', 'b', 'c'];
EDIT (after a long time)
This should handle bigger sizes (as basically it grows array exponentially until we get to closest power of two):
type Shift<A extends Array<any>> = ((...args: A) => void) extends ((...args: [A[0], ...infer R]) => void) ? R : never;
type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
0: GrowExpRev<[...A, ...P[0]], N, P>,
1: GrowExpRev<A, N, Shift<P>>
}[[...A, ...P[0]][N] extends undefined ? 0 : 1];
type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
0: GrowExp<[...A, ...A], N, [A, ...P]>,
1: GrowExpRev<A, N, P>
}[[...A, ...A][N] extends undefined ? 0 : 1];
export type FixedSizeArray<T, N extends number> = N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T, T], N, [[T]]>;
display:none is the best thing to avoid takeup white space on the page
Just putting this here to give the solution I eventually came up with.
I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements.
Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was.
It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.
For example for all users (Builtin\Users), this method works fine - enjoy.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all the time. ResultSetImpl has a method called getUpdateCount()
which returns the value you are looking for.
This code sample should suffice:
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()
I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
if you are a sudo user i mean if you got sudo access:
sudo sh startup.sh
otherwise: sh startup.sh
But things is that you have to be on the bin directory of your server like
cd /home/nanofaroque/servers/apache-tomcat-7.0.47/bin
In Filter the response is of ServletResponse
rather than HttpServletResponse
. Hence do the cast to HttpServletResponse
.
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/login.jsp");
If using a context path:
httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");
Also don't forget to call return;
at the end.
You have to first escape the backslash because it's a literal (yielding \\
), and then escape it again because of the regular expression (yielding \\\\
). So, Try:
s.replaceAll("'", "\\\\'");
output:
You\'ll be totally awesome, I\'m really terrible
At CMD
prompt:
>ver
Microsoft Windows [Version 10.0.18362.476]
>dir \\.\pipe\\
I'd just use an if statement. In this case:
Type nodeType = node.GetType();
if (nodeType == typeof(CasusNodeDTO))
{
}
else ...
The other way to do this is:
if (node is CasusNodeDTO)
{
}
else ...
The first example is true for exact types only, where the latter checks for inheritance too.
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
There is a method in the String API for those "joining list of string" usecases, you don't even need Stream.
List<String> myStringIterable = Arrays.asList("baguette", "bonjour");
String myReducedString = String.join(",", myStringIterable);
// And here you obtain "baguette,bonjour" in your myReducedString variable
window.router = new VueRouter({
hashbang: false,
//abstract: true,
history: true,
mode: 'html5',
linkActiveClass: 'active',
transitionOnLoad: true,
root: '/'
});
and server is properly configured In apache you should write the url rewrite
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
BATCH LOAD - OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)
$apikey = "whatever-us99";
$list_id = "12ab34dc56";
$email1 = "[email protected]";
$fname1 = "Jack";
$lname1 = "Black";
$email2 = "[email protected]";
$fname2 = "Jill";
$lname2 = "Hill";
$auth = base64_encode( 'user:'.$apikey );
$data1 = array(
"apikey" => $apikey,
"email_address" => $email1,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname1,
'LNAME' => $lname1,
)
);
$data2 = array(
"apikey" => $apikey,
"email_address" => $email2,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $fname2,
'LNAME' => $lname2,
)
);
$json_data1 = json_encode($data1);
$json_data2 = json_encode($data2);
$array = array(
"operations" => array(
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data1
),
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_data2
)
)
);
$json_post = json_encode($array);
$ch = curl_init();
$curlopt_url = "https://us99.api.mailchimp.com/3.0/batches";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post);
print_r($json_post . "\n");
$result = curl_exec($ch);
var_dump($result . "\n");
print_r ($result . "\n");
Taken from a link posted in response to despesz' link.
Postgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of:
http://www.postgresql.org/docs/current/interactive/sql-grant.html
Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)."
This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES".
Also present is information about how GRANT functionalities compare to SQL standards.
Instead you can use a Popup that will be TopMost always, decorate it similar to a Window and to attach it completely with your Application handle the LocationChanged event of your main Window and set IsOpen property of Popup to false.
I hope you want something like this:
Window1 window;
private void Button_Click(object sender, RoutedEventArgs e)
{
window = new Window1();
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.Topmost = true;
this.LocationChanged+=OnLocationchanged;
window.Show();
}
private void OnLocationchanged(object sender, EventArgs e)
{
if(window!=null)
window.Close();
}
Hope it helps!!!
This is another way of tackling the problem if you have long strings (like file path names) and you only want to break the strings on certain characters (like slashes). You can insert Unicode Zero Width Space characters just before (or after) the slashes in the HTML.
More cleaner way using LINQ
var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);
You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.
However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table"
it emits code which actually creates a StringBuilder
behind the scenes and appends to it, so the end result is not that bad afterall.
But of course anyone looking at that code is bound to think that it is kind of retarded.
There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List
Here some basics points about scenarios and functions:
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
Loading the values in an array would be much faster:
Dim data(), dict As Object, r As Long
Set dict = CreateObject("Scripting.Dictionary")
data = ActiveSheet.UsedRange.Columns(1).Value
For r = 1 To UBound(data)
dict(data(r, some_column_number)) = Empty
Next
data = WorksheetFunction.Transpose(dict.keys())
You should also consider early binding for the Scripting.Dictionary:
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
Note that using a dictionary is way faster than Range.AdvancedFilter on large data sets.
As a bonus, here's a procedure similare to Range.RemoveDuplicates to remove duplicates from a 2D array:
Public Sub RemoveDuplicates(data, ParamArray columns())
Dim ret(), indexes(), ids(), r As Long, c As Long
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
If VarType(data) And vbArray Then Else Err.Raise 5, , "Argument data is not an array"
ReDim ids(LBound(columns) To UBound(columns))
For r = LBound(data) To UBound(data) ' each row '
For c = LBound(columns) To UBound(columns) ' each column '
ids(c) = data(r, columns(c)) ' build id for the row
Next
dict(Join$(ids, ChrW(-1))) = r ' associate the row index to the id '
Next
indexes = dict.Items()
ReDim ret(LBound(data) To LBound(data) + dict.Count - 1, LBound(data, 2) To UBound(data, 2))
For c = LBound(ret, 2) To UBound(ret, 2) ' each column '
For r = LBound(ret) To UBound(ret) ' each row / unique id '
ret(r, c) = data(indexes(r - 1), c) ' copy the value at index '
Next
Next
data = ret
End Sub
Check here : http://codex.wordpress.org/Template_Tags/get_posts
Note: The category parameter needs to be the ID of the category, and not the category name.
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Why don't you just use CopyToDataTable
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
take look at my example
<tocheading language="EN">
<subj-group>
<subject>Editors Choice</subject>
<subject>creative common</subject>
</subj-group>
</tocheading>
now how to check if creative common
is exist
tocheading/subj-group/subject/text() = 'creative common'
hope this help you
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
The error is due the fact that you are passing a wrong to strcat()
. Look at strcat()
's prototype:
char *strcat(char *dest, const char *src);
But you pass char
as the second argument, which is obviously wrong.
Use snprintf()
instead.
char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);
snprintf(str + len, sizeof str - len, "%c", tmp);
As commented by OP:
That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array
In that case, snprintf()
can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf()
is that it's more flexible to concatenate various types of data into a char buffer.
For example to concatenate a string, char and an int:
char str[1024];
ch tmp = '.';
int i = 5;
// Fill str here
snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);
user2540984, as well as many others have pointed out that you can try increasing your timeout settings. I myself faced a similar issue to this one and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This, however, did not help me a single bit; there was no apparent change in NGINX' timeout settings. After many hours of searching, I finally managed to solve my issue.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
This might not be the solution to your particular problem, but if anyone else notices that the timeout changes in /etc/nginx/nginx.conf don't do anything, I hope this answer helps!
io.js has an exit
and a beforeExit
event, which do what you want.
Per Debian policy, python
refers to Python 2 and python3
refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.
Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.
With recent Python 3, venv
is part of the standard library; with older versions, you might need to install python3-venv
or a similar package.
$HOME~$ python --version
Python 2.7.11
$HOME~$ python3 -m venv myenv
... stuff happens ...
$HOME~$ . ./myenv/bin/activate
(myenv) $HOME~$ type python # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python
(myenv) $HOME~$ python --version
Python 3.5.1
A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile
or similar.
Use -Xms1024m -Xmx1024m to control your heap size (1024m is only for demonstration, the exact number depends your system memory). Setting minimum and maximum heap size to the same is usually a best practice since JVM doesn't have to increase heap size at runtime.
Left shift <<
This is somehow easy and whenever you use the shift operator, it is always a bit-wise operation, so we can't use it with a double and float operation. Whenever we left shift one zero, it is always added to the least significant bit (LSB
).
But in right shift >>
we have to follow one additional rule and that rule is called "sign bit copy". Meaning of "sign bit copy" is if the most significant bit (MSB
) is set then after a right shift again the MSB
will be set if it was reset then it is again reset, means if the previous value was zero then after shifting again, the bit is zero if the previous bit was one then after the shift it is again one. This rule is not applicable for a left shift.
The most important example on right shift if you shift any negative number to right shift, then after some shifting the value finally reach to zero and then after this if shift this -1 any number of times the value will remain same. Please check.
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
Little bit late to the party but had some problems with getting something useful out from a ReadableStream
produced from a Odata $batch request using the Sharepoint Framework.
Had similar issues as OP, but the solution in my case was to use a different conversion method than .json()
. In my case .text()
worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.
For creating real UML class diagrams:
In Visual Studio 2013 Ultimate you can do this without any external tools.
You will have a empty UMLClassDiagram.classdiagram.
I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.
OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:
This error is caused by the fact that you basically generate a new table with your subquery for the FROM
command.
That's what a derived table
is, and as such, it needs to have an alias
(actually a name reference to it).
So given the following hypothetical query:
SELECT id, key1
FROM (
SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.key3 = 'some-value'
) AS tt
So, at the end, the whole subquery inside the FROM
command will produce the table that is aliased as tt
and it will have the following columns id
, key1
, key2
, key3
.
So, then with the initial SELECT
from that table we finally select the id
and key1
from the tt
.
If the iFrame's target and the containing document are on a different domain, the methods previously posted might not work, but there is a solution:
For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:
var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello world', 'http://b.example.org/');
To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:
window.addEventListener('message', receiver, false);
function receiver(e) {
if (e.origin == 'http://example.com') {
if (e.data == 'Hello world') {
e.source.postMessage('Hello', e.origin);
} else {
alert(e.data);
}
}
}
This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.
I have used this CSS code and it worked for me:
html {
height: 100%;
}
body {
background: #f6cb4a; /* Old browsers */
background: -moz-linear-gradient(top, #f2b600 0%, #f6cb4a 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f2b600), color-stop(100%,#f6cb4a)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* IE10+ */
background: linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2b600', endColorstr='#f6cb4a',GradientType=0 ); /* IE6-9 */
height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
width: 100%;
background-position: 0px 0px;
}
A related information is that you can create your own great gradients at http://www.colorzilla.com/gradient-editor/
/Sten
A common solution to this problem uses absolute positioning or cropped floats, but these are tricky in that they require extensive tuning if your columns change in number+size, and that you need to make sure your "main" column is always the longest. Instead, I'd suggest you use one of three more robust solutions:
display: flex
: by far the simplest & best solution and very flexible - but unsupported by IE9 and older.table
or display: table
: very simple, very compatible (pretty much every browser ever), quite flexible.display: inline-block; width:50%
with a negative margin hack: quite simple, but column-bottom borders are a little tricky.display:flex
This is really simple, and it's easy to adapt to more complex or more detailed layouts - but flexbox is only supported by IE10 or later (in addition to other modern browsers).
Example: http://output.jsbin.com/hetunujuma/1
Relevant html:
<div class="parent"><div>column 1</div><div>column 2</div></div>
Relevant css:
.parent { display: -ms-flex; display: -webkit-flex; display: flex; }
.parent>div { flex:1; }
Flexbox has support for a lot more options, but to simply have any number of columns the above suffices!
<table>
or display: table
A simple & extremely compatible way to do this is to use a table
- I'd recommend you try that first if you need old-IE support. You're dealing with columns; divs + floats simply aren't the best way to do that (not to mention the fact that multiple levels of nested divs just to hack around css limitations is hardly more "semantic" than just using a simple table). If you do not wish to use the table
element, consider css display: table
(unsupported by IE7 and older).
Example: http://jsfiddle.net/emn13/7FFp3/
Relevant html: (but consider using a plain <table>
instead)
<div class="parent"><div>column 1</div><div>column 2</div></div>
Relevant css:
.parent { display: table; }
.parent > div {display: table-cell; width:50%; }
/*omit width:50% for auto-scaled column widths*/
This approach is far more robust than using overflow:hidden
with floats. You can add pretty much any number of columns; you can have them auto-scale if you want; and you retain compatibility with ancient browsers. Unlike the float solution requires, you also don't need to know beforehand which column is longest; the height scales just fine.
KISS: don't use float hacks unless you specifically need to. If IE7 is an issue, I'd still pick a plain table with semantic columns over a hard-to-maintain, less flexible trick-CSS solution any day.
By the way, if you need your layout to be responsive (e.g. no columns on small mobile phones) you can use a @media
query to fall back to plain block layout for small screen widths - this works whether you use <table>
or any other display: table
element.
display:inline block
with a negative margin hack.Another alternative is to use display:inline block
.
Example: http://jsbin.com/ovuqes/2/edit
Relevant html: (the absence of spaces between the div
tags is significant!)
<div class="parent"><div><div>column 1</div></div><div><div>column 2</div></div></div>
Relevant css:
.parent {
position: relative; width: 100%; white-space: nowrap; overflow: hidden;
}
.parent>div {
display:inline-block; width:50%; white-space:normal; vertical-align:top;
}
.parent>div>div {
padding-bottom: 32768px; margin-bottom: -32768px;
}
This is slightly tricky, and the negative margin means that the "true" bottom of the columns is obscured. This in turn means you can't position anything relative to the bottom of those columns because that's cut off by overflow: hidden
. Note that in addition to inline-blocks, you can achieve a similar effect with floats.
TL;DR: use flexbox if you can ignore IE9 and older; otherwise try a (css) table. If neither of those options work for you, there are negative margin hacks, but these can cause weird display issues that are easy to miss during development, and there are layout limitations you need to be aware of.
<?php foreach($this->models as /** @var Model_Object_WheelModel */ $model): ?>
<?php
// Type hinting now works:
$model->getImage();
?>
<?php endforeach; ?>
Most certainly, export JAVA_HOME=/usr/bin/java
is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home
.
Hmm, this seems to be a bit of an old question, but since I've been messing about with Doxygen configuration last few days, while my head's still full of current info let's have a stab at it -
I think the previous answers almost have it:
The missing option is to add COLLABORATION_GRAPH = YES
in the Doxyfile. I assume you can do the equivalent thing somewhere in the doxywizard GUI (I don't use doxywizard).
So, as a more complete example, typical "Doxyfile" options related to UML output that I tend to use are:
EXTRACT_ALL = YES
CLASS_DIAGRAMS = YES
HIDE_UNDOC_RELATIONS = NO
HAVE_DOT = YES
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
UML_LOOK = YES
UML_LIMIT_NUM_FIELDS = 50
TEMPLATE_RELATIONS = YES
DOT_GRAPH_MAX_NODES = 100
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = YES
These settings will generate both "inheritance" (CLASS_GRAPH=YES
) and "collaboration" (COLLABORATION_GRAPH=YES
) diagrams.
Depending on your target for "deployment" of the doxygen output, setting DOT_IMAGE_FORMAT = svg
may also be of use. With svg output the diagrams are "scalable" instead of the fixed resolution of bitmap formats such as .png. Apparently, if viewing the output in browsers other than IE, there is also INTERACTIVE_SVG = YES
which will allow "interactive zooming and panning" of the generated svg diagrams. I did try this some time ago, and the svg output was very visually attractive, but at the time, browser support for svg was still a bit inconsistent, so hopefully that situation may have improved lately.
As other comments have mentioned, some of these settings (DOT_GRAPH_MAX_NODES
in particular) do have potential performance impacts, so YMMV.
I tend to hate "RTFM" style answers, so apologies for this sentence, but in this case the Doxygen documentation really is your friend, so check out the Doxygen docs on the above mentioned settings- last time I looked you can find the details at http://www.doxygen.nl/manual/config.html.
That's what I do in Opencv to detect focus quality in a region:
Mat grad;
int scale = 1;
int delta = 0;
int ddepth = CV_8U;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
Sobel(matFromSensor, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
/// Gradient Y
Sobel(matFromSensor, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Scalar mu, sigma;
cv::meanStdDev(grad, /* mean */ mu, /*stdev*/ sigma);
focusMeasure = mu.val[0] * mu.val[0];
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
Anything you can do in regular old ANSI C can be done in Objective-C.
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
Upgrade to latest Angular 5
Angular Dep packages:
npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save
Other packages that are installed by the angular cli
npm install --save core-js@latest rxjs@latest zone.js@latest
Angular Dev packages:
npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest
Types Dev packages:
npm install --save-dev @types/{jasmine,jasminewd2,node}@latest
Other packages that are installed as dev dev by the angular cli:
npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest
Install the latest supported version used by the Angular cli (don't do @latest):
npm install --save-dev [email protected]
Rename file angular-cli.json to .angular-cli.json and update the content:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "project3-example"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
This is a pretty old question, and while looking for Git libraries, I found one that was made this year (2013) called Gittle.
It worked great for me (where the others I tried were flaky), and seems to cover most of the common actions.
Some examples from the README:
from gittle import Gittle
# Clone a repository
repo_path = '/tmp/gittle_bare'
repo_url = 'git://github.com/FriendCode/gittle.git'
repo = Gittle.clone(repo_url, repo_path)
# Stage multiple files
repo.stage(['other1.txt', 'other2.txt'])
# Do the commit
repo.commit(name="Samy Pesse", email="[email protected]", message="This is a commit")
# Authentication with RSA private key
key_file = open('/Users/Me/keys/rsa/private_rsa')
repo.auth(pkey=key_file)
# Do push
repo.push()
With eager evaluation, variables essentially turn into their values any time you look at them (to paraphrase). That said, Python does have built-in namespaces. For example, locals() will return a dictionary mapping a function's variables' names to their values, and globals() does the same for a module. Thus:
for name, value in globals().items():
if value is unknown_variable:
... do something with name
Note that you don't need to import anything to be able to access locals() and globals().
Also, if there are multiple aliases for a value, iterating through a namespace only finds the first one.
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
Don't forget, if you are also on a machine where you haven't set up heroku before
heroku keys:add
Or you won't be able to push or pull to the repo.
Ternary Operator is basically shorthand for if/else statement. We can use to reduce few lines of code and increases readability.
Your code looks cleaner to me. But we can add more cleaner way as follows-
$test = (empty($address['street2'])) ? 'Yes <br />' : 'No <br />';
Another way-
$test = ((empty($address['street2'])) ? 'Yes <br />' : 'No <br />');
Note- I have added bracket to whole expression to make it cleaner. I used to do this usually to increase readability. With PHP7 we can use Null Coalescing Operator / php 7 ?? operator for better approach. But your requirement it does not fit.
Use the Oracle documentation and search for keyword "trigger" in your browser.
This approach should work with other metadata type questions.
Make all parent element with 100% width and 100% height and use display: table; and display:table-cell;, check the working sample.
<!DOCTYPE html>
<html>
<head>
<style>
html,body{height: 100%;}
body{width: 100%;}
</style>
</head>
<body style="display: table; background-color: #ff0000; ">
<div style="display: table-cell; vertical-align: middle; text-align: center;">
<button type="button" style="text-align: center;" class="btn btn-info">
Discover More
</button>
</div>
</body>
</html>
Use $dec = $null
From the documentation:
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.
As Alexander Jank mentioned <base href="http://www.example.com/default/">
is great. When using sub-domains e.g. default.example.com
base works great, because the JS and CSS loads from the said sub-domain and is accessible to both default.example.com
and example.com/default
When using the root path, and your JS and CSS files are located in example.com/css
, or example.com/js
, then the subdomain has no access and the root of the subdomain is not accessible, except using the base.
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
To copy a list you can use list(a)
or a[:]
. In both cases a new object is created.
These two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:
>>> a = [[1,2],[3],[4]]
>>> b = a[:]
>>> c = list(a)
>>> c[0].append(9)
>>> a
[[1, 2, 9], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>> b
[[1, 2, 9], [3], [4]]
>>>
If you want a full copy of your objects you need copy.deepcopy
>>> from copy import deepcopy
>>> a = [[1,2],[3],[4]]
>>> b = a[:]
>>> c = deepcopy(a)
>>> c[0].append(9)
>>> a
[[1, 2], [3], [4]]
>>> b
[[1, 2], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>>
You have to actually call some method to create the directories. Just creating a file
object will not create the corresponding file or directory on the file system.
You can use File#mkdirs()
method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir()
and File#mkdirs()
is that, the later will create any intermediate directory if it does not exist.
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
={10,}
matches =
that is repeated 10 or more times.
find_elements_by_xpath("//*[@class='class name']")
is a great solution
This post contains a brilliant trick to detect where the cascade problem is:
Try to replace on Cascade at the time with Cascade.None()
until you do not get the error and then you have detected the cascade causing the problem.
Then solve the problem either by changing the original cascade to something else or using Tom Anderson answer.
To disable swap files from within vim, type
:set noswapfile
To disable swap files permanently, add the below to your ~/.vimrc
file
set noswapfile
For more details see the Vim docs on swapfile
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.
import codecs
decode_hex = codecs.getdecoder("hex_codec")
# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]
# for a string
string = decode_hex(string)[0]
DataRow has a method that is called IsNull()
that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.
DataRow["col"]==null
will allways be false
.
use
DataRow r;
if (r.IsNull("col")) ...
instead.
I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:
The solution I came up with is the following:
//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10; // NUMBER - Input Your Number here
var n:int = r * 10; // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; // NUMBER - Re-assemble the number
trace("ORG No: " + r);
trace("NEW No: " + d);
Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.
Good Luck!
A simple way to check if a key exists is to use in
:
if (key in obj) {
// Do something
} else {
// Create key
}
const obj = {
0: 'abc',
1: 'def'
}
const hasZero = 0 in obj
console.log(hasZero) // true
I used:
TableLayout tablelayout = (TableLayout) view.findViewById(R.id.table);
tablelayout.setColumnShrinkable(1,true);
it worked for me. 1 is the number of column.
Just use the killall command:
killall taskname
for more info and more advanced options, type "man killall".
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
In SQL, NULL = NULL is false, you usually have to use IS NULL:
SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words
But, if you want the number of rows, you should just use count(id)
since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.
If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.
But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.
document.write()
will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body>
tag and the DOM is ready, you can't use document.write()
anymore.
I wouldn't say using document.write()
is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write()
to accomplish the task. Look at how Google analytics gets injected into most websites.
After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>
):
Using innerHTML on a node:
var node = document.getElementById('node-id');
node.innerHTML('<p>some dynamic html</p>');
Using DOM methods:
var node = document.getElementById('node-id');
var newNode = document.createElement('p');
newNode.appendChild(document.createTextNode('some dynamic html'));
node.appendChild(newNode);
Using the DOM API methods might be the purist way to do stuff, but innerHTML
has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.
Note: The <script>
will have to be inside your <body>
tag for this to work.
Here's a slightly more concise version of @vbem's solution:
from datetime import datetime as dt
dt.utcnow().astimezone().tzinfo
The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc)
with datetime.datetime.utcnow()
. For brevity, I also aliased datetime.datetime
as dt
.
For my purposes, I want the UTC offset in seconds. Here's what that looks like:
dt.utcnow().astimezone().utcoffset().total_seconds()
Change the lines
if(nodeValue!=null)
fop.write(nodeValue.getBytes());
fop.flush();
to
if(nodeValue!=null) {
fop.write(nodeValue.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
fop.flush();
Update to address your edit:
In order to write each word on a different line, you need to split up your input string and then write each word separately.
private static void GetText(String nodeValue) throws IOException {
if(!file3.exists()) {
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null)
for(final String s : nodeValue.split(" ")){
fop.write(s.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
}
fop.flush();
fop.close();
}
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
In windows for me it kept saying "id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.
This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135
This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")
My Visual Studio 2015 RTM was also very slow using ReSharper 9.1.2, but it has worked fine since I upgraded to 9.1.3 (see ReSharper 9.1.3 to the Rescue). Perhaps a cue.
One more cue. A ReSharper 9.2 version was made available to:
refines integration with Visual Studio 2015 RTM, addressing issues discovered in versions 9.1.2 and 9.1.3
Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.
Another thing you mentioned in your question:
Object *myObject = new Object;
How does it work? It creates pointer of Object
type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new
), you also have to free memory manually, that means in code you should have:
delete myObject;
This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.
And now some introduction is over and go back to question.
You can use pointers instead of objects to get better performance while transferring data between function.
Take a look, you have std::string
(it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...)
which can be declarated in different ways:
void foo(std::string xml);
In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.void foo(std::string* xml);
In this case you will pass pointer to object, same speed as passing size_t
variable, however this declaration has error prone, because you can pass NULL
pointer or invalid pointer. Pointers usually used in C
because it doesn't have references.void foo(std::string& xml);
Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).void foo(const std::string* xml);
Here is the same as second, just pointer value cannot be changed.void foo(const std::string& xml);
Here is the same as third, but object value cannot be changed.What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new
or regular).
Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new
you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string
is also container, some guys forgot it :)
Create a view. Yes, in the view creation statement, you will have to list each...and...every...field...by...name.
Once.
Then just select * from viewname
after that.
You can find the first and last visible children of the recycle view and check if the view you're looking for is in the range:
var visibleChild: View = rv.getChildAt(0)
val firstChild: Int = rv.getChildAdapterPosition(visibleChild)
visibleChild = rv.getChildAt(rv.childCount - 1)
val lastChild: Int = rv.getChildAdapterPosition(visibleChild)
println("first visible child is: $firstChild")
println("last visible child is: $lastChild")
Two slices can be concatenated using append
method in the standard golang library. Which is similar to the variadic
function operation. So we need to use ...
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3}
y := []int{4, 5, 6}
z := append([]int{}, append(x, y...)...)
fmt.Println(z)
}
output of the above code is: [1 2 3 4 5 6]
API keys are just one way of authenticating users of web services.
The function supports the dry principle - ensuring that you don't hard code urls throughout your app. A url should be defined in one place, and only one place - your url conf. After that you're really just referencing that info.
Use reverse()
to give you the url of a page, given either the path to the view, or the page_name parameter from your url conf. You would use it in cases where it doesn't make sense to do it in the template with {% url 'my-page' %}
.
There are lots of possible places you might use this functionality. One place I've found I use it is when redirecting users in a view (often after the successful processing of a form)-
return HttpResponseRedirect(reverse('thanks-we-got-your-form-page'))
You might also use it when writing template tags.
Another time I used reverse()
was with model inheritance. I had a ListView on a parent model, but wanted to get from any one of those parent objects to the DetailView of it's associated child object. I attached a get__child_url()
function to the parent which identified the existence of a child and returned the url of it's DetailView using reverse()
.
Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.
Try this command
npm install github:[Organisation]/[Repository]#[master/BranchName] -g
this command worked for me.
npm install github:BlessCSS/bless#3.x -g
Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. (as in Django docs)
A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.
Just like the way you added this question on Stack Overflow and a dynamic page was generated and when you see in the address bar you will see your question title with "-" in place of the spaces. That's exactly the job of a slug field.
The title entered by you was something like this -> What is a “slug” in Django?
On storing it into a slug field it becomes "what-is-a-slug-in-django" (see URL of this page)
Polished version + case ignoring support:
public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
if (string.IsNullOrWhiteSpace(str) ||
string.IsNullOrWhiteSpace(substr))
{
throw new ArgumentException("String or substring is not specified.");
}
var indexes = new List<int>();
int index = 0;
while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
{
indexes.Add(index++);
}
return indexes.ToArray();
}
Inject the request object into the controller using Laravel's magic injection and then access the function non-statically. Laravel will automatically inject concrete dependencies into autoloaded classes
class MyController()
{
protected $request;
public function __construct(\Illuminate\Http\Request $request)
{
$this->request = $request;
}
public function myFunc()
{
$input = $this->request->all();
}
}
Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:
BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib
MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)
The differences between Model()
and Model.objects.create()
are the following:
INSERT vs UPDATE
Model.save()
does either INSERT or UPDATE of an object in a DB, while Model.objects.create()
does only INSERT.
Model.save()
does
UPDATE If the object’s primary key attribute is set to a value that evaluates to True
INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).
Existing primary key
If primary key attribute is set to a value and such primary key already exists, then Model.save()
performs UPDATE, but Model.objects.create()
raises IntegrityError
.
Consider the following models.py:
class Subject(models.Model):
subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
name = models.CharField(max_length=255)
max_marks = models.PositiveIntegerField()
Insert/Update to db with Model.save()
physics = Subject(subject_id=1, name='Physics', max_marks=100)
physics.save()
math = Subject(subject_id=1, name='Math', max_marks=50) # Case of update
math.save()
Result:
Subject.objects.all().values()
<QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
Insert to db with Model.objects.create()
Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
IntegrityError: UNIQUE constraint failed: m****t.subject_id
Explanation: In the example, math.save()
does an UPDATE (changes name
from Physics to Math, and max_marks
from 100 to 50), because subject_id
is a primary key and subject_id=1
already exists in the DB. But Subject.objects.create()
raises IntegrityError
, because, again the primary key subject_id
with the value 1
already exists.
Forced insert
Model.save()
can be made to behave as Model.objects.create()
by using force_insert=True
parameter: Model.save(force_insert=True)
.
Return value
Model.save()
return None
where Model.objects.create()
return model instance i.e. package_name.models.Model
Conclusion: Model.objects.create()
does model initialization and performs save()
with force_insert=True
.
Excerpt from the source code of Model.objects.create()
def create(self, **kwargs):
"""
Create a new object with the given kwargs, saving it to the database
and returning the created object.
"""
obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=self.db)
return obj
For more details follow the links:
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
You could run jconsole
(included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.
Array.prototype.combs = function(num) {
var str = this,
length = str.length,
of = Math.pow(2, length) - 1,
out, combinations = [];
while(of) {
out = [];
for(var i = 0, y; i < length; i++) {
y = (1 << i);
if(y & of && (y !== of))
out.push(str[i]);
}
if (out.length >= num) {
combinations.push(out);
}
of--;
}
return combinations;
}
you must change your model name first letter capital. in localhost small letter work properly but online this not work. for exa:
common_model.php
replaced it to
Common_model.php
Your code is correct. Just put them inside the <VirtualHost *:443>
Example:
<VirtualHost *:443>
SSLEnable
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>
Yes, I think for Windows users you need to change all the python3
calls to python
to solve your original error. This change will run the Python version set in your current environment. If you need to keep this call as it is (aka python3
) because you are working in cross-platform or for any other reason, then a work around is to create a soft link. To create it, go to the folder that contains the Python executable and create the link. For example, this worked in my case in Windows 10 using mklink:
cd C:\Python3
mklink python3.exe python.exe
Use a (soft) symbolic link in Linux:
cd /usr/bin/python3
ln -s python.exe python3.exe
Using code::blocks , I have solved this error by doing :
workspace properties > build target > build target files
and checking every project file.
Use JQuery Hover
to add/remove class or style on Hover:
$( "mah div" ).hover(
function() {
$( this ).css("background-color","red");
}, function() {
$( this ).css("background-color",""); //to remove property set it to ''
}
);
Explain what video describe to resolve problem
After Changing Password of root (Mysql Account). Accessing to phpmyadmin page will be denied because phpMyAdmin use root/''(blank) as default username/password. To resolve this problem, you need to reconfig phpmyadmin. Edit file config.inc.php in folder %wamp%\apps\phpmyadmin4.1.14 (Not in %wamp%)
$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
If you have more than 1 DB server, add "i++" to file and continue add new config as above
delay()
doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout
which others have mentioned.
The purpose of jQuery's delay()
is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250);
will make the element fade in after 3 seconds.
Everything as @user1341296 said, plus...
You better not to change /etc/mysql/my.cnf
Instead you want to create new file/etc/mysql/conf.d/ext.cnf
(any name, but extension should be cnf
)
And put in it your change:
[mysqld]
datadir=/vagrant/mq/mysql
In this way
The answer to this one is actually wrong.
Auto filling in the value (auto_now/auto_now_add isn't the same as default). The default value will actually be what the user sees if its a brand new object. What I typically do is:
date = models.DateTimeField(default=datetime.now, editable=False,)
Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field name
read_only = 'date'
Again, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise. There is certainly a difference however between setting a default value and implementing the auto_add which is key here. Test it out!
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return Comment.objects.get(pk=id)
except Comment.DoesNotExist:
return False
Spark2 is based on Spark which is now no longer maintained. Cluster is its successor, and it has some cool features, like spawning one worker process per CPU core and respawning dead workers.
A revert commit is just like any other commit in git. Meaning, you can revert it, as in:
git revert 648d7d808bc1bca6dbf72d93bf3da7c65a9bd746
That obviously only makes sense once the changes were pushed, and especially when you can't force push onto the destination branch (which is a good idea for your master branch). If the change has not been pushed, just do cherry-pick, revert or simply remove the revert commit as per other posts.
In our team, we have a rule to use a revert on Revert commits that were committed in the main branch, primarily to keep the history clean, so that you can see which commit reverts what:
7963f4b2a9d Revert "Revert "OD-9033 parallel reporting configuration"
"This reverts commit a0e5e86d3b66cf206ae98a9c989f649eeba7965f.
...
a0e5e86d3b6 Revert "OD-9055 paralel reporting configuration"
This reverts commit 648d7d808bc1bca6dbf72d93bf3da7c65a9bd746.
...
Merge pull request parallel_reporting_dbs to master* commit
'648d7d808bc1bca6dbf72d93bf3da7c65a9bd746'
This way, you can trace the history and figure out the whole story, and even those without the knowledge of the legacy could work it out for themselves. Whereas, if you cherry-pick or rebase stuff, this valuable information is lost (unless you include it in the comment).
Obviously, if a commit reverted and re-reverted more than once that becomes quite messy.
late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws
For example:
data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()
//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns
SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'
About the window.location.hash
property:
Return the anchor part of a URL.
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
These answers all collect shallow size information. I suspect that visitors to this question will end up here looking to answer the question, "How big is this complex object in memory?"
There's a great answer here: https://goshippo.com/blog/measure-real-size-any-python-object/
The punchline:
import sys
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
Used like so:
In [1]: get_size(1)
Out[1]: 24
In [2]: get_size([1])
Out[2]: 104
In [3]: get_size([[1]])
Out[3]: 184
If you want to know Python's memory model more deeply, there's a great article here that has a similar "total size" snippet of code as part of a longer explanation: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
I was facing the same issue with jenkins ssh slave 'jenkinsci/ssh-slave'. However, my case was a bit complicated because it was necessary to pass an argument which contained spaces. I've managed to do it like below (entrypoint in dockerfile is in exec form):
command: ["some argument with space which should be treated as one"]
It's called a favicon. It is inserted like this:
<link rel="shortcut icon" href="favicon.ico" />
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
Use a packet analyzer to intercept the packets to/from somewhere.com
. Studying those packets should tell you what is going on.
Time-outs or connections refused could mean that the remote host is too busy.
Why not use a simple javascript function and call it on onclick event?
function reset(){
document.getElementById("my_select").selectedIndex = 1; //1 = option 2
}
What do they do:
What's the difference:
Use which when:
keep the currently selected drop down value with chosen jquery in a global variable before writing the drop down 'on change' action function. If you want to set previous value in the function you can use the global variable.
//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
function (result) {
if (result) {
return true;
} else {
$("#dropDownList").val(previousValue).trigger('chosen:updated');
return false;
}
});
});
Let's give an example for int(10) one with zerofill keyword, one not, the table likes that:
create table tb_test_int_type(
int_10 int(10),
int_10_with_zf int(10) zerofill,
unit int unsigned
);
Let's insert some data:
insert into tb_test_int_type(int_10, int_10_with_zf, unit)
values (123456, 123456,3147483647), (123456, 4294967291,3147483647)
;
Then
select * from tb_test_int_type;
# int_10, int_10_with_zf, unit
'123456', '0000123456', '3147483647'
'123456', '4294967291', '3147483647'
We can see that
with keyword zerofill
, num less than 10 will fill 0, but without zerofill
it won't
Secondly with keyword zerofill
, int_10_with_zf becomes unsigned int type, if you insert a minus you will get error Out of range value for column.....
. But you can insert minus to int_10. Also if you insert 4294967291 to int_10 you will get error Out of range value for column.....
Conclusion:
int(X) without keyword zerofill
, is equal to int range -2147483648~2147483647
int(X) with keyword zerofill
, the field is equal to unsigned int range 0~4294967295, if num's length is less than X it will fill 0 to the left
image{
background-size: cover;
background-repeat: no-repeat;
background-position: center;
padding: 0 3em 0 3em;
margin: -1.5em -0.5em -0.5em -1em;
width: absolute;
max-width: 100%;
A great ES6 option would be to padStart
an empty string. Like this:
var str = ''.padStart(10, "#");
Note: this won't work in IE (without a polyfill).
cd /usr/local
git status
git status
til it's cleanbrew update
From your output:
no listening sockets available, shutting down
what basically means, that any port in which one apache is going to be listening is already being used by another application.
netstat -punta | grep LISTEN
Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill
stop
or do whatever you want to do with it.
After doing a nmap
of your ip I can see that
80/tcp open http
so I guess you sorted it out.
Since many of these answers are old here is how to install mysqli for Easyapache 4.
If you try and search for mysqli under your PHP extensions in WHM you are not going to find it. The way to know which extension you need to install mysqli you will need to run this command in terminal
repoquery -q --whatprovides 'ea-php70-php-mysqli' | sort -V | tail -1
Should return something like
ea-php70-php-mysqlnd-0:7.0.33-1.1.4.cpanel.x86_64
All you really need from this is mysqlnd copy it
To install mysqli using EachApache4:
No, only use semicolons when they're required.
I believe you can also get just the Xcode command-line tools which is about 170 MB.. It's described in the 'brew' setup guide: https://github.com/mxcl/homebrew/wiki/installation and can be found here: https://developer.apple.com/downloads/index.action#
Edit: this was already mentioned above by @josh
Try this one: http://www.pipsomania.com/best_php_obfuscator.do
Recently I wrote it in Java to obfuscate my PHP projects, because I didnt find any good and compatible ready written on the net, I decided to put it online as saas, so everyone use it free. It does not change variable names between different scripts for maximum compatibility, but is obfuscating them very good, with random logic, every instruction too. Strings... everything. I believe its much better then this buggy codeeclipse, that is by the way written in PHP and very slow :)
Summary: Instead of a.f();
it should be a->f();
In main you have defined a as a pointer to object of A, so you can access functions using the ->
operator.
An alternate, but less readable way is (*a).f()
a.f()
could have been used to access f(), if a was declared as:
A a;
I prefer manipulating the length of the stringbuilder:
data.Length = data.Length - 1;
Select getdate() -- 2010-02-05 10:03:44.527
-- To get all date format
select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'
Union
select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'
Union
select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'
Union
select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007
Union
select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007
union
select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010
union
select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'
union
select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205
union
select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010
SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14
SELECT convert(varchar, getdate(), 23) -- 2010-02-05
SELECT convert(varchar, getdate(), 24) -- 10:24:20
SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913
SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990
---==================================
-- To get the time
select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53
select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223
SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM
----=============================================
SELECT getdate()+1
SELECT month(getdate())+1
SELECT year(getdate())+1
You can use the new URL for Google Maps: https://www.google.com/maps/@39.774769,-74.86084,18z equivalent to http://maps.google.com/?ll=39.774769,-74.86084.
39.774769 is the latitude and -74.86084 is longitude and 18z is 18 zoom level.
Using the first for
-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.
The latter syntax is added in Java 5 and enumerates an array by using an Iterator
instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.
It's convenient when you just want to perform some actions on all objects in an array.
Ruby on rails uses ::
for namespace resolution.
class User < ActiveRecord::Base
VIDEOS_COUNT = 10
Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}
end
To use it :
User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"
Also, other usage is : When using nested routes
OmniauthCallbacksController
is defined under users.
And routed as:
devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
end
You can try this. Function below sets all values of object's properties to undefined. Works as well with nested objects.
var clearObjectValues = (objToClear) => {
Object.keys(objToClear).forEach((param) => {
if ( (objToClear[param]).toString() === "[object Object]" ) {
clearObjectValues(objToClear[param]);
} else {
objToClear[param] = undefined;
}
})
return objToClear;
};
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
It seems to work if you use
div#scrollable {
overflow-y: scroll;
height: 100%;
}
and add padding-bottom: 60px
to div.sidebar
.
For example: http://jsfiddle.net/AKL35/6/
However, I am unsure why it must be 60px
.
Also, you missed the f
from overflow-y: scroll;
I think I've done something similar with:
svn add . --recursive
but not sure if my memory is correct ;-p
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
You might want to consider also checking if a value is finite via Double.isFinite(value)
. Since Java 8 there is a new method in Double
class where you can check at once if a value is not NaN and infinity.
/**
* Returns {@code true} if the argument is a finite floating-point
* value; returns {@code false} otherwise (for NaN and infinity
* arguments).
*
* @param d the {@code double} value to be tested
* @return {@code true} if the argument is a finite
* floating-point value, {@code false} otherwise.
* @since 1.8
*/
public static boolean isFinite(double d)
Thank you All...
My issue solved by below code:
<a href="javascript:void(0)"> >>> </a>
The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.
Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.
Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.
reference here
!== is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:
a !== b
a !== "2"
4 !== '4'
Write these span properties
span{
display:inline-block;
vertical-align:middle;
}
Use display:inline-block;
When you use vertical-align
property.Those are assosiated properties
{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}
Probably very late to the answer but I just read this while preparing for my 70-480
exam, and found this to work -
var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }
Notice the event as onclick
instead of onClick
.
JS Bin example.
yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.
As per your question, it can be done by various ways: - For example you can use:
If you want to insert a new line in text area , you can try this:-
Line Feed and
Carriage return
<textarea>Hello Stackoverflow</textarea>
You can also
<pre>---</pre>
Preformatted text.
<pre>
This is Line1
This is Line2
This is Line3
</pre>
Or,you can use
<p>----</p>
Paragraph
<p>This is Line1</p>
<p>This is Line2</p>
<p>This is Line3</p>
Note: if you want to use
\n
you need to install a server like Xampp or Apache to support server side language
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.
Then at the prompt run:
cd a.exe
It will be read in by Cygwin and you will be asked to install it.
It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit()
instead of QApplication.closeAllWindows()
for closing a Java application it generates an error log.
In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:
# An error report file with more information is saved as hs_err_pid24139.log.
The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:
Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
Here is a Swift way to get screen sizes, this also takes current interface orientation into account:
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
These are included as a standard function in:
as of 1.8.X IDE C:\Users***\Documents\Arduino\Libraries\
How about statusid = statusid. Null is never equal to null.
One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.
Symfony 2.0:
$em = $this->getDoctrine()->resetEntityManager();
Symfony 2.1+:
$em = $this->getDoctrine()->resetManager();
I received the error because the component I was using wasn't registered in the declarations: [] section of the module.
After adding the component the error went away. I would have hoped for something less obscure than this error message to indicate the real problem.
No Hungarian whatsoever.
OK, you're thinking this is bad why? Well, because they considered this to be Hungarian:
int foo; int *pFoo; int **hFoo;
Now, any old-school Mac programmer will remember dealing with Handles and Ptrs. The above is the easiest way to tell them apart - Apple sample code is full of it, and Apple was hardly a hotbed of Hungarianism. And so when I had to write some old-school Mac code, naturally I did that, and got it shot down for being Hungarian.
But nobody could propose an alternate naming scheme that preserved the clarity of three variables referring to the same data in different ways, so I checked it in as-is.
Just use
as.Date("2001-01-01") + 45
from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.
Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).
R> library(RcppBDT)
Loading required package: Rcpp
R>
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
and 42 methods, of which 31 are possibly relevant:
addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear,
getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian,
getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize,
setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R>
shape
is a property of both numpy ndarray's and matrices.
A.shape
will return a tuple (m, n), where m is the number of rows, and n is the number of columns.
In fact, the numpy matrix
object is built on top of the ndarray
object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray
How about... It's like if you wanted to install a home theatre system in your house. Using an API is like getting all the wires, screws, bits, and pieces. The possibilities are endless (constrained only by the pieces you receive), but sometimes overwhelming. An SDK is like getting a kit. You still have to put it together, but it's more like getting pre-cut pieces and instructions for an IKEA bookshelf than a box of screws.
import os
directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'
directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'
parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'
This should also do the trick.
I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary
)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
I get what's expected:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult
action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting
Here's a simple actionresult JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
You'll see the difference (and can make sure you're using the right one) when serializing a date:
Microsoft way:
{"wireTime":"\/Date(1355627201572)\/"}
JSON.NET way:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
just use the full url as href like this:
<a href="https://www.example.com/" target="_blank">page link</a>
Another example with a struct :
package types
import "fmt"
type MyType struct {
Id int
Name string
}
func (t MyType) String() string {
return fmt.Sprintf(
"[%d : %s]",
t.Id,
t.Name)
}
Be careful when using it,
concatenation with '+' doesn't compile :
t := types.MyType{ 12, "Blabla" }
fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly
As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:
msec := time.Now().UnixNano() / 1000000
Resource: https://gobyexample.com/epoch
This is also possible using a series of self-overwriting getters:
(This is similar to jontro's solution, but doesn't require a counter variable.)
(() => {_x000D_
"use strict";_x000D_
Object.defineProperty(this, "a", {_x000D_
"get": () => {_x000D_
Object.defineProperty(this, "a", {_x000D_
"get": () => {_x000D_
Object.defineProperty(this, "a", {_x000D_
"get": () => {_x000D_
return 3;_x000D_
}_x000D_
});_x000D_
return 2;_x000D_
},_x000D_
configurable: true_x000D_
});_x000D_
return 1;_x000D_
},_x000D_
configurable: true_x000D_
});_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_
document.body.append("Yes, it’s possible.");_x000D_
}_x000D_
})();
_x000D_
AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.
This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.
No, there isn't a syntax for extracting text using regular expressions. You have to use the ordinary string manipulation functions.
Alternatively select the entire value from the database (or the first n characters if you are worried about too much data transfer) and then use a regular expression on the client.
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader
after calling open
. Simply move your setRequestHeader
line below your open
line (but before send
):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
you can use DateUtils class in org.apache.commons.lang3.time package
int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute
Try this:
CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4
The as col4
should go at the end of the CASE the statement. Also note that you're missing the END
too.
Another probably more simple option would be:
IIf([table3.col3] Is Null,[table2.col3],[table3.col3])
Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.
Edit after radical question change:
To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):
SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID,
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID
BTW, your CASE statement was missing a ,
before the field. That's why it didn't work.
I used the code below and tried to show the sitemap.xml file
router.get('/sitemap.xml', function (req, res) {
res.sendFile('sitemap.xml', { root: '.' });
});
You're looking for this on the command line (for a class called MyClass):
On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
You want the major version from the results. Here are some example values:
What is the most efficient way to create HTML elements using jQuery?
Since it's about jQuery
then I think it's better to use this (clean) approach (you are using)
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'text':'Text Only',
}).on('click', function(){
alert(this.id); // myDiv
}).appendTo('body');
This way, you can even use event handlers for the specific element like
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'style':'cursor:pointer;font-weight:bold;',
'html':'<span>For HTML</span>',
'click':function(){ alert(this.id) },
'mouseenter':function(){ $(this).css('color', 'red'); },
'mouseleave':function(){ $(this).css('color', 'black'); }
}).appendTo('body');
But when you are dealing with lots of dynamic elements, you should avoid adding event handlers
in particular element, instead, you should use a delegated event handler, like
$(document).on('click', '.myClass', function(){
alert(this.innerHTML);
});
var i=1;
for(;i<=200;i++){
$('<div/>', {
'class':'myClass',
'html':'<span>Element'+i+'</span>'
}).appendTo('body');
}
So, if you create and append hundreds of elements with same class, i.e. (myClass
) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.
Update : Since we can use following approach to create a dynamic element
$('<input/>', {
'type': 'Text',
'value':'Some Text',
'size': '30'
}).appendTo("body");
But the size
attribute can't be set using this approach using jQuery-1.8.0
or later and here is an old bug report, look at this example using jQuery-1.7.2
which shows that size
attribute is set to 30
using above example but using same approach we can't set size
attribute using jQuery-1.8.3
, here is a non-working fiddle. So, to set the size
attribute, we can use following approach
$('<input/>', {
'type': 'Text',
'value':'Some Text',
attr: { size: "30" }
}).appendTo("body");
Or this one
$('<input/>', {
'type': 'Text',
'value':'Some Text',
prop: { size: "30" }
}).appendTo("body");
We can pass attr/prop
as a child object but it works in jQuery-1.8.0 and later
versions check this example but it won't work in jQuery-1.7.2 or earlier
(not tested in all earlier versions).
BTW, taken from jQuery
bug report
There are several solutions. The first is to not use it at all, since it doesn't save you any space and this improves the clarity of the code:
They advised to use following approach (works in earlier ones as well, tested in 1.6.4
)
$('<input/>')
.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");
So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S)
instead of 'size'
then it will just work fine, even in version-2.0.2
$('<input>', {
'type' : 'text',
'Size' : '50', // size won't work
'autofocus' : 'true'
}).appendTo('body');
Also read about prop, because there is a difference, Attributes vs. Properties
, it varies through versions.
I use for(;/*ever*/;)
.
It is easy to read and it takes a bit longer to type (due to the shifts for the asterisks), indicating I should be really careful when using this type of loop. The green text that shows up in the conditional is also a pretty odd sight—another indication this construct is frowned upon unless absolutely necessary.
Try:-
Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""c:\Program Files\Mozilla Firefox\firefox.exe""")
Set objShell = Nothing
Note the extra ""s in the string. Since the path to the exe contains spaces it needs to be contained with in quotes. (In this case simply using "firefox.exe" would work).
Also bear in mind that many programs exist in the c:\Program Files (x86) folder on 64 bit versions of Windows.
In most project types, your async
"up" and "down" will end at an async void
event handler or returning a Task
to your framework.
However, Console apps do not support this.
You can either just do a Wait
on the returned task:
static void Main()
{
MainAsync().Wait();
// or, if you want to avoid exceptions being wrapped into AggregateException:
// MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
...
}
or you can use your own context like the one I wrote:
static void Main()
{
AsyncContext.Run(() => MainAsync());
}
static async Task MainAsync()
{
...
}
More information for async
Console apps is on my blog.
For some odd reason this part
$el.empty(); // remove old options
from CMS solution didn't work for me, so instead of that I've simply used this
el.html(' ');
And it's works. So my working code now looks like that:
var newOptions = {
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});