This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):
Select Table View > Size Inspector > Content Insets: Never
Try doing:
SHOW TABLE STATUS FROM credentialing1;
The foreign key constraints are listed in the Comment column of the output.
This worked for me, combo of two answers from above:
Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.
The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding.
PHP's getimagesize()
returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:
var $imagedata = getimagesize("someimage.jpg");
print "Image width is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];
For further information, see the documentation.
I just installed vim by:
brew install vim
now the new vim is accessed by vim
and the old vim (built-in vim) by vi
While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date
object instead of a datetime.datetime
. So for those searching and finding this thread:
datetime.date
has no .strptime
method; use the one on datetime.datetime
instead and then call .date()
on it to receive the datetime.date
object.
Like so:
>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)
another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().
For folks searching for solution to set spacing between N
divs, here is another approach using pseudo selectors:
div:not(:last-child) {
margin-right: 40px;
}
You can also combine child pseudo selectors:
div:not(:first-child):not(:last-child) {
margin-left: 20px;
margin-right: 20px;
}
Using environment variable is sometimes more convenient when you do not control the build scripts / process.
For C includes use C_INCLUDE_PATH
.
For C++ includes use CPLUS_INCLUDE_PATH
.
See this link for other gcc environment variables.
# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)
C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg
set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"
pip install asyncpg
# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=
If you want to simply remove the value in the combo box:
me.combobox = ""
If you want to remove the recordset of the combobox, the easiest way is:
me.combobox.recordset = ""
me.combobox.requery
It sounds like you need to set up passwordless sudo. Try:
%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt
Also comment out the following line (in /etc/sudoers via visudo), if it is there:
Defaults requiretty
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
You're mapping this JSON
{
"id": 2,
"socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
"type": "getDashboard",
"data": {
"workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
},
"reply": true
}
that contains an element named data
that has a JSON object as its value. You are trying to deserialize the element named workstationUuid
from that JSON object into this setter.
@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {
This won't work directly because Jackson sees a JSON_OBJECT, not a String.
Try creating a class Data
public class Data { // the name doesn't matter
@JsonProperty("workstationUuid")
private String workstationUuid;
// getter and setter
}
the switch up your method
@JsonProperty("data")
public void setWorkstation(Data data) {
// use getter to retrieve it
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:
(but note that
ALL TABLES
is considered to include views and foreign tables).
Bold emphasis mine. serial
columns are implemented with nextval()
on a sequence as column default and, quoting the manual:
For sequences, this privilege allows the use of the
currval
andnextval
functions.
So if there are serial
columns, you'll also want to grant USAGE
(or ALL PRIVILEGES
) on sequences
GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;
Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial
columns.)
You'll also be interested in DEFAULT PRIVILEGES
for users or schemas:
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;
This sets privileges for objects created in the future automatically - but not for pre-existing objects.
Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role
). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES
. To be explicit:
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;
Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE
clause manually when copying the SQL script.
HTML
<form ... id ="GoogleMapsApiKeyForm">
...
<input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
....
<span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
...
<button type="submit" class="btn btn-primary">Save</button>
</form>
Javascript
$(function () {
$("#GoogleMapsApiKeyForm").validate({
rules: {
GoogleMapsAPIKey: {
required: true
}
},
messages: {
GoogleMapsAPIKey: 'Google maps api key is required',
},
errorPlacement: function (error, element) {
if (element.attr("name") == "GoogleMapsAPIKey")
$("#GoogleMapsAPIKey-errorMsg").html(error);
},
submitHandler: function (form) {
// form.submit(); //if you need Ajax submit follow for rest of code below
}
});
//If you want to use ajax
$("#GoogleMapsApiKeyForm").submit(function (e) {
e.preventDefault();
if (!$("#GoogleMapsApiKeyForm").valid())
return;
//Put your ajax call here
});
});
If you're just interested in the properties and data types from the database, you can use Model.inspect
.
irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
reset_password_token: string, reset_password_sent_at: datetime,
remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
updated_at: datetime)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
ActiveRecord::Schema.define(version: 20130712162401) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
end
You can also use exists
, since sometimes it's faster than left join
. You'd have to benchmark them to figure out which one you want to use.
select
id
from
tableA a
where
not exists
(select 1 from tableB b where b.id = a.id)
To show that exists
can be more efficient than a left join
, here's the execution plans of these queries in SQL Server 2008:
left join
- total subtree cost: 1.09724:
exists
- total subtree cost: 1.07421:
180 degrees = PI * radians
You can try this format SS.FF
for milliseconds:
to_timestamp(table_1.date_col,'DD-Mon-RR HH24:MI:SS.FF')
For more details:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions193.htm
Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}
if (isset($_GET["id"])){
//do stuff
}
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
As long as the cell is in text format before the user types in the number, POI will allow you to obtain the value as a string. One key is that if there is a small green triangle in the upper left-hand corner of cell that is formatted as Text, you will be able to retrieve its value as a string (the green triangle appears whenever something that appears to be a number is coerced into a text format). If you have Text formatted cells that contain numbers, but POI will not let you fetch those values as strings, there are a few things you can do to the Spreadsheet data to allow that:
One final thing that you can do is that if you are using POI to obtain data from an Excel 2007 spreadsheet, you can the Cell class 'getRawValue()' method. This does not care what the format is. It will simply return a string with the raw data.
In my case I just wanted a line break after each dd
element.
Eg, I wanted to style this:
<dl class="p">
<dt>Created</dt> <dd><time>2021-02-03T14:23:43.073Z</time></dd>
<dt>Updated</dt> <dd><time>2021-02-03T14:44:15.929Z</time></dd>
</p>
like the default style of this:
<p>
<span>Created</span> <time>2021-02-03T14:23:43.073Z</time><br>
<span>Updated</span> <time>2021-02-03T14:44:15.929Z</time>
</p>
which just looks like this:
Created 2021-02-03T14:23:43.073Z
Updated 2021-02-03T14:44:15.929Z
To do that I used this CSS:
dl.p > dt {
display: inline;
}
dl.p > dd {
display: inline;
margin: 0;
}
dl.p > dd::after {
content: "\A";
white-space: pre;
}
Or you could use this CSS:
dl.p > dt {
float: left;
margin-inline-end: 0.26em;
}
dl.p > dd {
margin: 0;
}
I also added a colon after each dt
element with this CSS:
dl.p > dt::after {
content: ":";
}
The git diff
command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.
If you had a branch named origin
, the commit hash at tip of the branch would have been used if you supplied origin
to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin
.
An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:
git diff origin/<branchname>
git diff <branchname> origin/<branchname>
Edit: Having read further, I realise I'm slightly wrong, git diff origin
is shorthand for diffing against the head of the specified remote, so git diff origin
= git diff origin/HEAD
(compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)
It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.
Running git branch -r
will show you if origin/HEAD
is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>
).
A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.
But in the documentation you may read now : "All JavaScript API applications require authentication."
I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).
You better use a key when you want to be sure that your application will still work in 1 or 2 years.
I like an IDE because it puts a lot of functionality at my fingertips. Editing/Compilation/visibility of files in the project are all things I value in an IDE. I use Visual Studio now but in a former life I used SlickEdit and found that it made my development process more streamlined than when I wasn't using it.
In Symfony 3.3 you can use
$projectRoot = $this->get('kernel')->getProjectDir();
to get the web/project root.
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
Ensure all dependencies are installed. npm install
I was making a quick app for myself and I had forgotten to add express. Threw the above error.
The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.
The solution is:
That's it.
For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring
property is set to true, the sub-widget (actually, the entire subtree) is not clickable.
IgnorePointer(
ignoring: true, // or false
child: RaisedButton(
onPressed: _logInWithFacebook,
child: Text("Facebook sign-in"),
),
),
Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
You can try opening the wsdl in web browser and saving with .wsdl extension. And set the WSDL in SOAP UI project to this .wsdl file. This really works.
I'm on XP. I've installed MySQL-5.6.10 manually from .zip
, no Windows auto-installer provided by MySQL site. The /bin
directory of my MySQL is in my PATH. So I start the server with mysqld --console
command, like this:
C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).
From now on it is running. And that cmd window is occupied. I open and use another one.
I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown
on the other cmd window or with Ctrl + C
on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C
twice or more.
The log of the shutdown process is like this:
2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete
And I still don't know if it is 100% right way to shutdown the server, but it works :)
To match the title of this question, the value of the id
attribute is:
var myId = $(this).attr('id');
alert( myId );
BUT, of course, the element must already have the id element defined, as:
<option id="opt7" class='select_continent' value='7'>Antarctica</option>
In the OP post, this was not the case.
Note that plain js is faster (in this case):
var myId = this.id
alert( myId );
That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.
Using Laravel Eloquent you can get one row using first()
method,
it returns first row of table if where()
condition is not found otherwise it gives the first matched row of given criteria.
Syntax:
Model::where('fieldname',$value)->first();
Example:
$user = User::where('email',$email)->first();
//OR
//$user = User::whereEmail($email)->first();
You're not working with strings. You're working with pointers.
var1
is a char pointer (const char*
). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*)
.
Such an operator does exist. It takes two pointers and returns true
if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp
function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string
class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:
IDLE 2.6.2
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001
I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.
Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.
If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.
How to discover the line which causes the problem?
You have three ways to do that.
1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.
2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.
3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.
In my case I followed the third option and fortunately I pinpoint the line which causes the problem.
This is a long answer but it actually does not solve the exception. How I overcome this exception?
I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t
. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n
) and then it deals each line as a separate json string.
In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.
I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that. I used a string as output, as implode can't add new line (new line is something I added, and should really be there).
Please note, this only works with single value arrays (key, value)
. but could easily be updated to handle multi-dimensional (key, array())
.
function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = '';
foreach ( $fields as $key => $field ) {
if ($field === null && $nullToMysqlNull) {
$output = '';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output .= $key;
$output .= $delimiter;
$output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
$output .= PHP_EOL;
}
else {
$output .= $key;
$output .= $delimiter;
$output .= $field;
$output .= PHP_EOL;
}
}
return $output ;
}
Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement),
SecondList.OrderBy(sElement => sElement))
i solved the problem i exlained...for example in the file we render the other component,other component name is same with me method of current component such as:
const Login = () => {
}
render(
<Login/>
)
..for solve this we must change the method name
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
I also came across the same error. I just opened another non-running Juputer notebook and an error is automatically gone.
Since you add ..
after cmake, it will jump up and up (just like cd ..
) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use .
instead of ..
.
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
Since the Beta, Razor uses a different config section for globally defining namespace imports. In your Views\Web.config
file you should add the following:
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- Your namespace here -->
</namespaces>
</pages>
</system.web.webPages.razor>
Use the MVC 3 upgrade tool to automatically ensure you have the right config values.
Note that you might need to close and reopen the file for the changes to be picked up by the editor.
You can get the input element and then set its readOnly
property to true
as follows:
document.getElementById('InputFieldID').readOnly = true;
Specifically, this is what you want:
<script type="text/javascript">
function onLoadBody() {
document.getElementById('control_EMAIL').readOnly = true;
}
</script>
Call this onLoadBody()
function on body tag like:
<body onload="onLoadBody">
View Demo: jsfiddle.
With modern (as of mid-2017 Python 3.5 and Pillow 4.0):
StringIO no longer seems to work as it used to. The BytesIO class is the proper way to handle this. Pillow's save function expects a string as the first argument, and surprisingly doesn't see StringIO as such. The following is similar to older StringIO solutions, but with BytesIO in its place.
from io import BytesIO
from PIL import Image
image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')
The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.
For IE, I found that changing
.flex > div
{
flex: 1 0 50%;
}
to
.flex > div
{
flex: 1 0 45%;
}
seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.
In the case of Firefox I solved it by adding
display: inline-block;
to the items.
I got the same error, here is how I resolved it:
Even though I was processing large files there were no other errors or settings I had to change once I corrected the missing S3 access.
As mentioned this occurs when using RubyGems 1.6.0 with Ruby on Rails version earlier than version 3. My app is using Ruby on Rails 2.3.3 vendored into the /vendor of the project.
No doubt an upgrade of Ruby on Rails to a newer 2.3.X version may also fix this issue. However, this problem prevents you running Rake to unvendor Ruby on Rails and upgrade it.
Adding require 'thread' to the top of environment.rb did not fix the issue for me. Adding require 'thread' to /vendor/rails/activesupport/lib/active_support.rb did fix the problem.
If you want to log to the same file:
command1 >> log_file 2>&1
If you want different files:
command1 >> log_file 2>> err_file
Varchar has its own limits. Maybe try changing datatype to text.!
Also, if you'd like to know global memory rather than node process':
var os = require('os');
os.freemem();
os.totalmem();
This can happen for more than one reason. In my case this happened due to a permissions issue. The user that the task was running as didn't have permission to write to the logs directory so it failed with this error.
You can use fit-content
value for width
.
#wrap {
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
margin: auto;
}
Note: It works only in latest browsers.
select * from syscat.tables where type = 'T'
you may want to restrict the query to your tabschema
Maven advantages over ant are quite a few. I try to summarize them here.
Convention over Configuration
Maven uses a distinctive approach for the project layout and startup, that makes easy to just jump in a project. Usually it only takes the checkount and the maven command to get the artifacts of the project.
Project Modularization
Project conventions suggest (or better, force) the developer to modularize the project. Instead of a monolithic project you are often forced to divide your project in smaller sub components, which make it easier debug and manage the overall project structure
Dependency Management and Project Lifecycle
Overall, with a good SCM configuration and an internal repository, the dependency management is quite easy, and you are again forced to think in terms of Project Lifecycle - component versions, release management and so on. A little more complex than the ant something, but again, an improvement in quality of the project.
What is wrong with maven?
Maven is not easy. The build cycle (what gets done and when) is not so clear within the POM. Also, some issue arise with the quality of components and missing dependencies in public repositories.
The best approach (to me) is to have an internal repository for caching (and keeping) dependencies around, and to apply to release management of components. For projects bigger than the sample projects in a book, you will thank maven before or after
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
Notice that the session writing and reading works, yet no cookies seem to be passed to the browser. At least I couldn't find a "Set-Cookie" header anywhere.
First find the condition that occurs in all situations, then filter the special conditions:
$('[myc="blue"]')
.filter('[myid="1"],[myid="3"]');
Expanding on Ehsan's Answer....
If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute
Class in code.
private static bool IsValidEmailAddress(string emailAddress)
{
return new System.ComponentModel.DataAnnotations
.EmailAddressAttribute()
.IsValid(emailAddress);
}
If you are considering REGEX to verify email address then read:
I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack
SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.
MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.
It works fine, Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
Use the \
character to escape a character that has special meaning inside a regular expression.
To automate it, you could use this:
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape
Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
try using:
RAISERROR('your message here!!!',0,1) WITH NOWAIT
you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.
With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.
If all else fails, you could create a table:
create table temp_log (RowID int identity(1,1) primary key not null
, MessageValue varchar(255))
then:
INSERT INTO temp_log VALUES ('Your message here')
then after running the procedure (provided no rollbacks) just select
the table.
Reading Data From The Console
BufferedReader
is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner
breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace
.
« Until the user enters data, the scanning operation may block, waiting for input. « Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream. « A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
To manipulate the white space, use str_trim() in the stringr package. The package has manual dated Feb 15, 2013 and is in CRAN. The function can also handle string vectors.
install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)
(Credit goes to commenter: R. Cotton)
Alternatively, as long as permissions are not given, the good old <noscript>
tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
View this picture to see how you can change the bundle identifier
Explanation:
As you can see in the picture, the name of my App is PracticeApp. And my bundle identifier is: com.hello500.PracticeApp
In this case, You can change hello500 to change the bundle identifier of the app.
I was having some trouble with this so let me be very explicit so noobs like me can understand.
Lets say that we have a data file or something like that
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import sympy as sym
"""
Generate some data, let's imagine that you already have this.
"""
x = np.linspace(0, 3, 50)
y = np.exp(x)
"""
Plot your data
"""
plt.plot(x, y, 'ro',label="Original Data")
"""
brutal force to avoid errors
"""
x = np.array(x, dtype=float) #transform your data in a numpy array of floats
y = np.array(y, dtype=float) #so the curve_fit can work
"""
create a function to fit with your data. a, b, c and d are the coefficients
that curve_fit will calculate for you.
In this part you need to guess and/or use mathematical knowledge to find
a function that resembles your data
"""
def func(x, a, b, c, d):
return a*x**3 + b*x**2 +c*x + d
"""
make the curve_fit
"""
popt, pcov = curve_fit(func, x, y)
"""
The result is:
popt[0] = a , popt[1] = b, popt[2] = c and popt[3] = d of the function,
so f(x) = popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3].
"""
print "a = %s , b = %s, c = %s, d = %s" % (popt[0], popt[1], popt[2], popt[3])
"""
Use sympy to generate the latex sintax of the function
"""
xs = sym.Symbol('\lambda')
tex = sym.latex(func(xs,*popt)).replace('$', '')
plt.title(r'$f(\lambda)= %s$' %(tex),fontsize=16)
"""
Print the coefficients and plot the funcion.
"""
plt.plot(x, func(x, *popt), label="Fitted Curve") #same as line above \/
#plt.plot(x, popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3], label="Fitted Curve")
plt.legend(loc='upper left')
plt.show()
the result is: a = 0.849195983017 , b = -1.18101681765, c = 2.24061176543, d = 0.816643894816
I had trouble with ll of the above, including the approved answer. I converted Hardy's category back into a method since all i wanted was to rotate an image. Here's the code and usage:
- (UIImage *)imageRotatedByDegrees:(UIImage*)oldImage deg:(CGFloat)degrees{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,oldImage.size.width, oldImage.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(degrees * M_PI / 180);
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// // Rotate the image context
CGContextRotateCTM(bitmap, (degrees * M_PI / 180));
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-oldImage.size.width / 2, -oldImage.size.height / 2, oldImage.size.width, oldImage.size.height), [oldImage CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
And the usage:
UIImage *image2 = [self imageRotatedByDegrees:image deg:90];
Thanks Hardy!
Your code makes no sense, maybe because it's out of context.
If you mean code like this:
$('a').click(function () {
callFunction();
return false;
});
The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.
You could use ArraySegment<T>
. It's very light-weight as it doesn't copy the array:
string[] a = { "one", "two", "three", "four", "five" };
var segment = new ArraySegment<string>( a, 1, 2 );
You can do a port redirect. This is what I do for a Silverlight policy server running on a Linux box
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 943 -j REDIRECT --to-port 1300
On the other thread C# naming convention for enum and matching property someone pointed out what I think is a very good idea:
"I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I')."
This will return all the values matching your key valueTitle
subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();
There are many uses for the **null** value in the Boolean wrapper! :)
For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.
But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)
String interpolation is a nice way to pass in a formatted string.
values = ', '.join('$%s' % v for v in value_list)
You can loop through each the cells in your range and use the InStr
function to check if a cell contains a string, in your case; a hyphen.
Sub DeleteRowsWithHyphen()
Dim rng As Range
For Each rng In Range("A2:A10") 'Range of values to loop through
If InStr(1, rng.Value, "-") > 0 Then 'InStr returns an integer of the position, if above 0 - It contains the string
rng.Delete
End If
Next rng
End Sub
A PREFERRED OPTION over .attr
is to use .prop
like so:
$(this).prev('li').prop('id', 'newId');
.attr
retrieves the element's attribute whereas .prop
retrieves the property that the attribute references (i.e. what you're actually intending to modify)
If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength
TestBox code
<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">
Ng-Class to Add
ng-class="{ 'err' : myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"
SELECT CONVERT(NVARCHAR, LoginDate, 105)+' '+CONVERT(NVARCHAR, LoginDate, 108) AS LoginDate FROM YourTable
Output
-------------------
29-08-2013 13:55:48
I tried posting this as a comment, but couldn't get the columns to display right (as per your question).
You are asking for:
A B
C D
E
... but the answer accepted as the solution will return:
A D
B E
C
... so either the answer is incorrect or the question is.
A very simple solution would be to set the width of your <ul>
and then float and set the width of your <li>
items like so
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
ul{
width:210px;
}
li{
background:green;
float:left;
height:100px;
margin:0 10px 10px 0;
width:100px;
}
li:nth-child(even){
margin-right:0;
}
Example here http://jsfiddle.net/Jayx/Qbz9S/1/
If your question is wrong, then the previous answers apply (with a JS fix for lacking IE support).
This works for me - i am using jackson 2.0.4
ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);
This method I've used a lot, not sure if it is a very good way but it works fine for my needs.
<html>
<head>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<div id="HiddenStuff1" style="display:none">
CONTENT TO HIDE 1
</div>
<div id="HiddenStuff2" style="display:none">
CONTENT TO HIDE 2
</div>
<div id="HiddenStuff3" style="display:none">
CONTENT TO HIDE 3
</div>
<input id="YOUR ID" title="HIDDEN STUFF 1" type=button name=type value='HIDDEN STUFF 1' onclick="setVisibility('HiddenStuff1', 'inline');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 2" type=button name=type value='HIDDEN STUFF 2' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'inline');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 3" type=button name=type value='HIDDEN STUFF 3' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'inline');";>
</body>
</html>
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.
define("EMAIL_DOMAIN", "yourdomain.com");
public function send_email_html($to, $from, $subject, $html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$uniqid = md5(uniqid(time()));
$boundary = "--==_mimepart_".$uniqid;
$headers = "From: ".$from."\n".
'Reply-to: '.$from."\n".
'Return-Path: '.$from."\n".
'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
'Mime-Version: 1.0'."\n".
'Content-Type: multipart/related;'."\n".
' boundary='.$boundary.";\n".
' charset=UTF-8'."\n".
'X-Mailer: PHP/' . phpversion();
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'UTF-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if (file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
mail($to, $subject, $multipart, $headers);
}
If you are a user of MacPorts, you may simply install usbutils
sudo port install usbutils
If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.
For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />
Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>
Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.
As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).
Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:
public static class DateTimeUtils
{
public static DateTime Tomorrow { get { ... } }
}
And then use this in your code via:
WriteLine("{0}", DateTimeUtils.Tomorrow)
For showing keyboard use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
For hiding keyboard use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
@RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
The Like Box/ Page plugin is basically an iframe and ugly :D
So I created my own free plugin that I call Famax plugin to display FanPage feeds. It's similar to the like box but has a better UI and is more customizable.
Also because the Like box is shown in an iframe with a fixed width and height etc, its not really responsive.
/**
* Intent to Send SMS
*
*
* Extras:
*
* "subject"
* A string for the message subject (usually for MMS only).
* "sms_body"
* A string for the text message.
* EXTRA_STREAM
* A Uri pointing to the image or video to attach.
*
* For More Info:
* https://developer.android.com/guide/components/intents-common#SendMessage
*
* @param phoneNumber on which SMS to send
* @param message text Message to send with SMS
*/
public void startSMSIntent(String phoneNumber, String message) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
// This ensures only SMS apps respond
intent.setData(Uri.parse("smsto:"+phoneNumber));
intent.putExtra("sms_body", message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
I'm late to the party, but hopefully this is a useful addition to the other answers here...
I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.
The following are all candidates:
Uri
's on ImageView
's all constitute IO on the main thread)View
hierarchiesView
hierarchyonDraw
methods in custom View
'sAsyncTask
's are "background" by default, java.lang.Thread
is not)To actually determine the specific cause you'll need to profile your app.
I've been trying to understand Choreographer by experimenting and looking at the code.
The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.
The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:
The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.
The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.
From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View
hierarchy or a View
with a complicated onDraw method might be enough.
For example this will trigger the warning repeatedly:
public class AnnoyTheChoreographerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_linear_layout);
ViewGroup root = (ViewGroup) findViewById(R.id.root);
root.addView(new TextView(this){
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long sleep = (long)(Math.random() * 1000L);
setText("" + sleep);
try {
Thread.sleep(sleep);
} catch (Exception exc) {}
}
});
}
}
... which produces logging like this:
11-06 09:35:15.865 13721-13721/example I/Choreographer? Skipped 42 frames! The application may be doing too much work on its main thread.
11-06 09:35:17.395 13721-13721/example I/Choreographer? Skipped 59 frames! The application may be doing too much work on its main thread.
11-06 09:35:18.030 13721-13721/example I/Choreographer? Skipped 37 frames! The application may be doing too much work on its main thread.
You can see from the stack during onDraw
that the choreographer is involved regardless of whether you are animating:
at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)
... quite a bit of repetition ...
at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)
Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.
In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.
Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large
". To avoid such errors you can first check par("mar")
output. You should be getting:
[1] 5.1 4.1 4.1 2.1
To change that write:
par(mar=c(1,1,1,1))
This should rectify the error. Or else you can change the values accordingly.
Hope this works for you.
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
In Android its very Simple .Just use the Calender class to get currentTimeMillis.
Timestamp stamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
Date date = new Date(stamp.getTime());
Log.d("Current date Time is " +date.toString());
In Java just Use System.currentTimeMillis() to get current timestamp
For Mac Terminal
cd .. # one up
cd ../ # two up
cd # home directory
cd / # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces
There are two ways to compare three integers and check whether b is between a and c:
if a < b < c:
pass
and
if a < b and b < c:
pass
The first one looks like more readable, but the second one runs faster.
Let's compare using dis.dis:
>>> dis.dis('a < b and b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 COMPARE_OP 0 (<)
6 JUMP_IF_FALSE_OR_POP 14
8 LOAD_NAME 1 (b)
10 LOAD_NAME 2 (c)
12 COMPARE_OP 0 (<)
>> 14 RETURN_VALUE
>>> dis.dis('a < b < c')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 DUP_TOP
6 ROT_THREE
8 COMPARE_OP 0 (<)
10 JUMP_IF_FALSE_OR_POP 18
12 LOAD_NAME 2 (c)
14 COMPARE_OP 0 (<)
16 RETURN_VALUE
>> 18 ROT_TWO
20 POP_TOP
22 RETURN_VALUE
>>>
and using timeit:
~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop
~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop
also, you may use range, as suggested before, however it is much more slower.
This can also be achieved using the Scalar-Valued Function
in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE @SchoolName varchar(500)
SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=@MaskId
RETURN @SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
context.Authors.Where(a => a.Books.Any(b => b.BookID == bookID)).ToList();
a.Books
is the list of books by that author. The property is automatically created by Linq-to-Sql, provided you have a foreign-key relationship set up.
So, a.Books.Any(b => b.BookID == bookID)
translates to "Do any of the books by this author have an ID of bookID", which makes the complete expression "Who are the authors of the book with id bookID?"
That could also be written something like
from a in context.Authors
join b in context.Books on a.AuthorId equal b.AuthorID
where b.BookID == bookID
select a;
UPDATE:
Any()
as far as I know, only returns a bool
. Its effective implementation is:
public Any(this IEnumerable<T> coll, Func<T, bool> predicate)
{
foreach(T t in coll)
{
if (predicte(t))
return true;
}
return false;
}
You can use isset() without losing the concatenation:
//snip
$str = 'something'
. ( isset($output['alternate_title']) ? $output['alternate_title'] : '' )
. ( isset($output['access_info']) ? $output['access_info'] : '' )
. //etc.
You could also write a function to return the string if it is set - this probably isn't very efficient:
function getIfSet(& $var) {
if (isset($var)) {
return $var;
}
return null;
}
$str = getIfSet($output['alternate_title']) . getIfSet($output['access_info']) //etc
You won't get a notice because the variable is passed by reference.
I used scan to get total count of the required tableName.Following is a Java code snippet for same
Long totalItemCount = 0;
do{
ScanRequest req = new ScanRequest();
req.setTableName(tableName);
if(result != null){
req.setExclusiveStartKey(result.getLastEvaluatedKey());
}
result = client.scan(req);
totalItemCount += result.getItems().size();
} while(result.getLastEvaluatedKey() != null);
System.out.println("Result size: " + totalItemCount);
Typing in $(this)
will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.
alert($(this));
Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.
Further explanation can be found in Aditya Mittal's answer.
$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)
$scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.
$scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.
The $emit event can be cancelled by any one of the $scope who is listening to the event.
The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.
Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/
In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.
For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html
Another way:
a xls(x) file is just a collection of *.xml files stored in a *.zip container. unzip the file "app.xml" in the folder docProps.
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<Properties xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
<TotalTime>0</TotalTime>
<Application>Microsoft Excel</Application>
<DocSecurity>0</DocSecurity>
<ScaleCrop>false</ScaleCrop>
-<HeadingPairs>
-<vt:vector baseType="variant" size="2">
-<vt:variant>
<vt:lpstr>Arbeitsblätter</vt:lpstr>
</vt:variant>
-<vt:variant>
<vt:i4>4</vt:i4>
</vt:variant>
</vt:vector>
</HeadingPairs>
-<TitlesOfParts>
-<vt:vector baseType="lpstr" size="4">
<vt:lpstr>Tabelle3</vt:lpstr>
<vt:lpstr>Tabelle4</vt:lpstr>
<vt:lpstr>Tabelle1</vt:lpstr>
<vt:lpstr>Tabelle2</vt:lpstr>
</vt:vector>
</TitlesOfParts>
<Company/>
<LinksUpToDate>false</LinksUpToDate>
<SharedDoc>false</SharedDoc>
<HyperlinksChanged>false</HyperlinksChanged>
<AppVersion>14.0300</AppVersion>
</Properties>
The file is a german file (Arbeitsblätter = worksheets). The table names (Tabelle3 etc) are in the correct order. You just need to read these tags;)
regards
Instances of the String
constructor have a .search()
method which accepts a RegExp and returns the index of the first match.
To start the search from a particular position (faking the second parameter of .indexOf()
) you can slice
off the first i
characters:
str.slice(i).search(/re/)
But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i
) to the returned index if it wasn't -1
. This will give you the index in the original string:
function regexIndexOf(text, re, i) {
var indexInSuffix = text.slice(i).search(re);
return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="fname" id="fname"/>
<input type="submit" name="click" value="button" />
</form>
<script>
$(document).ready(function(){
$(function(){
$("#myForm").submit(function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
dataType: "json",
contentType: "application/json",
data : $('#myForm').serialize(),
success: function(data){
alert(data);
},
error: function(xhr, desc, err){
console.log(err);
}
});
});
});
});
</script>
</body>
</html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
For IDLE, select the lines, then open the "Format" menu. (Between "Edit" and "Run" if you're having trouble finding it.) This will also give you the keyboard shortcut, for me it turned out that dedent shortcut was "Ctrl+["
#include <algorithm>
#include <string>
std::string str;
str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
The behavior of std::remove may not quite be what you'd expect. See an explanation of it here.
const int
is identical to int const
, as is true with all scalar types in C. In general, declaring a scalar function parameter as const
is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.
.apply
is often used when the intention is to invoke a variadic function with a list of argument values, e.g.
The Math.max([value1[,value2, ...]])
function returns the largest of zero or more numbers.
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
The Math.max()
method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.
Math.max.apply(null, [10, 20]); // 20
Math.max.apply(null, [-10, -20]); // -10
Math.max.apply(null, [-10, 20]); // 20
However, as of the ECMAScript 6 you can use the spread operator:
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
Using the spread operator, the above can be rewritten as such:
Math.max(...[10, 20]); // 20
Math.max(...[-10, -20]); // -10
Math.max(...[-10, 20]); // 20
When calling a function using the variadic operator, you can even add additional values, e.g.
Math.max(...[10, 20], 50); // 50
Math.max(...[-10, -20], 50); // 50
Bonus:
Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push
, splice
, etc.
let foo = ['b', 'c'];
let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
Yes you should change the name of your function. Javascript has reserved methods and onclick = >>>> click() <<<< is one of them so just rename it, add an 's' to the end of it or something. strong text`
The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:
median(x = 1:10)
x
## Error: object 'x' not found
In this case, x
is declared within the scope of the function, so it does not exist in the user workspace.
median(x <- 1:10)
x
## [1] 1 2 3 4 5 6 7 8 9 10
In this case, x
is declared in the user workspace, so you can use it after the function call has been completed.
There is a general preference among the R community for using <-
for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like
x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3
Most R IDEs have keyboard shortcuts to make <-
easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.
If you prefer writing =
to <-
but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_*
functions in the formatR
package to automatically replace =
with <-
.
library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5
The answer to the question "Why does x <- y = 5
throw an error but not x <- y <- 5
?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether =
or <-
was used.
To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3)
.
Secondly, it's clearer if we use prefix notation for assignment. So
x <- 5
`<-`(x, 5) #same thing
y = 5
`=`(y, 5) #also the same thing
The parser interprets x <- y <- 5
as
`<-`(x, `<-`(y, 5))
We might expect that x <- y = 5
would then be
`<-`(x, `=`(y, 5))
but actually it gets interpreted as
`=`(`<-`(x, y), 5)
This is because =
is lower precedence than <-
, as shown on the ?Syntax
help page.
Conda can also be used as package manager. It can be installed from Anaconda.
Alternatively, a free minimal installer is Miniconda.
If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
You can do this by using asynchronous Javascript SDK provided by facebook
Have a look at the following code
FB Javascript SDK initialization
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this
Add JQuery Library, I would preferred Google Library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
Add share dialog box (You can customize this dialog box by setting up parameters
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>
Now finally add image button
<img src = "share_button.png" id = "share_button">
For more detailed kind of information. please click here
this is an interesting question so let check it if you have a image for use as a website-icon then
Add this to your script
<link rel="icon" type="image/gif" href="animated_favicon1.gif" />
otherwise if you have a icon for your website icon then you chose
<link rel="shortcut icon" href="favicon.ico" />
I always use http://www.iconspedia.com/ for more icons
if my answer solved your problem then give me vote ok
You can provide more flexibility to your users by provide Browser Button to them
Private Sub btn_browser_file_Click()
Dim xRow As Long
Dim sh1 As Worksheet
Dim xl_app As Excel.Application
Dim xl_wk As Excel.Workbook
Dim WS As Workbook
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\"
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show
Range("H13").Activate
If .SelectedItems.Count <> 0 Then
xDirect$ = .SelectedItems(1) & "\"
Range("h12").Value = xDirect$
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
If (Format(FileDateTime(xDirect$ & "\" & xFname$), "MM/DD/YYYY") > Format(Range("H10").Value, "MM/DD/YYYY")) Then
ActiveCell.Offset(xRow) = xFname$
xRow = xRow + 1
xFname$ = Dir
Else
xFname$ = Dir
xRow = xRow
End If
Loop
End If
End With
with this piece of code you can achieve this, easily. Tested code
In order to get around the Enable Macro prompt I suggest
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Be sure to return it to default when you are done
Application.AutomationSecurity = msoAutomationSecurityLow
A reminder that the .SaveAs
function contains all optional arguments.I recommend removing CreatBackup:= False
as it is not necessary.
The most interesting way I think is to create an object of the workbook and access the .SaveAs
property that way. I have not tested it but you are never using Workbooks.Open
rendering Application.AutomationSecurity
inapplicable. Possibly saving resources and time as well.
That said I was able to execute the following without any notifications on Excel 2013 windows 10.
Option Explicit
Sub Convert()
OptimizeVBA (True)
'function to set all the things you want to set, but hate keying in
Application.AutomationSecurity = msoAutomationSecurityForceDisable
'this should stop those pesky enable prompts
ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to
xlsx stop popup"
Workbooks.Open ("Book1.xlsm")
ActiveWorkbook.SaveAs Filename:= _
"F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_
stop popup\Book1.xlsx" _
, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
Application.AutomationSecurity = msoAutomationSecurityLow
'make sure you set this up when done
Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_
to xlsx stop popup\Book1.xlsx") 'clean up
OptimizeVBA (False)
End Sub
Function OptimizeVBA(ByRef Status As Boolean)
If Status = True Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
Else
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Application.EnableEvents = True
End If
End Function
The ionic approach rocks:
https://dotnetzip.codeplex.com/wikipage?title=PS-Examples
supports passwords, other crypto methods, etc.
String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";
// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);
This happened to me once after I merged a pull request on Bitbucket.
I just had to do:
git fetch
My problem was solved. I hope this helps!!!
If you are in a directory where only root have access to write in system. Then you can directly use wget www.example.com/wget-test
using a standard user account. So it will hit the url but because of having no write permission file won't be saved..
This method is working fine for me as i am using this method for a cronjob.
Thanks.
sthx
First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.
Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.
Formatting doesn't fit general indentation rules, but I don't think it's a big deal.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
SQL Server 2008 R2:
For an existing database that you wish to "restore: from a backup of a different database follow these steps:
You don't need to use a subclass of Thread
to make this work - take a look at the simple example I'm posting below to see how:
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub
you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))
Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:
finished with non-zero exit value 1 One reason for this error to occure is that the file path to a resource file is to long:
Error: File path too long on Windows, keep below 240 characters
Fix: Move your project folder closer to the root of your disk
Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...
Do://folder/short_name/MyProject
Another reason could be duplicated resources or name spaces
Example:
<style name="MyButton" parent="android:Widget.Button">
<item name="android:textColor">@color/accent_color</item>
<item name="android:textColor">#000000</item>
</style>
I wrote this so I could edit all tables and columns to null at once:
select
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(range(10), 'r') #row=0, col=0
ax[1, 0].plot(range(10), 'b') #row=1, col=0
ax[0, 1].plot(range(10), 'g') #row=0, col=1
ax[1, 1].plot(range(10), 'k') #row=1, col=1
plt.show()
That is a binary operator in hibernate you should use
is not null
Have a look at 14.10. Expressions
Maybe it does not fit every use case, but
<input type="range" min="0" max="10" />
can do a fine job: fiddle.
Check the documentation.
Here is what I did in pub/jade
extends layout
block content
script(src="/jquery/dist/jquery.js")
script.
function doThePost() {
var jqXHR = $.ajax({
type:'post'
, url:<blabla>
, headers: {
'x-custom1': 'blabla'
, 'x-custom2': 'blabla'
, 'content-type': 'application/json'
}
, data: {
'id': 123456, blabla
}
})
.done(function(data, status, req) { console.log("done", data, status, req); })
.fail(function(req, status, err) { console.log("fail", req, status, err); });
}
h1= title
button(onclick='doThePost()') Click
No! You should avoid using HTML entities.
Instead of using HTML entities for symbols you should just put those symbols directly into your text and correctly encode your document.
£
you should use the character £
.??
which is currently the most commonly used single character for rupee. Other alternatives are using INR
, Rs.
or rupees
.When the new Unicode symbol for the Indian Rupee is introduced then could use that instead (but note that it will be a while before all browsers support it).
There is also a set of predefined Android strings such as "Ok", "Cancel" and many others - so you don't have to declare all. They're available simply by:
getString(android.R.string.ok)
(In this case, "Ok" string). BTW there are also other Android resources available like for example icons images etc.
You get your browser's language for your button. There's no way to change it programmatically.
It may be bacause you do not have jre installed. Thus go to http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html and download it.
There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip
.)
For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the
this
value [...].
(param1, param2, ...rest) => { statements }
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy(); }, 1000);
}
If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind
. You can optionally pass any function arguments to create partial functions.
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Again, in your case, try this:
if (this.options.destroyOnHide) {
setTimeout(this.tip.destroy.bind(this.tip), 1000);
}
The same functionality has also been implemented in Prototype (any other libraries?).
Function.prototype.bind
can be implemented like this if you want custom backwards compatibility (but please observe the notes).
If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this
context of a function.
jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.
$.proxy(function, context[, additionalArguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}
It's available in Underscore.js, as well as lodash, as _.bind(...)
1,2
bind Bind a function to an object, meaning that whenever the function is called, the value of
this
will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.
_.bind(function, object, [*arguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}
Another way would be:
string="Paris, France, Europe"
IFS=', ' arr=(${string})
Now your elements are stored in "arr" array. To iterate through the elements:
for i in ${arr[@]}; do echo $i; done
What are you using when operate with CLOB?
In all events you can do it with PL/SQL
DECLARE
str varchar2(32767);
BEGIN
str := 'Very-very-...-very-very-very-very-very-very long string value';
update t1 set col1 = str;
END;
/
Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the
paintComponent(){
super...
}
and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();
I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.
Doug Hauf
htmlspecialchars
may be used:
When there is no need to encode all characters which have their HTML equivalents.
If you know that the page encoding match the text special symbols, why would you use htmlentities
? htmlspecialchars
is much straightforward, and produce less code to send to the client.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.
When the data will be processed not only through a browser (to avoid decoding HTML entities),
If the output is XML (see the answer by Artefacto).
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
Simple fix to this was setting showAsAction
to always
in menu.xml
in res/menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/add_alarm"
android:icon="@drawable/ic_action_name"
android:orderInCategory="100"
android:title="Add"
app:showAsAction="always"
android:visible="true"/>
</menu>
I had this problem when trying to change directory, using the character _
. The solution was to use a string to change directories.
C:\> cd "my_new_dir"
Edit: fsw
has been merged into fswatch
. In this answer, any reference to fsw
should now read fswatch
.
I wrote an fswatch
replacement in C++ called fsw
which features several improvements:
It's a GNU Build System project which builds on any supported platform (OS X v. >= 10.6) with
./configure && make && sudo make install
Multiple paths can be passed as different arguments:
fsw file-0 ... file-n
It dumps a detailed record with all the event information such as:
Sat Feb 15 00:53:45 2014 - /path/to/file:inodeMetaMod modified isFile
Its output is easy to parse so that fsw
output can be piped to another process.
-l, --latency
.-n, --numeric
.strftime
format strings with -t, --time-format
.-u, --utc-time
.Getting fsw:
fsw
is hosted on GitHub and can be obtained cloning its repository:
git clone https://github.com/emcrisostomo/fsw
Installing fsw:
fsw
can be installed using the following commands:
./configure && make && sudo make install
Further information:
I also wrote an introductory blog post where you can find a couple of examples about how fsw
works.
You can also use :
to embed documentation in a function.
Assume you have a library script mylib.sh
, providing a variety of functions. You could either source the library (. mylib.sh
) and call the functions directly after that (lib_function1 arg1 arg2
), or avoid cluttering your namespace and invoke the library with a function argument (mylib.sh lib_function1 arg1 arg2
).
Wouldn't it be nice if you could also type mylib.sh --help
and get a list of available functions and their usage, without having to manually maintain the function list in the help text?
#!/bin/bash # all "public" functions must start with this prefix LIB_PREFIX='lib_' # "public" library functions lib_function1() { : This function does something complicated with two arguments. : : Parameters: : ' arg1 - first argument ($1)' : ' arg2 - second argument' : : Result: : " it's complicated" # actual function code starts here } lib_function2() { : Function documentation # function code here } # help function --help() { echo MyLib v0.0.1 echo echo Usage: mylib.sh [function_name [args]] echo echo Available functions: declare -f | sed -n -e '/^'$LIB_PREFIX'/,/^}$/{/\(^'$LIB_PREFIX'\)\|\(^[ \t]*:\)/{ s/^\('$LIB_PREFIX'.*\) ()/\n=== \1 ===/;s/^[ \t]*: \?['\''"]\?/ /;s/['\''"]\?;\?$//;p}}' } # main code if [ "${BASH_SOURCE[0]}" = "${0}" ]; then # the script was executed instead of sourced # invoke requested function or display help if [ "$(type -t - "$1" 2>/dev/null)" = function ]; then "$@" else --help fi fi
A few comments about the code:
declare -f
to enumerate all available functions, then filters them through sed to only display functions with the appropriate prefix.mylib.sh function1
and it gets translated internally to lib_function1
. This is an exercise left to the reader.$1
. At the same time, it will clutter your namespace if you source the library. If you don't like that, you can either change the name to something like lib_help
or actually check the args for --help
in the main code and invoke the help function manually.You could "reset" your repository to any commit you want (e.g. 1 month ago).
Use git-reset for that:
git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]
If you use the enumerable mixin (as Rails does) you can do something similar to the php snippet listed. Just use the each_slice method and flatten the hash.
require 'enumerator'
['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
# is equivalent to...
{'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
Less monkey-patching required.
However, this does cause problems when you have a recursive array or a hash with array values. In ruby 1.9 this problem is solved with a parameter to the flatten method that specifies how deep to recurse.
# Ruby 1.8
[1,2,[1,2,3]].flatten
=> [1,2,1,2,3]
# Ruby 1.9
[1,2,[1,2,3]].flatten(0)
=> [1,2,[1,2,3]]
As for the question of whether this is a code smell, I'm not sure. Usually when I have to bend over backwards to iterate over something I step back and realize I'm attacking the problem wrong.
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
When you call figure
, simply number the plot.
x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)
z = np.sin(x)
plt.figure(1)
plt.plot(x, z)
w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Edit: Note that you can number the plots however you want (here, starting from 0
) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1
("Matlab Style" according to the docs).
Try this
$('#thisElement .classToSelect').each(function(i){
// do stuff
});
Hope it will help
var sibling = node.nextSibling;
This will return the sibling immediately after it, or null no more siblings are available. Likewise, you can use previousSibling
.
[Edit] On second thought, this will not give the next div
tag, but the whitespace after the node. Better seems to be
var sibling = node.nextElementSibling;
There also exists a previousElementSibling
.
You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv
Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)
which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function
You can cast even just one of them, but for consistency you may want to explicitly cast both so something like v = (float)s / (float)t should work.
I just moved to Spring Boot 1.4 and found these properties were renamed:
spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.time-between-eviction-runs-millis=3600000
spring.datasource.dbcp.validation-query=SELECT 1
Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
A Hacky way to combine multiple statements into a single statement in python is to use the "and" keyword as a short-circuit operator. Then you can use this single statement directly as part of the lambda expression.
This is similar to using "&&" as the short-circuit operator in shell languages such as bash.
Also note: You can always fix a function statement to return a true value by wrapping the function.
Example:
def p2(*args):
print(*args)
return 1 # a true value
junky = lambda x, y: p2('hi') and p2('there') and p2(x) and p2(y)
junky("a", "b")
On second thought, its probably better to use 'or' instead of 'and' since many functions return '0' or None on success. Then you can get rid of the wrapper function in the above example:
junky = lambda x, y: print('hi') or print('there') or print(x) or print(y)
junky("a", "b")
'and' operate will evaluate the expressions until it gets to the first zero return value. after which it short-circuits. 1 and 1 and 0 and 1 evaluates: 1 and 1 and 0, and drops 1
'or' operate will evaluate the expressions until it gets to the first non-zero return value. after which it short-circuits.
0 or 0 or 1 or 0 evaluates 0 or 0 or 1, and drops 0
Here is swift3 code with @IBInspectable
create a new file Cocoa Touch Class Swift File
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var leftBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(cgColor: layer.borderColor!)
line.tag = 110
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
line.tag = 110
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
@IBInspectable var rightBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
line.tag = 110
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
@IBInspectable var bottomBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = borderColor
line.tag = 110
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
}
}
func removeborder() {
for view in self.subviews {
if view.tag == 110 {
view.removeFromSuperview()
}
}
}
}
and replace the file with the below code and you will get the option in storyboard attribute inspector like this
Enjoy :)
Imagine you have a window open on http://www.foo.com/bar/page.html
In all of them (HTML, Javascript and CSS):
opened_url = http://www.foo.com/bar/page.html
base_path = http://www.foo.com/bar/
home_path = http://www.foo.com/
/kitten.png = Home_path/kitten.png
kitten.png = Base_path/kitten.png
In HTML and Javascript, the base_path is based on the opened window. In big javascript projects you need a BASEPATH
or root
variable to store the base_path occasionally. (like this)
In CSS the opened url is the address of which your .css is stored or loaded, its not the same like javascript with current opened window in this case.
And for being more secure in absolute paths it is recommended to use //
instead of http://
for possible future migrations to https://
. In your own example, use it this way:
<img src="//www.foo.com/images/kitten.png">
DAYS(start_date,end_date):
For example:
DAYS(A1,TODAY())
You could try to wiggle down the nesting by implementing parallel workers (like in cluster computing) instead of increasing the number of nesting function calls.
For example: you define a limited number of slots (eg. 100) and monitor the number of "workers" assigned to each/some of them. If any slots become free, you put the waiting workers "in them".
Just use crontab -e
and follow the tutorial here.
Look at point 3 for a guide on how to specify the frequency.
Based on your requirement, it should effectively be:
*/10 * * * * /usr/bin/python script.py
If you face this issue while using Azure Container Registry, you can solve it by logging in to your registry first.
docker login yourregistry.azurecr.io
And then tag your image to match the host name of your registry.
docker image tag yourimagename:[version] yourregistry.azurecr.io/yourimagename:[version]
And then finally push it.
docker push yourregistry.azurecr.io/yourimagename:[version]
user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.
Parent.component.ts
export class Notifier {
valueChanged: (data: number) => void = (d: number) => { };
}
export class Parent {
notifyObj = new Notifier();
tellChild(newValue: number) {
this.notifyObj.valueChanged(newValue); // inform child
}
}
Parent.component.html
<my-child-comp [notify]="notifyObj"></my-child-comp>
Child.component.ts
export class ChildComp implements OnInit{
@Input() notify = new Notifier(); // create object to satisfy typescript
ngOnInit(){
this.notify.valueChanged = (d: number) => {
console.log(`Parent has notified changes to ${d}`);
// do something with the new value
};
}
}
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
If you can live with 01 for January instead of 1, then try...
d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")
You can check the docs for other formatting directives.
Windows 7 64 bit, Intel i7
This happened to me as well after I updated the SDK to be Jelly Bean compatible. The folder platform-tools\lib was gone. I also wasn't able to uninstall/reinstall the program-tools in the SDK manager at first. It gave me the error that a particular file in the android\temp folder was not there. I had to change the permissions on the android folder to allow every action, and that solved it.
Firstly, if you're doing MVVM you would typically have this information available to your VM via separate properties bound from the view. That saves you having to pass any parameters at all to your commands.
However, you could also multi-bind and use a converter to create the parameters:
<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConverter}">
<Binding Path="Width" ElementName="MyCanvas"/>
<Binding Path="Height" ElementName="MyCanvas"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
In your converter:
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
Then, in your command execution logic:
public void OnExecute(object parameter)
{
var values = (object[])parameter;
var width = (double)values[0];
var height = (double)values[1];
}
You can use a one-liner with DOCKER_HOST
variable:
docker save app:1.0 | gzip | DOCKER_HOST=ssh://user@remotehost docker load
I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.
$(document).ready(function($) {
$.extend( true, jQuery.fn, {
imagePreview: function( options ){
var defaults = {};
if( options ){
$.extend( true, defaults, options );
}
$.each( this, function(){
var $this = $( this );
$this.bind( 'change', function( evt ){
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
$('#imageURL').attr('src',e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
});
});
}
});
$( '#fileinput' ).imagePreview();
});
Why don't just use The Round-trip ("O", "o") Format Specifier?
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.
The O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:
public class Example
{
public static void Main()
{
DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Unspecified);
Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind);
DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Utc);
Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);
DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Local);
Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);
DateTimeOffset dto = new DateTimeOffset(lDat);
Console.WriteLine("{0} --> {0:O}", dto);
}
}
// The example displays the following output:
// 6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000
// 6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z
// 6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00
//
// 6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00
Use variable capture to "pass in" parameters.
var x = rawData;
Task.Run(() =>
{
// Do something with 'x'
});
You also could use rawData
directly but you must be careful, if you change the value of rawData
outside of a task (for example a iterator in a for
loop) it will also change the value inside of the task.
Use Shift + Insert like in linux bash
Edit: It works even in putty.
Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
Essentially you have the following options
FragmentManager.popBackStack(String name,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.getBackStackEntryCount()
/getBackStackEntryAt().getId()
to retrieve the ID of the first entry on the back stack, and
FragmentManager.popBackStack(int id,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
is supposed to pop the entire back stack... I think the documentation for
that is just wrong. (Actually I guess it just doesn't cover the case where
you pass in POP_BACK_STACK_INCLUSIVE
), // Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }
// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }
var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');
This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.
If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.
Here is how to do a quick check to see if n.fn.init[0]
is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout
function like this:
function timeout(){
...your selector function that returns n.fn.init[0] goes here...
}
setTimeout(timeout, 5000)
This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.
This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.
The preferred ways to check if the DOM is loaded before executing your function are as follows:
1) Wrap your selector function in
$(document).ready(function(){ ... your selector function... };
2) If that doesn't work, use DOMContentLoaded
3) Try window.onload, which waits for all the images to load first, so its least preferred
window.onload = function () { ... your selector function... }
4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.
5) Finally, you can stick with hard-coded setTimeout
function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.
This list of fixes is probably far from perfect so everyone is welcome to edit it.
Go to SDK path: SDK\extras\android\m2repository\com\android\support\appcompat-v7
to see correct dependency name, then change name if your dependency is alpha version:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.0.0'
}
to :
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}
Navigate back/forward
Ctrl + Alt + Left/Right