The following is the correct overload (in your example you are missing a closing }
to the routeValues
anonymous object so your code will throw an exception):
<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
<span>People</span>
</a>
Assuming you are using the default routes this should generate the following markup:
<a href="/Listing/GetByList?name=John&contact=calgary%2C%20vancouver">
<span>People</span>
</a>
which will successfully invoke the GetByList
controller action passing the two parameters:
public ActionResult GetByList(string name, string contact)
{
...
}
let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];
let sortFn = (n1 , n2) => number { return n1 - n2; }
const sortedArray: number[] = numericArray.sort(sortFn);
Sort by some field:
let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];
let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }
const sortedArray2:{key:number}[] = arr.sort(sortFn2);
Try setting the disabled
attribute directly:
if ( someCondition == true ) {
document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
document.getElementById('btn1').removeAttribute('disabled');
}
You do not need to add permissions like what is the case with the solutions provided so far. Download this website as a string:
or
Downloading a website as a string can be done with java code:
http://www.itcuties.com/java/read-url-to-string/
Parse the JSON object like this:
https://stackoverflow.com/a/18998203/1987258
The json attribute "query" or "ip" contains the IP address.
Very simple just do this:
<button ng-click="hideShow=(hideShow ? false : true)">Toggle</button>
<div ng-if="hideShow">hide and show content ...</div>
You have to also add the "navbar-brand" class to your image a
container, also you have to include it inside the .navbar-inner
container, like so:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="navbar-brand" href="index.html"> <img src="images/57x57x300.jpg"></a>
</div>
</div>
</div>
Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.
Don't forget to check the Troubleshooting section.
Assuming you can use integrated security, you can remove the user id and pass:
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
just use '!' before the pip command in spyder terminal and it will be fine
Eg:
!pip install imutils
Or (more efficiently):
var arr = new Array(3); arr[0] = "Zero"; arr[1] = "One"; arr[2] = "Two"; document.write(arr); // same as document.write(arr.toString()) in this context
The toString method of an array when called returns exactly what you need - comma-separated list.
The direct parent of your child is markerDiv, so you should call remove from markerDiv as so:
markerDiv.removeChild(myCoolDiv);
Alternatively, you may want to remove markerNode. Since that node was appended directly to videoContainer, it can be removed with:
document.getElementById("playerContainer").removeChild(markerDiv);
Now, the easiest general way to remove a node, if you are absolutely confident that you did insert it into the DOM, is this:
markerDiv.parentNode.removeChild(markerDiv);
This works for any node (just replace markerDiv with a different node), and finds the parent of the node directly in order to call remove from it. If you are unsure if you added it, double check if the parentNode is non-null before calling removeChild.
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
You still can run it from File explorer on Windows 10 with the proper path. You just need to go to C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
and double click the file monitor.
If you want to use in the cmd just the 'monitor' command you have to add this folder (in my case with android studio 3.4.1 and win10) to your Environment variables. So, press the start button and then type Edit the system environment variabes
click it and System properties window should open. Then go to
Environment variables => System variables => path
press the Edit
button for path and add the new value
C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
click 'Ok', 'Ok' and 'Ok' and restart the cmd window if you had it opened and type 'monitor' and it should open the monitor as well.
Hope it helps!
PD: This answer was based on this answer https://stackoverflow.com/a/55077068/5360905 from Tiago Martins Peres
Below Function Perfectly Working on iOS7 or later version in Swift
func DeviceName()-> String {
var myDeviceName : String = String()
var systemInfo = [UInt8](count: sizeof(utsname), repeatedValue: 0)
let model = systemInfo.withUnsafeMutableBufferPointer { (inout body: UnsafeMutableBufferPointer<UInt8>) -> String? in
if uname(UnsafeMutablePointer(body.baseAddress)) != 0 {
return nil
}
return String.fromCString(UnsafePointer(body.baseAddress.advancedBy(Int(_SYS_NAMELEN * 4))))
}
let deviceNamesByCode : [String: String] = ["iPod1,1":"iPod Touch 1",
"iPod2,1":"iPod Touch 2",
"iPod3,1":"iPod Touch 3",
"iPod4,1":"iPod Touch 4",
"iPod5,1":"iPod Touch 5",
"iPod7,1":"iPod Touch 6",
"iPhone1,1":"iPhone",
"iPhone1,2":"iPhone ",
"iPhone2,1":"iPhone ",
"iPhone3,1":"iPhone 4",
"iPhone3,2":"iPhone 4",
"iPhone3,3":"iPhone 4",
"iPhone4,1":"iPhone 4s",
"iPhone5,1":"iPhone 5",
"iPhone5,2":"iPhone 5",
"iPhone5,3":"iPhone 5c",
"iPhone5,4":"iPhone 5c",
"iPhone6,1":"iPhone 5s",
"iPhone6,2":"iPhone 5s",
"iPhone7,2":"iPhone 6",
"iPhone7,1":"iPhone 6 Plus",
"iPhone8,1":"iPhone 6s",
"iPhone8,2":"iPhone 6s Plus",
"iPhone8,4":"iPhone SE",
"iPad2,1":"iPad 2",
"iPad2,2":"iPad 2",
"iPad2,3":"iPad 2",
"iPad2,4":"iPad 2",
"iPad3,1":"iPad 3",
"iPad3,2":"iPad 3",
"iPad3,3":"iPad 3",
"iPad3,4":"iPad 4",
"iPad3,5":"iPad 4",
"iPad3,6":"iPad 4",
"iPad4,1":"iPad Air",
"iPad4,2":"iPad Air",
"iPad4,3":"iPad Air",
"iPad5,3":"iPad Air 2",
"iPad5,4":"iPad Air 2",
"iPad2,5":"iPad Mini",
"iPad2,6":"iPad Mini",
"iPad2,7":"iPad Mini",
"iPad4,4":"iPad Mini 2",
"iPad4,5":"iPad Mini 2",
"iPad4,6":"iPad Mini 2",
"iPad4,7":"iPad Mini 3",
"iPad4,8":"iPad Mini 3",
"iPad4,9":"iPad Mini 3",
"iPad5,1":"iPad Mini 4",
"iPad5,2":"iPad Mini 4",
"iPad6,3":"iPad Pro",
"iPad6,4":"iPad Pro",
"iPad6,7":"iPad Pro",
"iPad6,8":"iPad Pro",
"AppleTV5,3":"Apple TV",
"i386":"Simulator",
"x86_64":"Simulator"
]
if model!.characters.count > 0 {
myDeviceName = deviceNamesByCode[model!]!
}else{
myDeviceName = UIDevice.currentDevice().model
}
print("myDeviceName==\(myDeviceName)")
return myDeviceName
}
On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:
Update: Tha latest version
brew instal php --with-imap
will not work any more!!!
$ brew install php72 --with-imap
Warning: homebrew/php/php72 7.2.xxx is already installed
Also, installing module only, here will not work:
$ brew install php72-imap
Error: No available formula with the name "php72-imap"
So, we must reinstall it:
$ brew reinstall php72 --with-imap
It will take a while :-) (built in 8 minutes 17 seconds)
Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.
You should do this with any object that implements AutoClosable.
try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
String sqlToExecute = "SELECT * FROM persons";
try (ResultSet resultSet = statement.execute(sqlToExecute)) {
if (resultSet.next()) {
System.out.println(resultSet.getString("name");
}
}
} catch (SQLException e) {
System.out.println("Failed to select persons.");
}
The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.
in below code midpointsList is an ArrayList of waypoints
private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;
String midpoints = "";
for (int mid = 0; mid < midpointsList.size(); mid++) {
midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
}
String waypoints = "waypoints=optimize:true" + midpoints + "|";
String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
Log.e("url", url);
parseDirectionApidata(url, googleMap);
return url;
}
Then copy and paste this url in your browser to check And the below code is to parse the url
private void parseDirectionApidata(String url, final GoogleMap googleMap) {
final JSONObject jsonObject = new JSONObject();
try {
AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
@Override
public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {
if (jsonResult != null) {
Log.e("jsonRes", jsonResult.toString());
String status = jsonResult.optString("status");
if (status.equalsIgnoreCase("ok")) {
drawPath(jsonResult, googleMap);
}
} else {
Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
}
}
}, url, jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
And then pass the result to the drawPath method
public void drawPath(JSONObject jObject, GoogleMap googleMap) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
List<LatLng> list = null;
try {
Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
list = decodePoly(polyline);
}
Log.e("list", list.toString());
routes.add(path);
Log.e("routes", routes.toString());
if (list != null) {
Polyline line = googleMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
.geodesic(true)
);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
decode poly function is to decode the points(lat and long) provided by Directions API in encoded form
While most people blindly follow the advice of the javadoc, there are very specific situations where you want to actually avoid toString(). For example, I'm using enums in my Java code, but they need to be serialized to a database, and back again. If I used toString() then I would technically be subject to getting the overridden behavior as others have pointed out.
Additionally one can also de-serialize from the database, for example, this should always work in Java:
MyEnum taco = MyEnum.valueOf(MyEnum.TACO.name());
Whereas this is not guaranteed:
MyEnum taco = MyEnum.valueOf(MyEnum.TACO.toString());
By the way, I find it very odd for the Javadoc to explicitly say "most programmers should". I find very little use-case in the toString of an enum, if people are using that for a "friendly name" that's clearly a poor use-case as they should be using something more compatible with i18n, which would, in most cases, use the name() method.
I had a similar issue where I was creating a numeric color without considering the leading alpha channel. ie. mytext.setTextColor(0xFF0000)
(thinking this would be red ). While this is a red color it is also 100% transparent as it = 0x00FF0000;
The correct 100% opaque value is 0xFFFF0000
or mytext.setTextcolor(0xFFFF0000)
.
HTML
<input type="text" name="number" only-digits>
// Just type 123
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
// type: 123 or 123.45
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
Maybe something like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
My two suggestions:
Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs
If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.
Why not just do as described under http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast
df.select(df.year.cast("int"),"make","model","comment","blank")
while number:
digit = number % 10
# do whatever with digit
# remove last digit from number (as integer)
number //= 10
On each iteration of the loop, it removes the last digit from number, assigning it to digit
.
It's in reverse, starts from the last digit, finishes with the first
I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
Not only can you, but you have to make a special effort not to if you don't want to. :-)
When the browser encounters a classic script
tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write
calls to output markup that the parser should handle).
That's the default behavior, but you have a few options for delaying script execution:
Use JavaScript modules. A type="module"
script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:
<script type="module" src="./my-code.js"></script>
<!-- Or -->
<script type="module">
// Your code here
</script>
The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)
This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.
Use the defer
attribute on a classic script tag:
<script defer src="./my-code.js"></script>
As with the module, the code in my-code.js
will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer
doesn't work with inline script content, only with external files referenced via src
.
I don't think it's what you want, but you can use the async
attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module"
tag, or use it instead of defer
on a classic script
tag.
Put the script
tag at the end of the document, just prior to the closing </body>
tag:
<!doctype html>
<html>
<!-- ... -->
<body>
<!-- The document's HTML goes here -->
<script type="module" src="./my-code.js"></script><!-- Or inline script -->
</body>
</html>
That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.
It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script
tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer
are better options.
The spec has a useful diagram showing a raw script
tag, defer
, async
, type="module"
, and type="module" async
and the timing of when the JavaScript code is fetched and run:
Here's an example of the default behavior, a raw script
tag:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
}_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
(See my answer here for details around that NodeList
code.)
When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.
In contrast, here's a type="module"
script:
.found {_x000D_
color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
document.querySelectorAll("p").forEach(p => {_x000D_
p.classList.add("found");_x000D_
});_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer
script
with external content (but not inline content).
(There was no need for the NodeList
check there because any modern browser supporting modules already has forEach
on NodeList
.)
In this modern world, there's no real value to the DOMContentLoaded
event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer
. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script
was in the head
instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body
, again back in the day.
Interestingly, I had the same exact issue and for me the problem was that my connection was timing out. To be able to see more details on my connections, I added $mail->SMTPDebug = 4;
to my phpmailer (look up how to capture the debug since the default output function is echo).
Here's the result:
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is ""
SMTP -> get_lines(): $data is ""
SMTP -> get_lines(): timed-out (10 seconds)
SMTP -> FROM SERVER:
SMTP -> ERROR: DATA not accepted from server:
The default timeout is set to 10 seconds. If your app can support more, add this line to your phpmailer:
$mail->Timeout = 20;
Getting this error, I changed the
c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD
for both code project and associated Google Test project. This solved the issue.
Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.
SOLVED WITH WIFI Router Setting :
I got same issue when I am in wifi with Settings PPPoE(auto login by wifi router).
Git download speed is very slow 15kb.
packet_write_wait: Connection to 17.121.133.16 port 22: Broken pipe fatal: The remote end hung up unexpectedly fatal: early EOF fatal: index-pack failed
Solution : 1. Changed setting to Dynamic IP, reboot wifi router. 2. From web browser login to Internet service provider portal (do not configure PPPoE , auto login from the wifi router).
After changing Git download speed is 1.7MiB.
Just loop through all the <strong>
tags and use next_sibling
to get what you want. Like this:
for strong_tag in soup.find_all('strong'):
print(strong_tag.text, strong_tag.next_sibling)
Demo:
from bs4 import BeautifulSoup
html = '''
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''
soup = BeautifulSoup(html)
for strong_tag in soup.find_all('strong'):
print(strong_tag.text, strong_tag.next_sibling)
This gives you:
YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN
If anyone finds themselves in a position where they need to remember set -e or set -x values and be able to restore them, please check out this gist which uses the first array deletion solution to manage it's own stack:
https://gist.github.com/kigster/94799325e39d2a227ef89676eed44cc6
As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.
If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
This can be recast into SQLite as:
INSERT INTO 'tablename'
SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs
within a single transaction:
BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;
If efficiency is your goal, you should try this first.
As several people commented, if you use UNION ALL
(as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2
. If you omit the ALL
, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.
P.S.: Please +1 river's reply, as it presented the solution first.
I am using the following environment
? python --version; ipython --version; jupyter --version
Python 3.5.2+
5.3.0
5.0.0
and the following aliases work well for me
alias pyspark="PYSPARK_PYTHON=/usr/local/bin/python3 PYSPARK_DRIVER_PYTHON=ipython ~/spark-2.1.1-bin-hadoop2.7/bin/pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11"
alias pysparknotebook="PYSPARK_PYTHON=/usr/bin/python3 PYSPARK_DRIVER_PYTHON=jupyter PYSPARK_DRIVER_PYTHON_OPTS='notebook' ~/spark-2.1.1-bin-hadoop2.7/bin/pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11"
In the notebook, I set up the environment as follows
from pyspark.context import SparkContext
sc = SparkContext.getOrCreate()
I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":
#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2
# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1
# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"
# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`
# go back to the original branch (assume master for this example)
git checkout master
# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2
There is no sudo command in case of windows and also there is no need to put any $. For installing Angular CLI through node.js command prompt in windows, I just wrote npm install -g @angular/cli and then pressed Enter. It worked fine.
It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push('/path')
Also see the replies to the this github issue: https://github.com/ReactTraining/react-router/issues/4059
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah
and have to specify it every time or use another syntax/approach,
I don't have enough reputation to add a comment on the answer from pomber so I'm posting another answer. Using pomber's approach I kept receiving a "400 Bad Request" response from an API I was POSTing my JSON request to (Visual Studio 2017, .NET 4.6.2). Eventually the problem was traced to the "Content-Type" header produced by StringContent() being incorrect (see https://github.com/dotnet/corefx/issues/7864).
tl;dr
Use pomber's answer with an extra line to correctly set the header on the request:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;
set -x
Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
[source]
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
expr
has been evaluated.echo
has been evaluated.To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
What everyone here is missing is Java's guarantee of definite assignment for final member variables.
For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.
C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.
So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.
Much simpler solution:
pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])
Yields,
team1 team2
-------------
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
7 SF NYG
If you wanted to split a column of delimited strings rather than lists, you could similarly do:
pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
columns=['team1', 'team2'])
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
As of 2018,
use MiniCssExtractPlugin
for Webpack(> 4.0) will solve this problem.
https://github.com/webpack-contrib/mini-css-extract-plugin
Using extract-text-webpack-plugin
in the accepted answer is NOT recommended for Webpack 4.0+.
<div class="container">
<div class="row justify-content-center">
<div class="col-3 text-center">
Center text goes here
</div>
</div>
</div>
I have used justify-content-center
class instead of mx-auto
as in this answer.
i have resolved this by following steps.
1) Go to customise icon in the top right corner chrome.
2) click on
more tools option.
3) Click task manager.
4) Kill/end process GPU process
This has resolved my issue of black screen in chrome.
Should be
<input type="button" class="btn btn-success"
style="font-weight: bold;display: inline;"
value="Close"
onclick="closeMe()">
<script>
function closeMe()
{
window.opener = self;
window.close();
}
</script>
One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE
and TRANSPARENT
.
With WINDOW
it works fine. That one took some time to find out! grr...
(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE
)
To generate a certificate on the Apple provisioning profile website, firstly you have to generate keys on your mac, then upload the public key. Apple will generate your certificates with this key. When you download your certificates, tu be able to use them you need to have the private key.
The error "XCode could not find a valid private-key/certificate pair for this profile in your keychain." means you don't have the private key.
Maybe because your Mac was reinstalled, maybe because this key was generated on another Mac. So to be able to use your certificates, you need to find this key and install it on the keychain.
If you can not find it you can generate new keys restart this process on the provisioning profile website and get new certificates you will able to use.
BEGIN...END works, you just have to add a commented section. The easiest way to do this is to add a section name! Another route is to add a comment block. See below:
BEGIN -- Section Name
/*
Comment block some stuff --end comment should be on next line
*/
--Very long query
SELECT * FROM FOO
SELECT * FROM BAR
END
set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());
Quicksort is the fastest sorting algorithm in practice but has a number of pathological cases that can make it perform as badly as O(n2).
Heapsort is guaranteed to run in O(n*ln(n)) and requires only finite additional storage. But there are many citations of real world tests which show that heapsort is significantly slower than quicksort on average.
If you absolutely need to only use one regex then
/(?=.*?(string1))(?=.*?(string2))/is
i modifier = case-insensitive
.*? Lazy evaluation for any character (matches as few as possible)
?= for Positive LookAhead it has to match somewhere
s modifier = .(period) also accepts line breaks
I was wired, but my project was already migrated to AndroidX, but after migrating to androidX again, it refactored some part of my project and the problem solved.
The problem is that the small figure region 2 created by your layout()
call is not sufficiently large enough to contain just the default margins, let alone a plot.
More generally, you get this error if the size of the plotting region on the device is not large enough to actually do any plotting. For the OP's case the issue was having too small a plotting device to contain all the subplots and their margins and leave a large enough plotting region to draw in.
RStudio users can encounter this error if the Plot tab is too small to leave enough room to contain the margins, plotting region etc. This is because the physical size of that pane is the size of the graphics device. These are not independent issues; the plot pane in RStudio is just another plotting device, like png()
, pdf()
, windows()
, and X11()
.
Solutions include:
reducing the size of the margins; this might help especially if you are trying, as in the case of the OP, to draw several plots on the same device.
increasing the physical dimensions of the device, either in the call to the device (e.g. png()
, pdf()
, etc) or by resizing the window / pane containing the device
reducing the size of text on the plot as that can control the size of margins etc.
Before the line causing the problem try:
par(mar = rep(2, 4))
then plot the second image
image(as.matrix(leg),col=cx,axes=T)
You'll need to play around with the size of the margins on the par()
call I show to get this right.
You may also need to increase the size of the actual device onto which you are plotting.
A final tip, save the par()
defaults before changing them, so change your existing par()
call to:
op <- par(oma=c(5,7,1,1))
then at the end of plotting do
par(op)
Pure JS solution is as follows:
function clearForm(myFormElement) {
var elements = myFormElement.elements;
myFormElement.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
Use the os.EOL constant instead.
var os = require("os");
function processInput ( text )
{
fs.open('H://log.txt', 'a', 666, function( e, id ) {
fs.write( id, text + os.EOL, null, 'utf8', function(){
fs.close(id, function(){
console.log('file is updated');
});
});
});
}
$('.class1, .class2').on('click', some_function);
Or:
$('.class1').add('.class2').on('click', some_function);
This also works with existing objects:
const $class1 = $('.class1');
const $class2 = $('.class2');
$class1.add($class2).on('click', some_function);
For debugging JavaScript code in VS2015, there is no need for
Attaching IE didn't work, but here is a workaround.
Select IE
and press F5. This will attach both worker process and IE as shown here-
If you are not interested in debugging server code, detach it from Processes window.
You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.
In most circumstances, I recommend using the <object>
tag to display SVG images. It feels a little unnatural, but it's the most reliable method if you want to provide dynamic effects.
For images without interaction, the <img>
tag or a CSS background can be used.
Inline SVGs or iframes are possible options for some projects, but it's best to avoid <embed>
But if you want to play with SVG stuff like
Go with the embedded one
<svg>
<g>
<path> </path>
</g>
</svg>
preg_split
the variable containing the text, and iterate over the returned array:
foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
// do stuff with $line
}
http://localhost/security/index.php
http://localhost/security/xamppsecurity.php
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:background="#000"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/header"
app:itemTextColor="your color"
app:menu="@menu/drawer" />
Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.
Try by changing X[:,3] to X.iloc[:,3] in label encoder
Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.
Escape dot. Sample command will be.
grep '0\.00'
First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....
You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select
Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.
= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use
$data = file_get_contents("php://input");
to just retrieve the http body and handle it yourself. See PHP input/output streams.
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.
Most Developers log-in to server(I assume you r having user-name and password for mysql database) then from Bash they switch to mysql> prompt
then use the command below(which doesn’t work
mysql -h localhost -u root -p
What needs to be done is use the above command in the bash prompt--> on doing so it will ask for password if given it will take directly to mysql prompt and
then database, table can be created one by one
I faced similar deadlock so sharing the experience
@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the +
operator fails for strings in EL (which is correct), then just do:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do:
<c:out value="${resp}${test}" />
While there are limits to query-string lengths that should be considered (for sending JSON data in HTTP/s GET calls versus using POST) ...
JSON.stringify(yourJSON) will create a String from your JSON object.
Then just hex-encode it (link below).
That will work ALWAYS versus various possible problems with base64 type URL encoding, UTF-8 characters, nested JSON objects and such.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
To see a frequency count for column two (for example):
awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr
fileA.txt
z z a
a b c
w d e
fileB.txt
t r e
z d a
a g c
fileC.txt
z r a
v d c
a m c
Result:
3 d
2 r
1 z
1 m
1 g
1 b
You should use scaleY instead.
ul {_x000D_
background-color: #eee;_x000D_
transform: scaleY(0); _x000D_
transform-origin: top;_x000D_
transition: transform 0.26s ease;_x000D_
}_x000D_
p:hover ~ ul {_x000D_
transform: scaleY(1);_x000D_
}
_x000D_
<p>Hover This</p>_x000D_
<ul>_x000D_
<li>Coffee</li>_x000D_
<li>Tea</li>_x000D_
<li>Milk</li>_x000D_
</ul>
_x000D_
I've made a vendor prefixed version of the above code on jsfiddle, and changed your jsfiddle to use scaleY instead of height.
In Python 3, map
returns an iterable object of type map
, and not a subscriptible list, which would allow you to write map[i]
. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
I have an alternative to the methods above that used the ALT tag and a CSS selector on the alt tag... Instead, add a URL hash like this:
First your Markdown image code:
![my image](/img/myImage.jpg#left)
![my image](/img/myImage.jpg#right)
![my image](/img/myImage.jpg#center)
Note the added URL hash #center.
Now add this rule in CSS using CSS 3 attribute selectors to select images with a certain path.
img[src*='#left'] {
float: left;
}
img[src*='#right'] {
float: right;
}
img[src*='#center'] {
display: block;
margin: auto;
}
You should be able to use a URL hash like this almost like defining a class name and it isn't a misuse of the ALT tag like some people had commented about for that solution. It also won't require any additional extensions. Do one for float right and left as well or any other styles you might want.
If you want nice json without hardcoding attributes into your service classes,
use <webHttp defaultOutgoingResponseFormat="Json"/>
in your behavior config
In this case, it doesn't matter as there is no content between the two div
s.
Either one will get the browser to scroll down to it.
The a
element will look like:
<a href="mypageName.html#buttonOne">buttonOne</a>
Or:
<a href="mypageName.html#linkedinB">linkedinB</a>
You also could set both parameters like,
mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );
This locates your map on a specific position and zoom. I use this on the setting up my map.
As pointed out by Tanis.7x, the support library version (23) does not match the targetSdkVersion (22)
You can fix this by doing the following:
In the build.grade
file of your app module, change the following line of code
compile 'com.android.support:appcompat-v7:23.0.0'
To
compile 'com.android.support:appcompat-v7:22.+'
This will use the latest version of the appcompat version that is compatible with SdkVersion 22.
Two years on, and this issue is still around...
In iOS 8 / XCode 6.1, I was sometimes finding that my UILabel
(created in a UITableViewCell
, with AutoLayout turned on, and flexible constraints so it had plenty of space) wouldn't resize itself to fit the text string.
The solution, as in previous years, was to set the text, and then call sizeToFit
.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
. . .
cell.lblCreatedAt.text = [note getCreatedDateAsString];
[cell.lblCreatedAt sizeToFit];
}
(Sigh.)
Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.
The pure list comprehension algorithms are O(n^2), since in
on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.
#!/usr/bin/env python
''' Time list- vs set-based list intersection
See http://stackoverflow.com/q/3697432/4014959
Written by PM 2Ring 2015.10.16
'''
from __future__ import print_function, division
from timeit import Timer
setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'
cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'
cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'
reps = 3
loops = 50000
def do_timing(heading, cmd, setup):
t = Timer(cmd, setup)
r = t.repeat(reps, loops)
r.sort()
print(heading, r)
return r[0]
m = 10
nums = list(range(6 * m))
for n in range(1, m + 1):
a = nums[:6*n:2]
b = nums[:6*n:3]
print('\nn =', n, len(a), len(b))
#print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
la = do_timing('lista', cmd_lista, setup)
lb = do_timing('listb', cmd_listb, setup)
lc = do_timing('lcsa ', cmd_lcsa, setup)
sa = do_timing('seta ', cmd_seta, setup)
sb = do_timing('setb ', cmd_setb, setup)
print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)
output
n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214
n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462
n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902
n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493
n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847
n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495
n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951
n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871
n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594
n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523
Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).
These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.
A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.
I'll use this example to simulate a coroutine that will raise exceptions, sometimes -
import asyncio
import random
async def a_flaky_tsk(i):
await asyncio.sleep(i) # bit of fuzz to simulate a real-world example
if i % 2 == 0:
print(i, "ok")
else:
print(i, "crashed!")
raise ValueError
coros = [a_flaky_tsk(i) for i in range(10)]
await asyncio.gather(*coros)
outputs -
0 ok
1 crashed!
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
asyncio.run(main())
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
await asyncio.gather(*coros)
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
As you can see, the coros after index 1
never got to execute.
But await asyncio.wait(coros)
continues to execute tasks, even if some of them fail -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Ofcourse, this behavior can be changed for both by using -
asyncio.gather(..., return_exceptions=True)
or,
asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)
But it doesn't end here!
Notice:
Task exception was never retrieved
in the logs above.
asyncio.wait()
won't re-raise exceptions from the child tasks until you await
them individually. (The stacktrace in the logs are just messages, they cannot be caught!)
done, pending = await asyncio.wait(coros)
for tsk in done:
try:
await tsk
except Exception as e:
print("I caught:", repr(e))
Output -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
On the other hand, to catch exceptions with asyncio.gather()
, you must -
results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
if isinstance(result_or_exc, Exception):
print("I caught:", repr(result_or_exc))
(Same output as before)
Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args]
.
Of course this assumes that .NET is installed on the target machine.
Here's the code. Feel free to copy!
using System;
using System.Diagnostics;
using System.Text;
namespace dotNetLauncher
{
class Program
{
/*
If you make .NET Core applications, they have to be launched like .NET blah.dll args here
This is a convenience EXE file that launches .NET Core applications via name.exe
Just rename the output exe to the name of the .NET Core DLL file you wish to launch
*/
static void Main(string[] args)
{
var exePath = AppDomain.CurrentDomain.BaseDirectory;
var exeName = AppDomain.CurrentDomain.FriendlyName;
var assemblyName = exeName.Substring(0, exeName.Length - 4);
StringBuilder passInArgs = new StringBuilder();
foreach(var arg in args)
{
bool needsSurroundingQuotes = false;
if (arg.Contains(" ") || arg.Contains("\""))
{
passInArgs.Append("\"");
needsSurroundingQuotes = true;
}
passInArgs.Append(arg.Replace("\"","\"\""));
if (needsSurroundingQuotes)
{
passInArgs.Append("\"");
}
passInArgs.Append(" ");
}
string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";
var p = new Process
{
StartInfo = new ProcessStartInfo("dotnet", callingArgs)
{
UseShellExecute = false
}
};
p.Start();
p.WaitForExit();
}
}
}
I suggest you truncate first, and then format:
double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);
Use the constant 100 for 2 digits truncate; use a 1 followed by as many zeros as digits after the decimal point you would like. Use the culture name you need to adjust the formatting result.
Use JavaScript for the main form / Button click event. An example is:
Context.Response.Write("<script language='javascript'>window.open('AccountsStmt.aspx?showledger=" & sledgerGrp & "','_newtab');</script>")
Try to play around also with the calc
and overflow
functions
.myClassName {
overflow: auto;
height: calc(100% - 1.5em);
}
Hello I solved it like this:
Install Application> Xcode.app> Contents> Resources> Packages> XcodeSystemResources.pkg.
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
Sometimes (for example in osgeo4w distribution) tkinter is removed.
Try changing matplotlib backend editing matplotlibrc file located in [python install dir]/matplotlib/mpl-data/matplotlibrc
changing The backend parameter from backend: TkAgg
to something other like backend: Qt4Agg
as described here: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
You can use the lock
statement instead. I think this can only replace the second version. Also, remember that both synchronized
and lock
need to operate on an object.
go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.
I will show visually the problem, using the great example from James answer and adding the alternative solution.
When you do the follow query, without the FETCH
:
Select e from Employee e
join e.phones p
where p.areaCode = '613'
You will have the follow results from Employee
as you expected:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
1 | James | 6 | 416 |
But when you add the FETCH
word on JOIN
, this is what happens:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416
register when you use WHERE
on the FETCH
join.
So, to bring all phones and apply the WHERE
correctly, you need to have two JOIN
s: one for the WHERE
and another for the FETCH
. Like:
Select e from Employee e
join e.phones p
join fetch e.phones //no alias, to not commit the mistake
where p.areaCode = '613'
Then provided your button is showing and the click event is being fired you can call the following in your click event:
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag");
ft.commit();
and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.
ft.addToBackStack(null);
Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.
Finally stumbled on tmpreaper and it has been worked pretty well for us so far.
tmpreaper -t 5d ~/Downloads
tmpreaper --protect '*.c' -t 5h ~/my_prg
Original Source link
Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting
The final
keyword indicates that a variable may only be initialized once. In your code you are only performing one initialization of final so the terms are satisfied. This statement performs the lone initialization of foo
. Note that final
!= immutable, it only means that the reference cannot change.
foo = new ArrayList();
When you declare foo
as static final
the variable must be initialized when the class is loaded and cannot rely on instantiation (aka call to constructor) to initialize foo
since static fields must be available without an instance of a class. There is no guarantee that the constructor will have been called prior to using the static field.
When you execute your method under the static final
scenario the Test
class is loaded prior to instantiating t
at this time there is no instantiation of foo
meaning it has not been initialized so foo
is set to the default for all objects which is null
. At this point I assume your code throws a NullPointerException
when you attempt to add an item to the list.
Answer in Swift 5 (Continuation of Ricky's answer in Swift)
Add the
UIGestureRecognizerDelegate
to your ViewController
override func viewDidLoad() {
super.viewDidLoad()
//Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.minimumPressDuration = 0.5
self.tableView.addGestureRecognizer(longPressGesture)
}
And the function:
@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
let p = longPressGesture.location(in: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: p)
if indexPath == nil {
print("Long press on table view, not row.")
} else if longPressGesture.state == UIGestureRecognizer.State.began {
print("Long press on row, at \(indexPath!.row)")
}
}
I have just had this under Win 7.
$ git stash pop error: cannot stat 'parentFolder/subfolder': Permission denied error: cannot stat 'parentFolder/subfolder': Permission denied
Diagnosis:
1>I went to the subfolder and it's there and I couldn't delete it !
2>Use "process explorer" -> Find -> Find handles and Dlls -> put the "subfolder" name there and search.
Result: It turns out it's XMLSpy has opened one of the xml there, close XML Spy and try stash pop again, it's working now.
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
if ($name ) { #since undef and '' both evaluate to false #this should work only when string is defined and non-empty... #unless you're expecting someting like $name="0" which is false. #notice though that $name="00" is not false }
Using lapply and grep:
lst <- list(a = 1:4, b = 4:8, c = 8:10)
# say you want to remove a and c
toremove<-c("a","c")
lstnew<-lst[-unlist(lapply(toremove, function(x) grep(x, names(lst)) ) ) ]
#or
pattern<-"a|c"
lstnew<-lst[-grep(pattern, names(lst))]
Non-javascript way . . aspx page:
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>
Code Behind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If Not CheckBox1.Checked Then
args.IsValid = False
End If
End Sub
For any actions you might need (business Rules):
If Page.IsValid Then
'do logic
End If
Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
Change statement to
DBCC CHECKIDENT('TableName', RESEED, 1)
This will start from 2 (or 1 when you recreate table), but it will never be 0.
Obfuscating things can only inconvenience your legitimate, law-abiding customers, while the people who would would rip you off are not your target paying customers anyway. (edited out other thoughts about obfuscation)
Another suggestion for protecting your software: create a business model in which the code is an incomplete part of the value of your offering. For example, sell product licenses along with access to some data you manage on your site, or license the product on a subscription model or with customer support.
Designing a EULA is a legal matter, not a coding matter. You can start by reading some EULA text for products and websites you use. You might find some interesting details!
Creating a proprietary license is is highly flexible, and probably a subject beyond the intended scope of StackOverflow, since it's not strictly about coding.
Some parts of a EULA that come to mind:
You should consult a legal professional to prepare a commercial EULA.
edit: If this project can't justify the expense of a lawyer, check out these resources:
You want to apply the fixed property to the position style of the element.
position: fixed;
What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here
http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html
Here's another solution that avoids the use of jObject.CreateReader()
, and instead creates a new JsonTextReader
(which is the behavior used by the default JsonCreate.Deserialze
method:
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
StringWriter writer = new StringWriter();
serializer.Serialize(writer, jObject);
using (JsonTextReader newReader = new JsonTextReader(new StringReader(writer.ToString())))
{
newReader.Culture = reader.Culture;
newReader.DateParseHandling = reader.DateParseHandling;
newReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
newReader.FloatParseHandling = reader.FloatParseHandling;
serializer.Populate(newReader, target);
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
You can make a div that has the same attributes as the <hr>
tag. This way it is fully able to be customized. Here is some sample code:
<h3>This is a header.</h3>
<div class="customHr">.</div>
<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>
.customHr {
width: 95%
font-size: 1px;
color: rgba(0, 0, 0, 0);
line-height: 1px;
background-color: grey;
margin-top: -6px;
margin-bottom: 10px;
}
To see how the project turns out, here is a JSFiddle for the above code: http://jsfiddle.net/SplashHero/qmccsc06/1/
use a negative character class:
[^,;]+
If you want to do it without using jquery or modenizer you can use the code below:
(function(){
"use strict";
//shim for String's trim function..
function trim(string){
return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
}
//returns whether the given element has the given class name..
function hasClassName(element, className){
//refactoring of Prototype's function..
var elClassName = element.className;
if(!elClassName)
return false;
var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
return regex.test(element.className);
}
function removeClassName(element, className){
//refactoring of Prototype's function..
var elClassName = element.className;
if(!elClassName)
return;
element.className = elClassName.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
}
function addClassName(element, className){
var elClassName = element.className;
if(elClassName)
element.className += " " + className;
else
element.className = className;
}
//strings to make event attachment x-browser..
var addEvent = document.addEventListener ?
'addEventListener' : 'attachEvent';
var eventPrefix = document.addEventListener ? '' : 'on';
//the class which is added when the placeholder is being used..
var placeHolderClassName = 'usingPlaceHolder';
//allows the given textField to use it's placeholder attribute
//as if it's functionality is supported natively..
window.placeHolder = function(textField){
//don't do anything if you get it for free..
if('placeholder' in document.createElement('input'))
return;
//don't do anything if the place holder attribute is not
//defined or is blank..
var placeHolder = textField.getAttribute('placeholder');
if(!placeHolder)
return;
//if it's just the empty string do nothing..
placeHolder = trim(placeHolder);
if(placeHolder === '')
return;
//called on blur - sets the value to the place holder if it's empty..
var onBlur = function(){
if(textField.value !== '') //a space is a valid input..
return;
textField.value = placeHolder;
addClassName(textField, placeHolderClassName);
};
//the blur event..
textField[addEvent](eventPrefix + 'blur', onBlur, false);
//the focus event - removes the place holder if required..
textField[addEvent](eventPrefix + 'focus', function(){
if(hasClassName(textField, placeHolderClassName)){
removeClassName(textField, placeHolderClassName);
textField.value = "";
}
}, false);
//the submit event on the form to which it's associated - if the
//placeholder is attached set the value to be empty..
var form = textField.form;
if(form){
form[addEvent](eventPrefix + 'submit', function(){
if(hasClassName(textField, placeHolderClassName))
textField.value = '';
}, false);
}
onBlur(); //call the onBlur to set it initially..
};
}());
For each text field you want to use it for you need to run placeHolder(HTMLInputElement)
, but I guess you can just change that to suit! Also, doing it this way, rather than just on load means that you can make it work for inputs which aren't in the DOM when the page loads.
Note, that this works by applying the class: usingPlaceHolder
to the input element, so you can use this to style it (e.g. add the rule .usingPlaceHolder { color: #999; font-style: italic; }
to make it look better).
My problem turned out to be that I was assigning as document.getElementById("myinput").Value = '1';
Notice the capital V in Value? Once I changed it to small case, i.e., value, the data started posting. Odd as it was not giving any JavaScript errors either.
To use the default android drawable resource, no need copy anything.. you can just import it first with..
import android.R;
but i will make your own resources will have an error if you want to use it. The error will be something like:
R. cannot be resolved
So, I prefer not to import android.R
but import *my.own.package*.R;
then when I can normally use my own resource with R.drawable.*something*
without error,
and put android.R.*something_default*
to use the default android resources.
The answers above all over complicate the story.
That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.
In swift 4
let Totalname = "10.0" //Now it is in string
let floatVal = (Totalname as NSString).floatValue //Now converted to float
Selenium won't let you do this.
Create the Java code that can receive an argument as a command line argument.
class TestCode{
public static void main(String args[]){
System.out.println("first argument is: "+args[0]);
}
}
Run the program without arguments (press F6).
In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.
If the argument you need to pass is testArgument
, then here in this window pass the argument as application.args=testArgument
.
This will give the output as follows in the same Output window:
first argument is: testArgument
For Maven, the instructions are similar, but change the exec.args
property instead:
exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3
Note: Use single quotes for string parameters that contain spaces.
Be sure to use System.Net.Mail
, not the deprecated System.Web.Mail
. Doing SSL with System.Web.Mail
is a gross mess of hacky extensions.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
There are 3 different ways you may wish to set this up:
Thrower
inside of Catcher
Catcher
inside of Thrower
Thrower
and Catcher
inside of another class in this example Test
THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional
" code block of the class you want to be main, and set that class as the ${Main-Class}
variable in the build.xml
file:
4 Things needed on throwing side code:
import java.util.*;//import of java.util.event
//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
List<ThrowListener> listeners = new ArrayList<ThrowListener>();
public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
//Set of functions that Throw Events.
public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
System.out.println("Something thrown");
}
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}
2 Things needed in a class file to receive events from a class
/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
@Override public void Catch() {
System.out.println("I caught something!!");
}
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
This should work for matches that might overlap:
public static void main(String[] args) {
String input = "aaaaaaaa";
String regex = "aa";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
System.out.println(count);
}
Have you tried moving DEL %FILE%.txt% to after @echo %FILE% deleted. >> results.txt so that it looks like this?
@echo %FILE% deleted. >> results.txt
DEL %FILE%.txt
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted
for this to work), or change the execution policy just for the current PowerShell session:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]
The above works. Are you doing something different?
Notice that your key function is just sum
; there's no need to write it explicitly.
I had the same issue which I resolved by first moving Atom.app from downloads to Applications. Then under Atom's menu options, I selected "Install Shell Commands".
Is Arr
a base type of Obj
? Does the Obj class exist? Your code would work only if Arr is a base type of Obj. You can try this instead:
Obj[] myArray = objects.Select(o =>
{
var someLocalVar = o.someVar;
return new Obj()
{
Var1 = someLocalVar,
Var2 = o.var2
};
}).ToArray();
Here are some easy to folow steps and a great on hover tutorial its the examples that you can "play" with and test live.
http://fivera.net/simple-cool-live-examples-image-hover-css-effect/
the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..
It might either be a header file or your own function Declaration..
If you're using framework 4.0 then the entry in the web.config (<pages validateRequest="false" />)
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
If you're using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>
If you want for only single page then, In you aspx file you should put the first line as this :
<%@ Page EnableEventValidation="false" %>
if you already have something like <%@ Page so just add the rest => EnableEventValidation="false"
%>
I recommend not to do it.
It looks like you want the indices of the duplicates. Here is some short code that will find those in O(n) time, without using any packages:
dups = {}
[dups.setdefault(v, []).append(i) for i, v in enumerate(mylist)]
dups = {k: v for k, v in dups.items() if len(v) > 1}
# dups now has keys for all the duplicate values
# and a list of matching indices for each
# The second line produces an unused list.
# It could be replaced with this:
for i, v in enumerate(mylist):
dups.setdefault(v, []).append(i)
The .map
files are for js
and css
(and now ts
too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.
So, to answer you questions in order:
I hope this makes sense.
I solve problem by adding "arm64" in "Excluded Architectures" for both project target and pod target.
Xcode -> Target Project -> Build Setting -> Excluded Architectures > "arm64"
Xcode -> Pod Target -> Build Setting -> Excluded Architectures > "arm64"
Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push)
, #pragma warning (disable)
and a matching #pragma warning (pop)
, as shown here.
Although there are some other options, including #pramga warning (once)
.
I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.
One option is strtok
example:
char name[20];
//pretend name is set to the value "My name"
You want to split it at the space between the two words
split=strtok(name," ");
while(split != NULL)
{
word=split;
split=strtok(NULL," ");
}
Maybe these two examples illustrate you the difference between a deadlock and a livelock:
Java-Example for a deadlock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
}
public static void doB() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
}
}
Sample output:
Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2
Java-Example for a livelock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LivelockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(LivelockSample::doA, "Thread A");
Thread threadB = new Thread(LivelockSample::doB, "Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
public static void doB() {
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
}
Sample output:
Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...
Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
If You want to REMOVE page break from document
use Edit / Find-Replace
\f
with regex
If You want to TURN OFF (as You asked)
uncheck "Print Layout" from the "View" menu, but dotted lines will remain indicating page breaks
There is no more efficient way, if all you have is the iterator. And if the iterator can only be used once, then getting the count before you get the iterator's contents is ... problematic.
The solution is either to change your application so that it doesn't need the count, or to obtain the count by some other means. (For example, pass a Collection
rather than Iterator
...)
There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.
You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:
Top level classes:
1 public class
0 private class
any number of default/protected classes
Inner classes:
any number of inner classes with any visibility (default, private, protected, public)
Please correct me if I am wrong.
Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.
In order to match PyQt5's behavior, you have to create the started signal yourself.
Here is an easy solution:
# Use this class instead of QThread
class QThread2(QThread):
# Use this signal instead of "started"
started2 = Signal()
def __init__(self):
QThread.__init__(self)
self.started.connect(self.onStarted)
def onStarted(self):
self.started2.emit()
If you are using custom TableViewCells, the generic
[self.tableView reloadData];
does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.
To successfully reload your first table view cell without switching views, use the following code:
//For iOS 5 and later
- (void)reloadTopCell {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):
- (void)refresh:(UIRefreshControl *)refreshControl {
//call to the method which will perform the function
[self reloadTopCell];
//finish refreshing
[refreshControl endRefreshing];
}
Now that you have that sorted, inside of your viewDidLoad
add the following:
//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the
[self.tableView reloadData];
to your new refresh method.
If you wish to reload the data every time you switch views, implement the method:
//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
I think your problem is that you are not using good OO design for your player and enemies. Create two classes:
public class Player
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
public class Enemy
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
Your Player should have X,Y,Width,and Height variables.
Your enemies should as well.
In your game loop, do something like this (C#):
foreach (Enemy e in EnemyCollection)
{
Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);
// Assuming there is an intersect method, otherwise just handcompare the values
if (r.Intersects(p))
{
// A Collision!
// we know which enemy (e), so we can call e.DoCollision();
e.DoCollision();
}
}
To speed things up, don't bother checking if the enemies coords are offscreen.
Just adding to the above answer, In a web application
@valid
is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull
, @Email
(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results.
bindingResult.hasErrors()
will tell if any validation failed.
Are you sure you're using the correct proxy as system properties?
Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
If you are using Swift:
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)
Array.join
is what you need, but if you like, the friendly people at phpjs.org have created implode
for you.
Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.
Calling a Sub Procedure – 3 Way technique
Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.
Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
msgbox strFullName
End Sub
Sub Exercise()
CreateCustomer
End Sub
Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Sub Exercise()
Call CreateCustomer
End Sub
When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Sub Exercise()
CreateCustomer()
End Sub
Procedures and Access Levels
Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:
Private Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
The rules that were applied to global variables are the same:
Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.
Also, when a procedure is private, its name does not appear in the Macros dialog box
Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.
Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there
Why not try this.
NSArray *animationFrames = [NSArray arrayWithObjects:
[UIImage imageWithName:@"image1.png"],
[UIImage imageWithName:@"image2.png"],
nil];
UIImageView *animatedImageView = [[UIImageView alloc] init];
animatedImageView.animationImages = animationsFrame;
[animatedImageView setAnimationRepeatCount:1];
[animatedImageView startAnimating];
A swift version:
let animationsFrames = [UIImage(named: "image1.png"), UIImage(named: "image2.png")]
let animatedImageView = UIImageView()
animatedImageView.animationImages = animationsFrames
animatedImageView.animationRepeatCount = 1
animatedImageView.startAnimating()
SET IDENTITY_INSERT tableA ON
INSERT Into tableA ([id], [c2], [c3], [c4], [c5] )
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB
Not like this
INSERT INTO tableA
SELECT * FROM tableB
SET IDENTITY_INSERT tableA OFF
Add a type to your variable and then return.
Eg:
const myVariable : string [] = ['hello', 'there'];
const result = myVaraible.map(x=> {
return
{
x.id
}
});
=> Important part is adding the string[] type etc:
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6
for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.
As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
if __name__ == "__main__":
for word in read_words('./very_large_file.txt'):
process(word)
The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?
If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.
If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.
I just had this issue, and moving the JS references and code towards the bottom of the page before the </body>
tag fixed it for me.
Use the following to convert uint8 array to base64 encoded string
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};
Unfortunately none of the solutions works for me.
ColorStateList themeColorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{android.R.attr.state_enabled},
new int[]{android.R.attr.state_focused, android.R.attr.state_pressed},
new int[]{-android.R.attr.state_enabled},
new int[]{} // this should be empty to make default color as we want
},
new int[]{
pressedFontColor,
defaultFontColor,
pressedFontColor,
disabledFontColor,
defaultFontColor
}
);
This is constructor from source code:
/**
* Creates a ColorStateList that returns the specified mapping from
* states to colors.
*/
public ColorStateList(int[][] states, int[] colors) {
mStateSpecs = states;
mColors = colors;
if (states.length > 0) {
mDefaultColor = colors[0];
for (int i = 0; i < states.length; i++) {
if (states[i].length == 0) {
mDefaultColor = colors[i];
}
}
}
}
How to create CascadeClassifier :
In a large group at my company, we use C++ almost exclusively. Passing by non-const reference is forbidden.
If you want to modify a parameter to a function, you must pass it by pointer.
We have an internal flame war over the pros (easier to identify function calls that can modify variables) and cons (ridiculousness; having to deal with possible NULL pointers when you want a parameter to be required) about once a year.
I know others have mentioned String.split
, but here is a variant that only yields two tokens (the base and the extension):
String[] tokens = fileName.split("\\.(?=[^\\.]+$)");
For example:
"test.cool.awesome.txt".split("\\.(?=[^\\.]+$)");
Yields:
["test.cool.awesome", "txt"]
The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).
Technically Regexically speaking, this technique is called zero-width positive lookahead.
BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,
String[] tokens = dir.split(".+?/(?=[^/]+$)");
For example:
String dir = "/foo/bar/bam/boozled";
String[] tokens = dir.split(".+?/(?=[^/]+$)");
// [ "/foo/bar/bam/" "boozled" ]
A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.
Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.
Hope the explanation is clear enough.
If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.
You can solve this by adding the following statement to the NAMESPACE:
exportPattern("^[^\\\\.]")
This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:
.myHiddenFunction <- function(x) cat("my hidden function")
Java doesn't have associative arrays, the closest thing you can get is the Map interface
Here's a sample from that page.
import java.util.*;
public class Freq {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
// Initialize frequency table from command line
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
}
If run with:
java Freq if it is to be it is up to me to delegate
You'll get:
8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653
I think @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
should work.
You need to write it like
string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is correct");
else
Response.Write(email + " is incorrect");
Be warned that this will fail if:
There is a subdomain after the @
symbol.
You use a TLD with a length greater than 3, such as .info
If all the other answers didn't work for you, try disabling HTTP input encoding translation.
This is a setting related to PHP extension mbstring. This was the problem in my case. This setting was enabled by default in my server.
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
I know this is old. But yeah. I prefer much shorter solution, than Giona answer
[contenteditable] {
border-bottom: 1px solid transparent;
&:focus {outline: none; border-bottom: 1px dashed #000;}
}
I started using the new ASP.NET Chart control a few days ago, and it's absolutely amazing in its capabilities.
EDIT: This is obviously only if you are using ASP.NET. Not sure about WinForms.
hive -e "set hive.hwi.war.file;" | cut -d'-' -f3
Use array_search
to get the key and remove it with unset
if found:
if (($key = array_search('strawberry', $array)) !== false) {
unset($array[$key]);
}
array_search
returns false (null until PHP 4.2.0) if no item has been found.
And if there can be multiple items with the same value, you can use array_keys
to get the keys to all items:
foreach (array_keys($array, 'strawberry') as $key) {
unset($array[$key]);
}
Something like?
select t.*, round(dbms_random.value() * 8) + 1 from foo t;
Edit: David has pointed out this gives uneven distribution for 1 and 9.
As he points out, the following gives a better distribution:
select t.*, floor(dbms_random.value(1, 10)) from foo t;
You need to enable the sa
account first and log in to your SQL management studio with the sa
account (please chose SQl Server authentication).
After you logged in with the sa account, go to security
, right-click on logins
, select new login
, select SQL Server authentication
, create a user name (no /
or any other special characters, just a name), then give it a password, confirm the password and at the bottom of that page select your default Database.
Go to logins
, right-click on the user you created and click on properties
.
Go to Server Roles
and select the roles you want to give to the user you created.
Click OK
and go back to login properties
, click on User Mapping
, double-click on the database you want to map this user to and select the database role membership for that database in the bottom window.
...Just open this answer for edit to see it.
Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item
Nested lists, deeper levels:
first level B item
Nested lists, deeper levels:
...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
* first level A item - no space in front the bullet character
* second level Aa item - 1 space is enough
* third level Aaa item - 5 spaces min
* second level Ab item - 4 spaces possible too
* first level B item
For windows:
import pip
help(pip)
shows the version at the end of the help file.
Original answer 2010:
If all of those directories are separate git repo, you should reference them as submodules.
That means your "origin" would be that remote repo 'plugins
' which only contains references to subrepos 'cms
', 'admin
', 'chart
'.
A git pull
followed by a git submodule update
would achieve what your are looking for.
Update January 2016:
With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2
.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"
This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671
This solution requires both an UPDATE
and INSERT
.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507
Reading the file is easier done with the static File
class:
// First read all the text into a single string.
string text = File.ReadAllText(FileName);
// Then split the lines at "\r\n".
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
// Finally replace lonely '\r' and '\n' by whitespaces in each line.
foreach (string s in lines) {
Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
}
Note: The text might also contain vertical tabulators \v
. Those are used by Microsoft Word as manual linebreaks.
In order to catch any possible kind of breaks, you could use regex for the replacement
Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));
I don't know about JSON.NET, but it works fine with JavaScriptSerializer
from System.Web.Extensions.dll
(.NET 3.5 SP1):
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{
const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}
}
Edit:
Json.NET works using the same JSON and classes.
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType
# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"),
("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])
# Setting an user define function:
# This function converts the string cell into a date:
func = udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())
df = df1.withColumn('test', func(col('first')))
df.show()
df.printSchema()
Here is the output:
+----------+----------+----------+----------+
| first| second| third| test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+
root
|-- first: string (nullable = true)
|-- second: string (nullable = true)
|-- third: string (nullable = true)
|-- test: date (nullable = true)
For PostgreSQL:
UPDATE Sales_Import SI
SET AccountNumber = RAN.AccountNumber
FROM RetrieveAccountNumber RAN
WHERE RAN.LeadID = SI.LeadID;
There is 1 more way to do this.
Usually the .aar file is not supposed to be directly used like we use a .jar and hence the solutions mentioned above to mention it in libs folder and declaring in gradle can be avoided.
Step 1: Unpack the .aar file (You can do this by renaming its extension from ".aar" to ".zip")
Step 2: You will most probably find the .jar file in the folder after extraction. Copy this .jar file and paste it in your module/libs folder
Step 3: That's it, now sync your project and you should be able to access all classes/methods/ properties from that .jar . You don't need to mention about it's path/name/existence in any gradle file, this is because the gradle build system always looks out for files existing in libs folder while building the project
Programming habits could help too; e.g. add static
to functions that are not accessed outside a specific file; use shorter names for symbols (can help a bit, likely not too much); use const char x[]
where possible; ... this paper, though it talks about dynamic shared objects, can contain suggestions that, if followed, can help to make your final binary output size smaller (if your target is ELF).
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999
instead of "134.20"
.
If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099;
(Math.round( n * 100 )/100 ).toString() //-> "1.1"
n.toFixed(2) //-> "1.10"
var n = 3;
(Math.round( n * 100 )/100 ).toString() //-> "3"
n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
Updated mysqli version:
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
echo "Table exists";
}
}
else {
echo "Table does not exist";
}
Original mysql version:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
Referenced from the PHP docs.
A file containing some statements :
cat test.txt
Result :
This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement
So, to print the 4th word of this statement type :
cat test.txt |awk '{print $4}'
Output :
1st
2nd
3rd
4th
5th
$('.AlphabetsOnly').keypress(function (e) {
var regex = new RegExp(/^[a-zA-Z\s]+$/);
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
return false;
}
});
Don't quote me on this, but you could use goto as suggested in the MSDN. There are other solutions, as including a flag that is checked in each iteration of both loops. Finally you could use an exception as a really heavyweight solution to your problem.
GOTO:
for ( int i = 0; i < 10; ++i ) {
for ( int j = 0; j < 10; ++j ) {
// code
if ( break_condition ) goto End;
// more code
}
}
End: ;
Condition:
bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
exit = true;
break; // or continue
}
// more code
}
}
Exception:
try {
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
throw new Exception()
}
// more code
}
}
catch ( Exception e ) {}