I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.
The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.
lipo -create libPhone.a libSimulator.a -output libUniversal.a
I tried it and it works!
Do something like this:
typedef std::map<std::string, std::string> InnerMap;
typedef std::map<std::string, InnerMap> OuterMap;
Outermap mm;
...//set the initial values
for (OuterMap::iterator i = mm.begin(); i != mm.end(); ++i) {
InnerMap &im = i->second;
for (InnerMap::iterator ii = im.begin(); ii != im.end(); ++ii) {
std::cout << "map["
<< i->first
<< "]["
<< ii->first
<< "] ="
<< ii->second
<< '\n';
}
}
I'll interpret your question as two questions: 1) why ->
even exists, and 2) why .
does not automatically dereference the pointer. Answers to both questions have historical roots.
Why does ->
even exist?
In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator ->
had very exclusive meaning, not synonymous with *
and .
combination
The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare
struct S {
int a;
int b;
};
and name a
would stand for offset 0, while name b
would stand for offset 2 (assuming int
type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare
struct X {
int a;
int x;
};
and that would be OK, since the name a
would consistently stand for offset 0. But this additional declaration
struct Y {
int b;
int a;
};
would be formally invalid, since it attempted to "redefine" a
as offset 2 and b
as offset 0.
And this is where the ->
operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these
int i = 5;
i->b = 42; /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */
The first assignment was interpreted by the compiler as "take address 5
, add offset 2
to it and assign 42
to the int
value at the resultant address". I.e. the above would assign 42
to int
value at address 7
. Note that this use of ->
did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).
This sort of trickery was not possible with *
and .
combination. You could not do
(*i).b = 42;
since *i
is already an invalid expression. The *
operator, since it is separate from .
, imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the ->
operator, which is independent from the type of the left-hand operand.
As Keith noted in the comments, this difference between ->
and *
+.
combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1
be of pointer type, the expression E1->MOS
is exactly equivalent to (*E1).MOS
Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of ->
operator became fully identical to the functionality of *
and .
combination.
Why can't .
dereference the pointer automatically?
Again, in CRM version of the language the left operand of the .
operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->
, as explained above). Note that CRM did not require the left operand of .
to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this
struct S { int a, b; };
struct T { float x, y, z; };
struct T c;
c.b = 55;
In this case the compiler would write 55
into an int
value positioned at byte-offset 2 in the continuous memory block known as c
, even though type struct T
had no field named b
. The compiler would not care about the actual type of c
at all. All it cared about is that c
was an lvalue: some sort of writable memory block.
Now note that if you did this
S *s;
...
s.b = 42;
the code would be considered valid (since s
is also an lvalue) and the compiler would simply attempt to write data into the pointer s
itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.
I.e. in that version of the language your proposed idea about overloading operator .
for pointer types would not work: operator .
already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.
Of course, this weird functionality is not a very strong reason against introducing overloaded .
operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.
(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)
If your site is not live yet, and you just want to update the stylesheet at your pleased intervals, then use this:
Ctrl + F5
This will force your browser to reload and refresh all the resources related to the website's page.
So everytime you change something in your stylesheet and you wanna view the new results, use this.
On Mac OS Chrome use: Command + Shift + R.
Another approach to sort HTML table. (based on W3.JS HTML Sort)
/* Facility Name */_x000D_
$('#bioTable th:eq(0)').addClass("control-label pointer");_x000D_
/* Phone # */_x000D_
$('#bioTable th:eq(1)').addClass("not-allowed");_x000D_
/* City */_x000D_
$('#bioTable th:eq(2)').addClass("control-label pointer");_x000D_
/* Specialty */_x000D_
$('#bioTable th:eq(3)').addClass("not-allowed");_x000D_
_x000D_
_x000D_
var collection = [{_x000D_
"FacilityName": "MinION",_x000D_
"Phone": "999-8888",_x000D_
"City": "France",_x000D_
"Specialty": "Genetic Prediction"_x000D_
}, {_x000D_
"FacilityName": "GridION X5",_x000D_
"Phone": "999-8812",_x000D_
"City": "Singapore",_x000D_
"Specialty": "DNA Assembly"_x000D_
}, {_x000D_
"FacilityName": "PromethION",_x000D_
"Phone": "929-8888",_x000D_
"City": "San Francisco",_x000D_
"Specialty": "DNA Testing"_x000D_
}, {_x000D_
"FacilityName": "iSeq 100 System",_x000D_
"Phone": "999-8008",_x000D_
"City": "Christchurch",_x000D_
"Specialty": "gDNA-mRNA sequencing"_x000D_
}]_x000D_
_x000D_
$tbody = $("#bioTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
content: "*";_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.pointer {_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.not-allowed {_x000D_
cursor: not-allowed;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="bioTable" class="w3-table-all">_x000D_
<thead>_x000D_
<tr>_x000D_
<th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th>_x000D_
<th>Phone #</th>_x000D_
<th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th>_x000D_
<th>Specialty</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.
I am assuming that you had imported the project into your desktop eclipse installation? If that is the case, you should just select Project > Clean. Then rebuild your project. Worked like a charm for me.
You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).
Install python and create a sample file test.py
import sys
# print sys.argv[0] prints test.py
# print sys.argv[1] prints your_var_1
def hello():
print "Hi" + " " + sys.argv[1]
if __name__ == "__main__":
hello()
Create a method in your Web API Server
[HttpGet]
public string SayHi(string id)
{
string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
return p.StandardOutput.ReadToEnd();
}
And now for your JavaScript:
function processSayingHi() {
var your_param = 'abc';
$.ajax({
url: '/api/your_controller_name/SayHi/' + your_param,
type: 'GET',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
Remember that your .py file won't run on your user's computer, but instead on the server.
Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.
The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.
As a bonus, text is responsively centered in the quarters.
HTML:
<head>
<meta charset="utf-8">
<title>Box model</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="title">Title Bar</h1>
<div id="dividedbox">
<div class="quarter" id="NW">
<p>NW</p>
</div>
<div class="quarter" id="NE">
<p>NE</p>
</div>
<div class="quarter" id="SE">
<p>SE</p>
</div>?
<div class="quarter" id="SW">
<p>SW</p>
</div>
</div>
</body>
</html>
CSS:
html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%} /* for div growth */
.quarter {position: absolute; width:50%; height:50%; /* gives quarters their size */
display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0; left:0; background:orange; }
#NE { top:0; left:50%; background:lightblue; }
#SW { top:50%; left:0; background:green; }
#SE { top:50%; left:50%; background:red; }
The documentation currently shows that as of 3.0, $.post will accept the settings object, meaning that you can use the $.ajax options. 3.0 is not released yet and on the commit they're talking about hiding the reference to it in the docs, but look for it in the future!
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
The only way to reliably detect if a socket is still connected is to periodically try to send data. Its usually more convenient to define an application level 'ping' packet that the clients ignore, but if the protocol is already specced out without such a capability you should be able to configure tcp sockets to do this by setting the SO_KEEPALIVE socket option. I've linked to the winsock documentation, but the same functionality should be available on all BSD-like socket stacks.
int i = 4567789;
int digit1 = int.Parse(i.ToString()[0].ToString());
I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)
To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:
sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
If you are interested in html formatted email, make sure to pass Content-type: text/html;
in the header. Example:
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mail function.
Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).
# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)
cursor = conn.cursor()
# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
print('Table exists. I can do my custom stuff here now.... ')
pass
else:
# then table doesn't exist.
custRET = myCustFunc(foo,bar) # replace this with your custom logic
I like the answer that attempts to do the translate, however, while using the code it doesn't like columns that are not VARCHAR type such as BIGINT or DATETIME. I needed something similar today so I took the time to modify it more to my liking. It is also now encapsulated in a function which is the closest thing I could find to just typing describe as oracle handles it. I may still be missing a few data types in my case statement but this works for everything I tried it on. It also orders by ordinal position. this could be expanded on to include primary key columns easily as well.
CREATE FUNCTION dbo.describe (@TABLENAME varchar(50))
returns table
as
RETURN
(
SELECT TOP 1000 column_name AS [ColumnName],
IS_NULLABLE AS [IsNullable],
DATA_TYPE + '(' + CASE
WHEN DATA_TYPE = 'varchar' or DATA_TYPE = 'char' THEN
CASE
WHEN Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) = -1 THEN 'Max'
ELSE Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5))
END
WHEN DATA_TYPE = 'decimal' or DATA_TYPE = 'numeric' THEN
Cast(NUMERIC_PRECISION AS VARCHAR(5))+', '+Cast(NUMERIC_SCALE AS VARCHAR(5))
WHEN DATA_TYPE = 'bigint' or DATA_TYPE = 'int' THEN
Cast(NUMERIC_PRECISION AS VARCHAR(5))
ELSE ''
END + ')' AS [DataType]
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = @TABLENAME
order by ordinal_Position
);
GO
once you create the function here is a sample table that I used
create table dbo.yourtable
(columna bigint,
columnb int,
columnc datetime,
columnd varchar(100),
columne char(10),
columnf bit,
columng numeric(10,2),
columnh decimal(10,2)
)
Then you can execute it as follows
select * from describe ('yourtable')
It returns the following
ColumnName IsNullable DataType
columna NO bigint(19)
columnb NO int(10)
columnc NO datetime()
columnd NO varchar(100)
columne NO char(10)
columnf NO bit()
columng NO numeric(10, 2)
columnh NO decimal(10, 2)
hope this helps someone.
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});
You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later.
Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.
I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
Quoting Yoga...
For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/
I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...
/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml
...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.
There are two main scenarios
You haven't pushed the commit yet
If the problem was extra files you commited (and you don't want those on repository), you can remove them using git rm
and then commiting with --amend
git rm <pathToFile>
You can also remove entire directories with -r
, or even combine with other Bash commands
git rm -r <pathToDirectory>
git rm $(find -name '*.class')
After removing the files, you can commit, with --amend option
git commit --amend -C HEAD # the -C option is to use the same commit message
This will rewrite your recent local commit removing the extra files, so, these files will never be sent on push and also will be removed from your local .git repository by GC.
You already pushed the commit
You can apply the same solution of the other scenario and then doing git push
with the -f
option, but it is not recommended since it overwrites the remote history with a divergent change (it can mess your repository).
Instead, you have to do the commit without --amend
(remember this about -amend`: That option rewrites the history on the last commit).
<form id = "uploadForm" name = "uploadForm" enctype="multipart/form-data">
<label for="uploadFile">Upload Your File</label>
<input type="file" name="uploadFile" id="uploadFile">
</form>
<script>
$('#uploadFile').change(function(){
var fileName = this.files[0].name;
var fileSize = this.files[0].size;
var fileType = this.files[0].type;
alert('FileName : ' + fileName + '\nFileSize : ' + fileSize + ' bytes');
});
</script>
Note: To get the uploading file name means then use jquery val() method.
For Ex:
var fileName = $('#uploadFile').val();
I checked this above code before post, it works perfectly.!
Don't use normal
android:drawableLeft
etc... with vector drawables, else it will crash in lower API versions. (I have faced it in live app)
If you are using vector drawable, then you must
It was released in version 1.1.0-alpha01
, so appcompat version should be at least 1.1.0-alpha01
. Current latest version is 1.1.0-alpha02
, use latest versions for better reliability, see release notes - link.
implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
Use AppCompatTextView
/AppCompatButton
/AppCompatEditText
app:drawableLeftCompat
, app:drawableTopCompat
, app:drawableRightCompat
, app:drawableBottomCompat
, app:drawableStartCompat
and app:drawableEndCompat
If you don't need vector drawable, then you can
android:drawableLeft
, android:drawableRight
, android:drawableBottom
, android:drawableTop
TextView
, Button
& EditText
or AppCompat
classes.You can achieve Output like below -
use a simple formula: WHO.WHAT = VALUE
where,
WHO is the element in the storyboard you want to make changes to for eg. label
WHAT is the property of that element you wish to change for eg. text
VALUE is the change that you wish to be displayed
for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1
In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road
so our final code will be as follows: Final code
screenshot 1 changes to screenshot 2 once the above code is executed.
I hope this solution helps you solve your issue. Thank you!
You can change or import a theme by using the icon that the "Duplicate Theme" arrow is pointing to in the photo.
Every one sees color differently. Most times a small change in contrast is all you need. Removing the hase from Dracula by changing the Background color to 242527 was perfect for me.
Use detectOS.js:
var Detect = {
init: function () {
this.OS = this.searchString(this.dataOS);
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
dataOS : [
{
string: navigator.platform,
subString: 'Win',
identity: 'Windows'
},
{
string: navigator.platform,
subString: 'Mac',
identity: 'macOS'
},
{
string: navigator.userAgent,
subString: 'iPhone',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPad',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPod',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'Android',
identity: 'Android'
},
{
string: navigator.platform,
subString: 'Linux',
identity: 'Linux'
}
]
};
Detect.init();
console.log("We know your OS – it's " + Detect.OS + ". We know everything about you.");
Try PyPDF2.
There is a good tutorial here: https://automatetheboringstuff.com/chapter13/
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
This error in REACT. following steps
Go to Project Root Directory Package.json file
add "type":"module";
Save it and Restart Server
adb shell am start -n '<appPackageName>/.<appActitivityName>
Ex:
adb shell am start -n 'com.android.settings/.wifi.WifiStatusTest'
You can use APK-INFO application to know the list of App Activities with respect to each App Package
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
I believe this might be just repeat answer, but just to clarify, I got this on a @OneToOne
mapping as well as a @OneToMany
. In both cases, it was the fact that the Child
object I was adding to the Parent
wasn't saved in the database yet. So when I added the Child
to the Parent
, then saved the Parent
, Hibernate would toss the "object references an unsaved transient instance - save the transient instance before flushing"
message when saving the Parent.
Adding in the cascade = {CascadeType.ALL}
on the Parent's
reference to the Child
solved the problem in both cases. This saved the Child
and the Parent
.
Sorry for any repeat answers, just wanted to further clarify for folks.
@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
return performanceLog;
}
How can I make xargs execute the command exactly once for each line of input given?
-L 1
is the simple solution but it does not work if any of the files contain spaces in them. This is a key function of find's -print0
argument – to separate the arguments by '\0' character instead of whitespace. Here's an example:
echo "file with space.txt" | xargs -L 1 ls
ls: file: No such file or directory
ls: with: No such file or directory
ls: space.txt: No such file or directory
A better solution is to use tr
to convert newlines to null (\0
) characters, and then use the xargs -0
argument. Here's an example:
echo "file with space.txt" | tr '\n' '\0' | xargs -0 ls
file with space.txt
If you then need to limit the number of calls you can use the -n 1
argument to make one call to the program for each input:
echo "file with space.txt" | tr '\n' '\0' | xargs -0 -n 1 ls
This also allows you to filter the output of find before converting the breaks into nulls.
find . -name \*.xml | grep -v /target/ | tr '\n' '\0' | xargs -0 tar -cf xml.tar
Call second ajax from 'complete'
Here is the example
var dt='';
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
dt=data;
/*Do something*/
},
complete:function(){
$.ajax({
var a=dt; // This line shows error.
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
/*do some thing in second function*/
},
});
}
});
I like to write a small plugin to make things cleaner:
$.fn.setClass = function(classes) {
this.attr('class', classes);
return this;
};
That way you can simply do
$('button').setClass('btn btn-primary');
You can use linear indexing to access each element.
for idx = 1:numel(array)
element = array(idx)
....
end
This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual
CURDATE()
returns the DATE part of the current time. Manual on CURDATE()
NOW()
returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().
You may consider a third party email service who handles delivery issues:
you can use HashMap<String, List<Integer>>
to merge both hashmaps and avoid losing elements paired with the same key.
HashMap<String, Integer> map1 = new HashMap<>();
HashMap<String, Integer> map2 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
map1.put("key3", 3);
map2.put("key1", 4);
map2.put("key2", 5);
map2.put("key3", 6);
HashMap<String, List<Integer>> map3 = new HashMap<>();
map1.forEach((str, num) -> map3.put(str, new ArrayList<>(Arrays.asList(num))));
//checking for each key if its already in the map, and if so, you just add the integer to the list paired with this key
for (Map.Entry<String, Integer> entry : map2.entrySet()) {
Integer value = entry.getValue();
String key = entry.getKey();
if (map3.containsKey(key)) {
map3.get(key).add(value);
} else {
map3.put(key, new ArrayList<>(Arrays.asList(value)));
}
}
map3.forEach((str, list) -> System.out.println("{" + str + ": " + list + "}"));
output:
{key1: [1, 4]}
{key2: [2, 5]}
{key3: [3, 6]}
It is specific from your driver. You need to supply a parameter in your Java program to tell it the time zone you want to use.
java -Duser.timezone="America/New_York" GetCurrentDateTimeZone
Further this:
to_char(new_time(sched_start_time, 'CURRENT_TIMEZONE', 'NEW_TIMEZONE'), 'MM/DD/YY HH:MI AM')
May also be of value in handling the conversion properly. Taken from here
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
In html
button ng-click="myMethod()">Videos</button>
In angular
$scope.myMethod = function () {
$(".collapse").collapse('hide'); //if you want to hide
$(".collapse").collapse('toggle'); //if you want toggle
$(".collapse").collapse('show'); //if you want to show
}
Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).
There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.
hope this may help you:
SELECT CAST(LoginTime AS DATE)
FROM AuditTrail
If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month
Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:
SELECT DATABASE() FROM DUAL;
There is much discussion over whether or not FROM DUAL
should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use the following instead:
SELECT DATABASE();
That said, it is perhaps important to note, that while FROM DUAL
does not actually do anything, it is valid MySQL syntax. From a strict perspective, including braces in a single line conditional in JavaScript also does not do anything, but it is still a valid practice.
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
As an extra, you can take the Enum.Parse
answers already provided and put them in an easy-to-use static method in a helper class.
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}
And use it like so:
{
Content = ParseEnum<ContentEnum>(fileContentMessage);
};
Especially helpful if you have lots of (different) Enums to parse.
There are different eclipse plugins available to manage Tomcat server and create war file.
For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.
Use the bitwise AND
operator.
function oddOrEven(x) {_x000D_
return ( x & 1 ) ? "odd" : "even";_x000D_
}_x000D_
_x000D_
function checkNumber(argNumber) {_x000D_
document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);_x000D_
}_x000D_
_x000D_
checkNumber(17);
_x000D_
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
_x000D_
If you don't want a string return value, but rather a boolean one, use this:
var isOdd = function(x) { return x & 1; };
var isEven = function(x) { return !( x & 1 ); };
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
Well, once you have your font, you can invoke deriveFont
. For example,
helvetica = helvetica.deriveFont(Font.BOLD, 12f);
Changes the font's style to bold and its size to 12 points.
When you get this vague error message, you can find out the more specific error by running
SHOW ENGINE INNODB STATUS;
The most common reasons are that when creating a foreign key, both the referenced field and the foreign key field need to match:
Another cause of this error is:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note: implements Serializable in your Question class.
I hope this helps you
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public int getNavigationBarHeight()
{
boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0 && !hasMenuKey)
{
return getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
If your instance is called SQLEXPRESS
, then you need to use .\SQLEXPRESS
or (local)\SQLEXPRESS
or yourMachineName\SQLEXPRESS
as your server name - if you have a named instance, you need to specify that name of the instance in your server name.
If you want ex. change all country codes in .json file from uppercase to lowercase:
ctrl+h
alt+r
alt+c
Find: ([A-Z]{2,})
Replace: $1
alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter
ex file:
[
{"id": "PL", "name": "Poland"},
{"id": "NZ", "name": "New Zealand"},
...
]
Long string: Just use echo($var);
instead of dump($var);
.
Object or Array: var_dump('<pre>'.json_encode($var).'</pre>);'
static byte[] discardWhitespace(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++) {
switch (data[i]) {
case (byte) '\n' :
case (byte) '\r' :
break;
default:
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
Code found on commons-codec project.
visualize the rolling averages to see if it makes sense. I don't understand why sum was used when the rolling average was requested.
df=pd.read_csv('poll.csv',parse_dates=['enddate'],dtype={'favorable':np.float,'unfavorable':np.float,'other':np.float})
df.set_index('enddate')
df=df.fillna(0)
fig, axs = plt.subplots(figsize=(5,10))
df.plot(x='enddate', ax=axs)
plt.show()
df.rolling(window=3,min_periods=3).mean().plot()
plt.show()
print("The larger the window coefficient the smoother the line will appear")
print('The min_periods is the minimum number of observations in the window required to have a value')
df.rolling(window=6,min_periods=3).mean().plot()
plt.show()
Check the $VIRTUAL_ENV
environment variable.
The $VIRTUAL_ENV
environment variable contains the virtual environment's directory when in an active virtual environment.
>>> import os
>>> os.environ['VIRTUAL_ENV']
'/some/path/project/venv'
Once you run deactivate
/ leave the virtual environment, the $VIRTUAL_ENV
variable will be cleared/empty. Python will raise a KeyError
because the environment variable was unset.
>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'
These same environment variable checks can of course also be done outside of the Python script, in the shell.
In PHP>=5.3 and based on Luc M's answer (the first one) you can make use of closures like this
array_walk_recursive($aNonFlat, function(&$v, $k, &$t){$t->aFlat[] = $v;}, $objTmp);
I love this because I don't have to surround the function's code with quotes like when using create_function()
bs := string(body)
should be enough to give you a string.
From there, you can use it as a regular string.
A bit as in this thread:
var client http.Client
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
log.Info(bodyString)
}
See also GoByExample.
As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)
?" (reverse problem, but the same conclusion apply) where zzzz mentioned:
Some conversions are the same as a cast, like
uint(myIntvar)
, which just reinterprets the bits in place.
Sonia adds:
Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. Thebytes.Buffer
type is often useful.
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
this
is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.
super
allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.
To quote the great explanation of Eric
What happens? Do you want the list of giraffes to contain a tiger? Do you want a crash? or do you want the compiler to protect you from the crash by making the assignment illegal in the first place? We choose the latter.
But what if you want to choose for a runtime crash instead of a compile error? You would normally use Cast<> or ConvertAll<> but then you will have 2 problems: It will create a copy of the list. If you add or remove something in the new list, this won't be reflected in the original list. And secondly, there is a big performance and memory penalty since it creates a new list with the existing objects.
I had the same problem and therefore I created a wrapper class that can cast a generic list without creating an entirely new list.
In the original question you could then use:
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
IList<A> listOfA = new List<C>().CastList<C,A>(); // now ok!
}
}
and here the wrapper class (+ an extention method CastList for easy use)
public class CastedList<TTo, TFrom> : IList<TTo>
{
public IList<TFrom> BaseList;
public CastedList(IList<TFrom> baseList)
{
BaseList = baseList;
}
// IEnumerable
IEnumerator IEnumerable.GetEnumerator() { return BaseList.GetEnumerator(); }
// IEnumerable<>
public IEnumerator<TTo> GetEnumerator() { return new CastedEnumerator<TTo, TFrom>(BaseList.GetEnumerator()); }
// ICollection
public int Count { get { return BaseList.Count; } }
public bool IsReadOnly { get { return BaseList.IsReadOnly; } }
public void Add(TTo item) { BaseList.Add((TFrom)(object)item); }
public void Clear() { BaseList.Clear(); }
public bool Contains(TTo item) { return BaseList.Contains((TFrom)(object)item); }
public void CopyTo(TTo[] array, int arrayIndex) { BaseList.CopyTo((TFrom[])(object)array, arrayIndex); }
public bool Remove(TTo item) { return BaseList.Remove((TFrom)(object)item); }
// IList
public TTo this[int index]
{
get { return (TTo)(object)BaseList[index]; }
set { BaseList[index] = (TFrom)(object)value; }
}
public int IndexOf(TTo item) { return BaseList.IndexOf((TFrom)(object)item); }
public void Insert(int index, TTo item) { BaseList.Insert(index, (TFrom)(object)item); }
public void RemoveAt(int index) { BaseList.RemoveAt(index); }
}
public class CastedEnumerator<TTo, TFrom> : IEnumerator<TTo>
{
public IEnumerator<TFrom> BaseEnumerator;
public CastedEnumerator(IEnumerator<TFrom> baseEnumerator)
{
BaseEnumerator = baseEnumerator;
}
// IDisposable
public void Dispose() { BaseEnumerator.Dispose(); }
// IEnumerator
object IEnumerator.Current { get { return BaseEnumerator.Current; } }
public bool MoveNext() { return BaseEnumerator.MoveNext(); }
public void Reset() { BaseEnumerator.Reset(); }
// IEnumerator<>
public TTo Current { get { return (TTo)(object)BaseEnumerator.Current; } }
}
public static class ListExtensions
{
public static IList<TTo> CastList<TFrom, TTo>(this IList<TFrom> list)
{
return new CastedList<TTo, TFrom>(list);
}
}
You need to edit your my.cnf
file and make sure you have the port set as in the following line:
port = 3360
Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port
is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use
echo
,console.log()
, or its equivalent to show the entire command so you can see it.Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE
, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE
at that point.
Messages that say ...near '' at line...
simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query;
or var_dump($query)
to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE
command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [
and ]
are optional; vertical bars |
indicate alternatives; and ellipses ...
denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE
keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference
must be followed by the SET
keyword: whereas in our command it was actually followed by the WHERE
keyword. This explains why the parser reports that a problem was encountered at that point.
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE
at this point and so will raise a similar syntax error—but you hadn't intended for that where
to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]The identifier quote character is the backtick (“
`
”):mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the
ANSI_QUOTES
SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:mysql> CREATE TABLE "test" (col INT); ERROR 1064: You have an error in your SQL syntax... mysql> SET sql_mode='ANSI_QUOTES'; mysql> CREATE TABLE "test" (col INT); Query OK, 0 rows affected (0.00 sec)
The answer is on the MSDN site:
The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.
The following actions might require a table to be re-created:
- Adding a new column to the middle of the table
- Dropping a column
- Changing column nullability
- Changing the order of the columns
- Changing the data type of a column
EDIT 1:
Additional useful informations from here:
To change the Prevent saving changes that require the table re-creation option, follow these steps:
- Open SQL Server Management Studio (SSMS).
- On the Tools menu, click Options.
- In the navigation pane of the Options window, click Designers.
- Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.
Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.
Risk of turning off the "Prevent saving changes that require table re-creation" option
Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.
If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ?
where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.
E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.
Sub UpdateQuery
Dim cn As WorkbookConnection
Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
For Each cn In ThisWorkbook.Connections
If cn.Type = xlConnectionTypeODBC Then
Set odbcCn = cn.ODBCConnection
' If you do have multiple connections you would want to modify
' the line below each time you run through the loop.
odbcCn.CommandText = "select blah from someTable where blah like ?"
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = "select blah from someTable where blah like ?"
End If
Next
End Sub
To find all tables with a particular column:
select owner, table_name from all_tab_columns where column_name = 'ID';
To find tables that have any or all of the 4 columns:
select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');
To find tables that have all 4 columns (with none missing):
select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;
If this is for a non-Rails project, I'd use String#index
:
"foobar".index("foo") == 0 # => true
I have managed to solve the problem by following the Chris Slade's answer, but to restart the server, I had to use the following commands:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
that I found here (pjammer's answer down at the bottom)
There are many ways you can do this. You can just use what is described here or you can do myDate.ToString("dd-MMM-yyyy");
There are plenty of help for this topic in the MSDN documentation.
You could also write you own DateExtension class which will allow you to go something like myDate.ToMyDateFormat();
public static class DateTimeExtensions
{
public static DateTime ToMyDateFormat(this DateTime d)
{
return d.ToString("dd-MMM-yyyy");
}
}
Have you heard about the jQuery Waypoint plugin.
Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :
$(document).ready(function() {
var $loading = $("<div class='loading'><p>Loading more items…</p></div>"),
$footer = $('footer'),
opts = {
offset: '100%'
};
$footer.waypoint(function(event, direction) {
$footer.waypoint('remove');
$('body').append($loading);
$.get($('.more a').attr('href'), function(data) {
var $data = $(data);
$('#container').append($data.find('.article'));
$loading.detach();
$('.more').replaceWith($data.find('.more'));
$footer.waypoint(opts);
});
}, opts);
});
Before proceeding:
Install a proper mergetool. On Linux, I strongly suggest you to use meld:
sudo apt-get install meld
Configure your mergetool:
git config --global merge.tool meld
Then, iterate in the following way:
git cherry-pick ....
git mergetool
git cherry-pick --continue
Most of the time this happens due to the invalid response type from server.
Make sure the following 2 to avoid this issue..
The function eat
of my package safejoin has such feature, if you give
it a list of data.frames as a second input it will join them
recursively to the first input.
Borrowing and extending the accepted answer's data :
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
z2 <- data_frame(i = c("a","b","c"), l = rep(100L,3),l2 = rep(100L,3)) # for later
# devtools::install_github("moodymudskipper/safejoin")
library(safejoin)
eat(x, list(y,z), .by = "i")
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
We don't have to take all columns, we can use select helpers from tidyselect and
choose (as we start from .x
all .x
columns are kept):
eat(x, list(y,z), starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j l
# <chr> <int> <int>
# 1 a 1 9
# 2 b 2 NA
# 3 c 3 7
or remove specific ones:
eat(x, list(y,z), -starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
# i j k
# <chr> <int> <int>
# 1 a 1 NA
# 2 b 2 4
# 3 c 3 5
If the list is named the names will be used as prefixes :
eat(x, dplyr::lst(y,z), .by = "i")
# # A tibble: 3 x 4
# i j y_k z_l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
If there are column conflicts the .conflict
argument allows you to resolve it,
for example by taking the first/second one, adding them, coalescing them,
or nesting them.
keep first :
eat(x, list(y, z, z2), .by = "i", .conflict = ~.x)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
keep last:
eat(x, list(y, z, z2), .by = "i", .conflict = ~.y)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 100
# 2 b 2 4 100
# 3 c 3 5 100
add:
eat(x, list(y, z, z2), .by = "i", .conflict = `+`)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 109
# 2 b 2 4 NA
# 3 c 3 5 107
coalesce:
eat(x, list(y, z, z2), .by = "i", .conflict = dplyr::coalesce)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <dbl>
# 1 a 1 NA 9
# 2 b 2 4 100
# 3 c 3 5 7
nest:
eat(x, list(y, z, z2), .by = "i", .conflict = ~tibble(first=.x, second=.y))
# # A tibble: 3 x 4
# i j k l$first $second
# <chr> <int> <int> <int> <int>
# 1 a 1 NA 9 100
# 2 b 2 4 NA 100
# 3 c 3 5 7 100
NA
values can be replaced by using the .fill
argument.
eat(x, list(y, z), .by = "i", .fill = 0)
# # A tibble: 3 x 4
# i j k l
# <chr> <int> <dbl> <dbl>
# 1 a 1 0 9
# 2 b 2 4 0
# 3 c 3 5 7
By default it's an enhanced left_join
but all dplyr joins are supported through
the .mode
argument, fuzzy joins are also supported through the match_fun
argument (it's wrapped around the package fuzzyjoin
) or
giving a formula such as ~ X("var1") > Y("var2") & X("var3") < Y("var4")
to the
by
argument.
screen.orientation.lock('landscape');
Will force it to change to and stay in landscape mode. Tested on Nexus 5.
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
If you want to allow 1
and 1.2
:
(?<=^| )\d+(\.\d+)?(?=$| )
If you want to allow 1
, 1.2
and .1
:
(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )
If you want to only allow 1.2
(only floats):
(?<=^| )\d+\.\d+(?=$| )
\d
allows digits (while \D
allows anything but digits).
(?<=^| )
checks that the number is preceded by either a space or the beginning of the string. (?=$| )
makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.
Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.
Solution in python can be as below:
class Word:
def __init__(self, data, index):
self.data = data
self.index = index
def printAnagrams(arr):
dupArray = []
size = len(arr)
for i in range(size):
dupArray.append(Word(arr[i], i))
for i in range(size):
dupArray[i].data = ''.join(sorted(dupArray[i].data))
dupArray = sorted(dupArray, key=lambda x: x.data)
for i in range(size):
print arr[dupArray[i].index]
def main():
arr = ["dog", "act", "cat", "god", "tac"]
printAnagrams(arr)
if __name__== '__main__':
main()
The time complexity of above is O(NMLogN + NMLogM) = O(NMlogN)
What worked for me
import databricks.koalas as ks
df1k = df1.to_koalas()
df2k = df2.to_koalas()
df3k = df1k.merge(df2k, on=['col1', 'col2'])
df3 = df3k.to_spark()
All of the columns except for col1 and col2 had "_x" appended to their names if they had come from df1 and "_y" appended if they had come from df2, which is exactly what I needed.
Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.
WARNING this is a destructive action. If you use this ensure you back up your database first
you can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :
$ php artisan migrate:refresh
Well, I ran into a similar problem where I added somthing to the data source and it's not reloading.
The easiest way I found whas simply to reassigning the data
let dataSource = ['a','b','c']
dataSource.push('d')
let cloned = dataSource.slice()
// OR IN ES6 // let cloned = [...dataSource]
dataSource = cloned
You can also check contents of *.tag.gz file using pigz
(parallel gzip) to speedup the archive check:
pigz -cvdp number_of_threads /[...]path[...]/archive_name.tar.gz | tar -tv > /dev/null
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
I know it's been a while since this thread was open. From the answer given by chmike and improved by Aqib Mumtaz. They give a good answer but only works for a infinite line as said Aqib. So I add some comparisons to know if the line segment touch the circle, I write it in Python.
def LineIntersectCircle(c, r, p1, p2):
#p1 is the first line point
#p2 is the second line point
#c is the circle's center
#r is the circle's radius
p3 = [p1[0]-c[0], p1[1]-c[1]]
p4 = [p2[0]-c[0], p2[1]-c[1]]
m = (p4[1] - p3[1]) / (p4[0] - p3[0])
b = p3[1] - m * p3[0]
underRadical = math.pow(r,2)*math.pow(m,2) + math.pow(r,2) - math.pow(b,2)
if (underRadical < 0):
print("NOT")
else:
t1 = (-2*m*b+2*math.sqrt(underRadical)) / (2 * math.pow(m,2) + 2)
t2 = (-2*m*b-2*math.sqrt(underRadical)) / (2 * math.pow(m,2) + 2)
i1 = [t1+c[0], m * t1 + b + c[1]]
i2 = [t2+c[0], m * t2 + b + c[1]]
if p1[0] > p2[0]: #Si el punto 1 es mayor al 2 en X
if (i1[0] < p1[0]) and (i1[0] > p2[0]): #Si el punto iX esta entre 2 y 1 en X
if p1[1] > p2[1]: #Si el punto 1 es mayor al 2 en Y
if (i1[1] < p1[1]) and (i1[1] > p2[1]): #Si el punto iy esta entre 2 y 1
print("Intersection")
if p1[1] < p2[1]: #Si el punto 2 es mayo al 2 en Y
if (i1[1] > p1[1]) and (i1[1] < p2[1]): #Si el punto iy esta entre 1 y 2
print("Intersection")
if p1[0] < p2[0]: #Si el punto 2 es mayor al 1 en X
if (i1[0] > p1[0]) and (i1[0] < p2[0]): #Si el punto iX esta entre 1 y 2 en X
if p1[1] > p2[1]: #Si el punto 1 es mayor al 2 en Y
if (i1[1] < p1[1]) and (i1[1] > p2[1]): #Si el punto iy esta entre 2 y 1
print("Intersection")
if p1[1] < p2[1]: #Si el punto 2 es mayo al 2 en Y
if (i1[1] > p1[1]) and (i1[1] < p2[1]): #Si el punto iy esta entre 1 y 2
print("Intersection")
if p1[0] > p2[0]: #Si el punto 1 es mayor al 2 en X
if (i2[0] < p1[0]) and (i2[0] > p2[0]): #Si el punto iX esta entre 2 y 1 en X
if p1[1] > p2[1]: #Si el punto 1 es mayor al 2 en Y
if (i2[1] < p1[1]) and (i2[1] > p2[1]): #Si el punto iy esta entre 2 y 1
print("Intersection")
if p1[1] < p2[1]: #Si el punto 2 es mayo al 2 en Y
if (i2[1] > p1[1]) and (i2[1] < p2[1]): #Si el punto iy esta entre 1 y 2
print("Intersection")
if p1[0] < p2[0]: #Si el punto 2 es mayor al 1 en X
if (i2[0] > p1[0]) and (i2[0] < p2[0]): #Si el punto iX esta entre 1 y 2 en X
if p1[1] > p2[1]: #Si el punto 1 es mayor al 2 en Y
if (i2[1] < p1[1]) and (i2[1] > p2[1]): #Si el punto iy esta entre 2 y 1
print("Intersection")
if p1[1] < p2[1]: #Si el punto 2 es mayo al 2 en Y
if (i2[1] > p1[1]) and (i2[1] < p2[1]): #Si el punto iy esta entre 1 y 2
print("Intersection")
Node's answer is really great, but it left open the question how can get stdout and stderr redirected. I found a solution on Unix & Linux, but it is also not complete. I would like to merge these two solutions. Here it is:
For my test I made a small bash script called loop.sh, which prints the pid of itself with a minute sleep in an infinite loop.
$./loop.sh
Now get the PID of this process somehow. Usually ps -C loop.sh
is good enough, but it is printed in my case.
Now we can switch to another terminal (or press ^Z and in the same terminal). Now gdb
should be attached to this process.
$ gdb -p <PID>
This stops the script (if running). Its state can be checked by ps -f <PID>
, where the STAT
field is 'T+' (or in case of ^Z 'T'), which means (man ps(1))
T Stopped, either by a job control signal or because it is being traced
+ is in the foreground process group
(gdb) call close(1)
$1 = 0
Close(1) returns zero on success.
(gdb) call open("loop.out", 01102, 0600)
$6 = 1
Open(1) returns the new file descriptor if successful.
This open is equal with open(path, O_TRUNC|O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)
.
Instead of O_RDWR
O_WRONLY
could be applied, but /usr/sbin/lsof
says 'u' for all std* file handlers (FD
column), which is O_RDWR
.
I checked the values in /usr/include/bits/fcntl.h header file.
The output file could be opened with O_APPEND
, as nohup
would do, but this is not suggested by man open(2)
, because of possible NFS problems.
If we get -1 as a return value, then call perror("")
prints the error message. If we need the errno, use p errno
gdb comand.
Now we can check the newly redirected file. /usr/sbin/lsof -p <PID>
prints:
loop.sh <PID> truey 1u REG 0,26 0 15008411 /home/truey/loop.out
If we want, we can redirect stderr to another file, if we want to using call close(2)
and call open(...)
again using a different file name.
Now the attached bash
has to be released and we can quit gdb
:
(gdb) detach
Detaching from program: /bin/bash, process <PID>
(gdb) q
If the script was stopped by gdb
from an other terminal it continues to run. We can switch back to loop.sh's terminal. Now it does not write anything to the screen, but running and writing into the file. We have to put it into the background. So press ^Z
.
^Z
[1]+ Stopped ./loop.sh
(Now we are in the same state as if ^Z
was pressed at the beginning.)
Now we can check the state of the job:
$ ps -f 24522
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID><PPID> 0 11:16 pts/36 S 0:00 /bin/bash ./loop.sh
$ jobs
[1]+ Stopped ./loop.sh
So process should be running in the background and detached from the terminal. The number in the jobs
command's output in square brackets identifies the job inside bash
. We can use in the following built in bash
commands applying a '%' sign before the job number :
$ bg %1
[1]+ ./loop.sh &
$ disown -h %1
$ ps -f <PID>
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID><PPID> 0 11:16 pts/36 S 0:00 /bin/bash ./loop.sh
And now we can quit from the calling bash. The process continues running in the background. If we quit its PPID become 1 (init(1) process) and the control terminal become unknown.
$ ps -f <PID>
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID> 1 0 11:16 ? S 0:00 /bin/bash ./loop.sh
$ /usr/bin/lsof -p <PID>
...
loop.sh <PID> truey 0u CHR 136,36 38 /dev/pts/36 (deleted)
loop.sh <PID> truey 1u REG 0,26 1127 15008411 /home/truey/loop.out
loop.sh <PID> truey 2u CHR 136,36 38 /dev/pts/36 (deleted)
COMMENT
The gdb stuff can be automatized creating a file (e.g. loop.gdb) containing the commands and run gdb -q -x loop.gdb -p <PID>
. My loop.gdb looks like this:
call close(1)
call open("loop.out", 01102, 0600)
# call close(2)
# call open("loop.err", 01102, 0600)
detach
quit
Or one can use the following one liner instead:
gdb -q -ex 'call close(1)' -ex 'call open("loop.out", 01102, 0600)' -ex detach -ex quit -p <PID>
I hope this is a fairly complete description of the solution.
Basically, since Python 3.x you need to use print
with parenthesis.
Python 2.x: print "Lord of the Rings"
Python 3.x: print("Lord of the Rings")
print
was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.
>>> items = ['foo', 'bar', 'baz'] >>> print(*items, sep='+') foo+bar+baz
In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.
When building on the build/CI server, turn off the import of Microsoft.WebApplication.targets
altogether by specifying /p:VSToolsPath=''
. This will, essentially, make the condition of the following line false:
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
This is how it's done in TeamCity:
Try
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).
Finally, the constructor we are passing these iterators into is a string constructor of the form:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
Newtonsoft.JSON
is a good solution for these kind of situations. Also Newtonsof.JSON
is faster than others, such as JavaScriptSerializer
, DataContractJsonSerializer
.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray
, and you can use a for
loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
If you are using react-redux for your application and if you want to show data which is in the redux store, you can set "checked" option as below.
<label>Male</label>
<input
type="radio"
name="gender"
defaultChecked={this.props.gender == "0"}
/>
<label>Female</label>
<input
type="radio"
name="gender"
defaultChecked={this.props.gender == "1"}
/>
You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment
in order to find the action.
Global variables are fine in small programs, but horrible if used the same way in large ones.
This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.
When you are more experienced it will be easier to learn when they are okay.
Try
pip3 install pandas
from terminal. Maybe your original pip install pandas is referencing anaconda distribution
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");
No need of row number functions if field ID is unique.
SELECT TOP 1 *
FROM (
SELECT TOP 2 *
FROM yourTable
ORDER BY ID
) z
ORDER BY ID DESC
You can use 'onclick' attribute like this :
<a ... href="javascript: onclick();" ...>...</a>
Ignore the files ending with .iws
, and the workspace.xml
and tasks.xml
files in your .gitignore
Reference
The correct way to use max in the having clause is by performing a self join first:
select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)
The following is how you would join with a subquery:
select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
from table1 t1_max
where t1.id = t1_max.id)
Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
join #dataset d_max
on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c
Sub query version:
select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
on t1.id = t2.id
join table2 t3
on t1.id = t3.id
select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
from #dataset d_max
where d.id = d_max.id)
Probably somewhere you have DBconnection->close();
and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close();
in __destruct()
(because __destruct
is event, after which there will be a need for execution of queries)
A POST is considered something of a factory type method. You include data with it to create what you want and whatever is on the other end knows what to do with it. A PUT is used to update existing data at a given URL, or to create something new when you know what the URI is going to be and it doesn't already exist (as opposed to a POST which will create something and return a URL to it if necessary).
The above solutions were not working for me. I solved it by creating a View with the same background colour as the parent and added negative margin to move the image upwards.
<ScrollView style={{ backgroundColor: 'blue' }}>
<View
style={{
width: '95%',
paddingLeft: '5%',
marginTop: 80,
height: 800,
}}>
<View style={{ backgroundColor: 'white' }}>
<Thumbnail square large source={{uri: uri}} style={{ marginTop: -30 }}/>
<Text>Some Text</Text>
</View>
</View>
</ScrollView>
and I got the following result.
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
OK, for me that is the way it worked (I am using Python 2.7):
a = __import__('file_to_import', globals(), locals(), ['*'], -1)
b = a.MyClass()
Then, b is an instance of class 'MyClass'
If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :
Step 1:
ng build --prod --env=prod
Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.
Step 3. Creates .htaccess
file in root folder and paste this in the .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Run the following commands:
$ git checkout mobiledevice
$ git pull origin master
This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.
I don't know if this is the best practice but works for me.
Not sure why this thread got necroed; but here is a 2014 approved answer, which should be far faster:
import numpy as np
data = np.random.rand(100)
bins = 10
slices = np.linspace(0, 100, bins+1, True).astype(np.int)
counts = np.diff(slices)
mean = np.add.reduceat(data, slices[:-1]) / counts
print mean
You can use the Environment class's static NewLine property to get the proper newline:
$errorMsg = "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
jQuery now has the .one()
function that limits any given event (such as "submit") to one occurrence.
Example:
$('#myForm').one('submit', function() {
$(this).find('input[type="submit"]').attr('disabled','disabled');
});
This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.
Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.
Note 2: Per gorelog, using attr('disabled','disabled')
will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;')
instead.
Isn't the 'date' command much simpler? No need for awk, stat, etc.
date -r <filename>
Also, consider looking at the man page for date formatting; for example with common date and time format:
date -r <filename> "+%m-%d-%Y %H:%M:%S"
Any easy way to cover ALL file inputs is to just style your input[type=button] and drop this in globally to turn file inputs into buttons:
$(document).ready(function() {
$("input[type=file]").each(function () {
var thisInput$ = $(this);
var newElement = $("<input type='button' value='Choose File' />");
newElement.click(function() {
thisInput$.click();
});
thisInput$.after(newElement);
thisInput$.hide();
});
});
Here's some sample button CSS that I got from http://cssdeck.com/labs/beautiful-flat-buttons:
input[type=button] {
position: relative;
vertical-align: top;
width: 100%;
height: 60px;
padding: 0;
font-size: 22px;
color:white;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
background: #454545;
border: 0;
border-bottom: 2px solid #2f2e2e;
cursor: pointer;
-webkit-box-shadow: inset 0 -2px #2f2e2e;
box-shadow: inset 0 -2px #2f2e2e;
}
input[type=button]:active {
top: 1px;
outline: none;
-webkit-box-shadow: none;
box-shadow: none;
}
This issue occurs when someone has commited the code to develop/master and latest code has not been rebased from develop/master and you're trying to overwrite new changes to develop/master branch
Solution:
In VS 2017 it is automatic. So just Add Reference
as usually.
Note that in Reference Properties
absolute path is shown, but in .vbproj/.csproj
relative is used.
<Reference Include="NETnetworkmanager">
<HintPath>..\..\libs\NETnetworkmanager.dll</HintPath>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
The only time I've wanted to do this is for code golf, and then I've just copied my code out of the file and pasted it into an echo -n 'content'>file
statement.
I have found answers to my confusions.
There is a very important difference between the root
and the alias
directives. This difference exists in the way the path specified in the root
or the alias
is processed.
In case of the root
directive, full path is appended to the root including the location part, whereas in case of the alias
directive, only the portion of the path NOT including the location part is appended to the alias.
To illustrate:
Let's say we have the config
location /static/ {
root /var/www/app/static/;
autoindex off;
}
In this case the final path that Nginx will derive will be
/var/www/app/static/static
This is going to return 404
since there is no static/
within static/
This is because the location part is appended to the path specified in the root
. Hence, with root
, the correct way is
location /static/ {
root /var/www/app/;
autoindex off;
}
On the other hand, with alias
, the location part gets dropped. So for the config
location /static/ {
alias /var/www/app/static/;
autoindex off; ?
} |
pay attention to this trailing slash
the final path will correctly be formed as
/var/www/app/static
alias
directiveThere is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.
A few more places have discussed this, not conclusively though.
https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working
You can simply create a contained user in SQL DB V12.
Create user containeduser with password = 'Password'
Contained user login is more efficient than login to the database using the login created by master. You can find more details @ http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/
public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
JSONObject json = new JSONObject();
// get the keys of json object
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(obj.getJSONObject(key), keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(jArray.getJSONObject(i), keyString, newValue);
}
}
}
return obj;
}
// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t":
s.replaceAll("\n","");
s.replaceAll("\t","");
edited:
I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)
In your styles.xml, modify style "AppTheme" like
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
I did not see anyone using this method:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean focused) {
InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (focused)
keyboard.showSoftInput(editText, 0);
else
keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
And then just request focus to the editText:
editText.requestFocus();
// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width
public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (OnlyResizeIfWider)
{
if (FullsizeImage.Width <= NewWidth)
{
NewWidth = FullsizeImage.Width;
}
}
int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
if (NewHeight > MaxHeight)
{
// Resize with height instead
NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
NewHeight = MaxHeight;
}
System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose();
// Save resized picture
NewImage.Save(NewFile);
}
location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL
var hash = document.URL.substr(document.URL.indexOf('#')+1)
You can use text classes:
.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white
use text classes in any tag where needed.
<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>
You can add your own classes or modify above classes as your requirement.
The checked answer does work but officially in MongooseJS latest, you should use pull.
doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull
I was just looking that up too.
See Daniel's answer for the correct answer. Much better.
The situation is essentially that VS
is not set up to go through a proxy to get to the resources it's trying to get to (when using FTP). This is the cause of the 407 error you're getting. I did some research on this and there are a few things that you can try to get this debugged. Fundamentally this is a bit of a flawed area in the product that is supposed to be reviewed in a later release.
Here are some solutions, in order of less complex to more complex:
VS
.devenv.exe.config
add <servicePointManager expect100Continue="false" />
as laid out below:<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
</configuration>
defaultProxy
settings as follows:<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy proxyaddress="http://your.proxyserver.ip:port"/>
</defaultProxy>
<settings>
...
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" />
</defaultProxy>
Hope this solves it for you.
Example with glob() function. It will delete all files and folders recursively, including files that starts with dot.
delete_all( 'folder' );
function delete_all( $item ) {
if ( is_dir( $item ) ) {
array_map( 'delete_all', array_diff( glob( "$item/{,.}*", GLOB_BRACE ), array( "$item/.", "$item/.." ) ) );
rmdir( $item );
} else {
unlink( $item );
}
};
Try calling setWillNotDraw(false)
from surfaceCreated
:
public void surfaceCreated(SurfaceHolder holder) {
try {
setWillNotDraw(false);
mycam.setPreviewDisplay(holder);
mycam.startPreview();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG,"Surface not created");
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(area, rectanglePaint);
Log.w(this.getClass().getName(), "On Draw Called");
}
and calling invalidate
from onTouchEvent
:
public boolean onTouch(View v, MotionEvent event) {
invalidate();
return true;
}
If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:
#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN
The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.
Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....
You can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log; // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Better way is to autowire with a constructor:
private final HttpServletRequest httpServletRequest;
public ClassConstructor(HttpServletRequest httpServletRequest){
this.httpServletRequest = httpServletRequest;
}
another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns
print(df.iloc[:,dct['D']])
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter. So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
less will look in its environment to see if there is a variable named LESS
You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less
from the comand line, it will find the LESS.
Try adding this
export LESS="-CQaix4"
This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less
, just tap the 'h' key and nose around, or run less --help
.
Edit:
I looked at the help, and noticed there is also an -r
option
-r -R .... --raw-control-chars --RAW-CONTROL-CHARS
Output "raw" control characters.
I agree that cat
may be the most exact match to your stated needs.
cat -vet file | less
Will add '$' at end of each line and convert tab char to visual '^I'.
cat --help
(edited)
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
I hope this helps.
use app.render
in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.
The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.
I might have
/WEB-INF/jsp/pages/Home.jsp
and a method on a class
@RequestMapping(value="/pages/Home.html")
private ModelMap buildHome() {
return somestuff;
}
The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.
How it accomplishes this varies widely with configuration and Spring version.
There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.
Little addition in answer if you have different user rather then dbo
then do like this.
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'
Had the same problem a few minutes ago, I was missing the 'Maven depencendies' library in my Deployment Assembly. I added it through the section 'Web Deployment Assembly' in Eclipse
Found the solution:
It should be:
"{'Id1':'2','Id2':'2'}"
and not
"{'Id1':'2'},{'Id2':'2'}"
No, it's not possible.
It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".
The fleqn
option in the document class will apply left aligning setting in all equations of the document. You can instead use \begin{flalign}
. This will align only the desired equations.
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered
class name to elements I want to center:
.contentCentered {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.contentCentered::before {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
height: 100%; _x000D_
vertical-align: middle;_x000D_
margin-right: -.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
.contentCentered > * {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div class="contentCentered">_x000D_
<div>_x000D_
<h1>Some text</h1>_x000D_
<p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
shoulder, said—"Did ye see anything looking like men going_x000D_
towards that ship a while ago?"</p>_x000D_
</div>_x000D_
</div>
_x000D_
Forked CodePen: http://codepen.io/dougli/pen/Eeysg
Have you tried using 'onkeydown'? This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another
You are right:
conda update --all
is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).
But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.
e.g. X requires Y <5.0, so Y will never be >= 5.0
That's why you 'cannot' upgrade them all.
To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.
A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge
as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.
Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:
X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0
So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.
(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)
So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!
1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv
and then conda activate myenv
). Executing conda update --all
inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.
To download the wsdl from a url using Developer Command Prompt for Visual Studio, run it in Administrator mode and enter the following command:
svcutil /t:metadata http://[your-service-url-here]
You can now consume the downloaded wsdl in your project as you see fit.
A couple ways this can be done:
This will make it a square
ul
{
list-style-type: square;
}
This will make it green
li
{
color: #0F0;
}
This will prevent the text from being green
li p
{
color: #000;
}
However that will require that all text within lists be in paragraphs so that the color is not overridden.
A better way is to make an image of a green square and use:
ul
{
list-style: url(green-square.png);
}
A lot of vim's features (like autoindent
and cindent
) are turned off by default. To really see what vim can do for you, you need a decent ~/.vimrc
.
A good starter one is in $VIMRUNTIME/vimrc_example.vim
. If you want to try it out, use
:source $VIMRUNTIME/vimrc_example.vim
when in vim.
I'd actually suggest just copying the contents to your ~/.vimrc
as it's well commented, and a good place to start learning how to use vim. You can do this by
:e $VIMRUNTIME/vimrc_example.vim
:w! ~/.vimrc
This will overwrite your current ~/.vimrc
, but if all you have in there is the indent settings Davr suggested, I wouldn't sweat it, as the example vimrc will take care of that for you as well. For a complete walkthrough of the example, and what it does for you, see :help vimrc-intro
.
In my case the problem was that a method was defined in some Interface A
as default
, while its sub-class overrode it as private. Then when the method was called, the java Runtime realized it was calling a private method.
I am still puzzled as to why the compiler didn't complain about the private override..
public interface A {
default void doStuff() {
// doing stuff
}
}
public class B {
private void doStuff() {
// do other stuff instead
}
}
public static final main(String... args) {
A someB = new B();
someB.doStuff();
}
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
app.post('/login', function(req, res) {
});
or
app.get('/login', function(req, res) {
});
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
For my application, i have done this way
<ListView
android:id="@+id/staff_jobassigned_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:dividerHeight="10dp">
</ListView>
just set the divider to null
and providing height to the divider did for me.
Example :
android:divider="@null"
or
android:divider="@android:color/transparent"
and this is result
I am using in the way and it is working for me.
public static void main(String[] args) {
new CarpoolDBAppTest();
}
public CarpoolDBAppTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Student stud = (Student) context.getBean("yourBeanId");
}
Here Student is my classm you will get the class matching yourBeanId.
Now work on that object with whatever operation you want to do.
Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.
The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.
Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).
The primary benefits of Python Eggs are:
They enable tools like the "Easy Install" Python package manager
.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)
They can include package metadata, such as the other eggs they depend on
They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)
They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.
They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).
There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
Did you took a look at this? http://developer.yahoo.com/yui/history/
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
This code is working for me
Dim N As Long, r As Range
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
Set r = Cells(i, "B")
r.Value = CDate(r.Value)
Next i
Try it changing the columns to suit your sheet
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.
Its simple just close the specified text like this for example <b>"your text here:"</b>
<string name="headquarters">"<b>"Headquarters:"</b>" Mooresville, North Carolina, U.S.</string>
result: Headquarters: Mooresville, North Carolina, U.S.
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
I have read all answers and I want to summarize for better understanding at first glance like following:
Firstly, the whole command that gets executed in the container includes two parts: the command and the arguments
ENTRYPOINT defines the executable invoked when the container is started (for command)
CMD specifies the arguments that get passed to the ENTRYPOINT (for arguments)
In the Kubernetes In Action book points an important note about it. (chapter 7)
Although you can use the CMD instruction to specify the command you want to execute when the image is run, the correct way is to do it through the ENTRYPOINT instruction and to only specify the CMD if you want to define the default arguments.
You can also read this article for great explanation in a simple way
You can create a single function that calls both of those, and then use it in the event.
function myFunction(){
pay();
cls();
}
And then, for the button:
<input id="btn" type="button" value="click" onclick="myFunction();"/>
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
this creates an image just placing the 1st with transparency on top of the 2nd
composite -gravity center ImgWithTransp.png BackgroundSameSizeOfImg.png ResultImg.png
originally found the tip on this post
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
scipy.stats.rv_discrete
might be what you want. You can supply your probabilities via the values
parameter. You can then use the rvs()
method of the distribution object to generate random numbers.
As pointed out by Eugene Pakhomov in the comments, you can also pass a p
keyword parameter to numpy.random.choice()
, e.g.
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
If you are using Python 3.6 or above, you can use random.choices()
from the standard library – see the answer by Mark Dickinson.
I usually put all my files like that into an "assets" folder in the application root, and then I make sure to use an Asset_Helper to point to those files for me. This is what CodeIgniter suggests.
In my case all of them did not work and finally it was
msiexec /i "msinamebla.msi" INSTALLFOLDER="C:\test\" /qb
I checked the log.txt as described by ezzadeen and found "INSTALLFOLDER" in there.
From https://github.com/Homebrew/brew/issues/4436#issuecomment-403194892
Issue solved by setting this env variable:
export HOMEBREW_FORCE_BREWED_CURL=1
Here an improved answer of ShravankumarKumar. I created special classes for the pages so you can access words in the pdf based on the text rows and the word in that row.
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
//create a list of pdf pages
var pages = new List<PdfPage>();
//load the pdf into the reader. NOTE: path can also be replaced with a byte array
using (PdfReader reader = new PdfReader(path))
{
//loop all the pages and extract the text
for (int i = 1; i <= reader.NumberOfPages; i++)
{
pages.Add(new PdfPage()
{
content = PdfTextExtractor.GetTextFromPage(reader, i)
});
}
}
//use linq to create the rows and words by splitting on newline and space
pages.ForEach(x => x.rows = x.content.Split('\n').Select(y =>
new PdfRow() {
content = y,
words = y.Split(' ').ToList()
}
).ToList());
The custom classes
class PdfPage
{
public string content { get; set; }
public List<PdfRow> rows { get; set; }
}
class PdfRow
{
public string content { get; set; }
public List<string> words { get; set; }
}
Now you can get a word by row and word index.
string myWord = pages[0].rows[12].words[4];
Or use Linq to find the rows containing a specific word.
//find the rows in a specific page containing a word
var myRows = pages[0].rows.Where(x => x.words.Any(y => y == "myWord1")).ToList();
//find the rows in all pages containing a word
var myRows = pages.SelectMany(r => r.rows).Where(x => x.words.Any(y => y == "myWord2")).ToList();
Unfortunately, you can't hide option
elements in all browsers.
In the past when I have needed to do this, I have set their disabled
attribute, like so...
$('option').prop('disabled', true);
I've then used the hiding where it is supported in browsers using this piece of CSS...
select option[disabled] {
display: none;
}
You should be strongly typing your views. Then you can do this:
public class YourViewModel {
public bool ConditionaValue { get; set; }
}
In your view, you can create a checkbox that will bind to this boolean value:
@Html.CheckBoxFor(x => x.ConditionalValue)
If it is checked, the model property will be true.
For your immediate problem though.. you need to name your checkbox to be the same name as your action method parameters.. and they should be bool
..
You don't need any date-specific functions for this, it's just string manipulation:
var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
#many .more.selectors h4 + p { ... }
This is called the adjacent sibling selector.
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
IE 8 doesn't have indexOf function, so I used jQuery inArray instead.
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [$.inArray(string, array) == -1];
}
});
I had the same issue on Galaxy S4 (i9505) on stock ROM (4.2.2 ME2). I had free space like this: 473 MB on /data
, 344 MB on /system
, 2 GB on /cache
. I was getting the free spate error on any download from Play Store (small app, 2.5 MB), I checked LogCat, it said "Cancel download of ABC because insufficient free space".
Then I freed up some space on /data
, 600 MB free, and now it's working fine, apps download and install ;). So it seems like this ROM needs a little more free space to work OK...
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
If the user should select only one option at once, just remove the "multiple" - make a normal select:
<select name="mySelect" size="3">
<option>Foo</option>
<option>Bar</option>
<option>Foo Bar</option>
<option>Bar Foo</option>
</select>
I know this is an old question, but the following should work if you don't need the month name at the DB level:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month;
You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.
N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;
You can try this:
((BigDecimal) volume).intValue();
I use java.math.BigDecimal
convert to int
(primitive type).
It is worked for me.
Type :h recording to learn more.
*q* *recording* q{0-9a-zA-Z"} Record typed characters into register {0-9a-zA-Z"} (uppercase to append). The 'q' command is disabled while executing a register, and it doesn't work inside a mapping. {Vi: no recording} q Stops recording. (Implementation note: The 'q' that stops recording is not stored in the register, unless it was the result of a mapping) {Vi: no recording} *@* @{0-9a-z".=*} Execute the contents of register {0-9a-z".=*} [count] times. Note that register '%' (name of the current file) and '#' (name of the alternate file) cannot be used. For "@=" you are prompted to enter an expression. The result of the expression is then executed. See also |@:|. {Vi: only named registers}
To get your program to run, please put jsp files under web-content and not under WEB-INF
because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:
http://localhost:8080/YourProject/yourfile.jsp
then your problem will be solved.