Here is a standalone solution:
$(window).load(function() {
$('img').each(function() {
if ( !this.complete
|| typeof this.naturalWidth == "undefined"
|| this.naturalWidth == 0 ) {
// image was broken, replace with your new image
this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
}
});
});
Look at the ToLookup
and/or ToDictionary
extension methods.
This one is compatible with git repositories, and a bit simpler:
Linux:
git grep -l 'original_text' | xargs sed -i 's/original_text/new_text/g'
Mac:
git grep -l 'original_text' | xargs sed -i '' -e 's/original_text/new_text/g'
(Thanks to http://blog.jasonmeridth.com/posts/use-git-grep-to-replace-strings-in-files-in-your-git-repository/)
Can use either json or ast python modules:
Using json :
=============
import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")
Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2
Using ast:
==========
import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")
Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2
(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:
$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();
Oh, also: count()
instead if exists
but this could be something used after get
.
You can convert hex to RGB:
string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
Using Twisted's FilePath module:
from twisted.python.filepath import FilePath
def subdirs(pathObj):
for subpath in pathObj.walk():
if subpath.isdir():
yield subpath
if __name__ == '__main__':
for subdir in subdirs(FilePath(".")):
print "Subdirectory:", subdir
Since some commenters have asked what the advantages of using Twisted's libraries for this is, I'll go a bit beyond the original question here.
There's some improved documentation in a branch that explains the advantages of FilePath; you might want to read that.
More specifically in this example: unlike the standard library version, this function can be implemented with no imports. The "subdirs" function is totally generic, in that it operates on nothing but its argument. In order to copy and move the files using the standard library, you need to depend on the "open
" builtin, "listdir
", perhaps "isdir
" or "os.walk
" or "shutil.copy
". Maybe "os.path.join
" too. Not to mention the fact that you need a string passed an argument to identify the actual file. Let's take a look at the full implementation which will copy each directory's "index.tpl" to "index.html":
def copyTemplates(topdir):
for subdir in subdirs(topdir):
tpl = subdir.child("index.tpl")
if tpl.exists():
tpl.copyTo(subdir.child("index.html"))
The "subdirs" function above can work on any FilePath
-like object. Which means, among other things, ZipPath
objects. Unfortunately ZipPath
is read-only right now, but it could be extended to support writing.
You can also pass your own objects for testing purposes. In order to test the os.path-using APIs suggested here, you have to monkey with imported names and implicit dependencies and generally perform black magic to get your tests to work. With FilePath, you do something like this:
class MyFakePath:
def child(self, name):
"Return an appropriate child object"
def walk(self):
"Return an iterable of MyFakePath objects"
def exists(self):
"Return true or false, as appropriate to the test"
def isdir(self):
"Return true or false, as appropriate to the test"
...
subdirs(MyFakePath(...))
I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint
.
Even though gsprint
is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.
I convert the web page to PDF using Puppeteer, Chrome's headless browser. But you need to pass in the session cookie to maintain credentials.
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}
@sfjedi
I've created a class and assigned the css values to it.
.radioA{
vertical-align: middle;
}
It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.
Shorter answer: no, you must encode a space; it is correct to encode a space as +
, but only in the query string; in the path you must use %20
.
Note the url in DocumentCompleted can be different than navigating url due to server transfer or url normalization (e.g. you navigate to www.microsoft.com and got http://www.microsoft.com in documentcomplete)
In pages with no frames, this event fires one time after loading is complete. In pages with multiple frames, this event fires for each navigating frame (note navigation is supported inside a frame, for instance clicking a link in a frame could navigate the frame to another page). The highest level navigating frame, which may or may not be the top level browser, fires the final DocumentComplete event.
In native code you would compare the sender of the DocumentComplete event to determine if the event is the final event in the navigation or not. However in Windows Forms the sender parameter is not wrapped by WebBrowserDocumentCompletedEventArgs. You can either sink the native event to get the parameter's value, or check the readystate property of the browser or frame documents in the DocumentCompleted event handler to see if all frames are in the ready state.
There is a prolblem with the readystate method as if a download manager is present and the navigation is to a downloadable file, the navigation could be cancelled by the download manager and the readystate won't become complete.
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
How about
<!--[if IE]>
...
<![endif]-->
You can read here about conditional comments.
In addition to Doug Kavendek answer. One could use the following approach to get closer to tz_database.
var shapeFile = new ShapeFile(shapeFilePath); var shapeIndex = shapeFile.GetShapeIndexContainingPoint(new PointD(long, lat), 0D); var attrValues = shapeFile.GetAttributeFieldValues(shapeIndex); var timeZoneId = attrValues[0];
P.S. Can't insert all the links :( So please use search.
None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:
setx YOUR_VAR "VALUE"
You can access it in your scripts using os.environ['YOUR_VAR']
.
In my case, My principal was kafka/[email protected]
I got below lines in the terminal:
>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
suSec is 111309
error code is 7
error Message is Server not found in Kerberos database
cname is kafka/[email protected]
sname is kafka/[email protected]
msgType is 30
After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties
listeners=SASL_PLAINTEXT://kafka.com:9092
Also I got two entries of kafka.niroshan.com
and kafka.com
for same IP address.
I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092
Then it worked!
According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.
https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html
In my case Eclipse wasn't properly picking up a Java project that a current project was dependent on.
You can go to Project > BuildPath > Configure BuildPath and then delete and re-add the project.
new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int.
The pointer will then store the address to this block of memory.
But be careful, this allocated block of memory will not be freed until you tell it so by writing
delete [] array;
You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)
.Fixed
{
position: fixed;
top: 20px;
}
or with jQuery:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').css('top', $(this).scrollTop());
});
I'm using this in .NET 5, on Windows, with Windows Forms. It works even with other default browsers (such as Firefox):
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
border: 0
should be enough, but if it isn't, perhaps the button's browser-default styling in interfering. Have you tried setting appearance
to none
(e.g. -webkit-appearance: none
)
typeid provides the type of the data at runtime, when asked for. Typedef is a compile time construct that defines a new type as stated after that. There is no typeof in C++ Output appears as (shown as inscribed comments):
std::cout << typeid(t).name() << std::endl; // i
std::cout << typeid(person).name() << std::endl; // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl; // P6Person
std::cout << typeid(*ptr).name() << std::endl; //8Employee
If you want the value from cell then you don't have to recreate cell in the didSelectRowAtIndexPath
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println(tasks[indexPath.row])
}
Task would be as follows :
let tasks=["Short walk",
"Audiometry",
"Finger tapping",
"Reaction time",
"Spatial span memory"
]
also you have to check the cellForRowAtIndexPath
you have to set identifier.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
var (testName) = tasks[indexPath.row]
cell.textLabel?.text=testName
return cell
}
Hope it helps.
In package.json, I changed
"start": "react-scripts start"
to
"start": "NODE_ENV=production node_modules/react-scripts/bin/react-scripts.js start"
I hope this solves the problem for some people. Although the other solutions above seem not to work for me.
To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.
set "var=%cd%"
cd var
ipython notebook
If B
is a Boolean array, write
B = B*1
(A bit code golfy.)
shuffle(names)
is an in-place operation. Drop the assignment.
This function returns None
and that's why you have the error:
TypeError: object of type 'NoneType' has no len()
First of all, for initializing a container you cannot use a primitive type (i.e. int
; you can use int[]
but as you want just an array of integers, I see no use in that). Instead, you should use Integer
, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add
function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList
you may use the build-in functionality of toString()
:
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
The main concept of partial view is returning the HTML code rather than going to the partial view it self.
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
this action return the HTML code of the partial view ("HolidayPartialView").
To refresh partial view replace the existing item with the new filtered item using the jQuery below.
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
http://jdpgrailsdev.github.io/blog/2014/09/09/spring_data_hibernate_join.html
from this link:
if you are using JPA on top of Hibernate, there is no way to set the FetchMode used by Hibernate to JOINHowever, if you are using JPA on top of Hibernate, there is no way to set the FetchMode used by Hibernate to JOIN.
The Spring Data JPA library provides a Domain Driven Design Specifications API that allows you to control the behavior of the generated query.
final long userId = 1;
final Specification<User> spec = new Specification<User>() {
@Override
public Predicate toPredicate(final Root<User> root, final
CriteriaQuery<?> query, final CriteriaBuilder cb) {
query.distinct(true);
root.fetch("permissions", JoinType.LEFT);
return cb.equal(root.get("id"), userId);
}
};
List<User> users = userRepository.findAll(spec);
It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!
It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)
Thank you SQL! gnnn
I use Ubuntu 12.10 and js from commandline
It is available with my installation of java:
el@apollo:~/foo$ java -version
java version "1.6.0_27"
el@apollo:~/foo$ which js
/usr/bin/js
Some examples:
el@apollo:~/foo$ js
> 5
5
> console.log("hello");
hello
undefined
> var f = function(){ console.log("derp"); };
undefined
> f();
derp
> var mybool = new Boolean();
undefined
> mybool
{}
> mybool == true
false
> mybool == false
true
> var myobj = {};
undefined
> myobj.skipper = "on my mark, engage!"
'on my mark, engage!'
> myobj.skipper.split(" ");
[ 'on',
'my',
'mark,',
'engage!' ]
The sky is the limit, then keep right on going.
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
To count the columns of your table precisely, you can get form information_schema.columns
with passing your desired Database(Schema) Name and Table Name.
Reference the following Code:
SELECT count(*)
FROM information_schema.columns
WHERE table_schema = 'myDB'
AND table_name = 'table1';
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
This is a C# version of the answer from dhanushka using OpenCVSharp
Mat large = new Mat(INPUT_FILE);
Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();
// downsample and use it for processing
Cv2.PyrDown(large, rgb);
Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);
// morphological gradient
var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);
// binarize
Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
// connect horizontally oriented regions
morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);
// find contours
var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));
// filter contours
var idx = 0;
foreach (var hierarchyItem in hierarchy)
{
idx = hierarchyItem.Next;
if (idx < 0)
break;
OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
var maskROI = new Mat(mask, rect);
maskROI.SetTo(new Scalar(0, 0, 0));
// fill the contour
Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);
// ratio of non-zero pixels in the filled region
double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
if (r > .45 /* assume at least 45% of the area is filled if it contains text */
&&
(rect.Height > 8 && rect.Width > 8) /* constraints on region size */
/* these two conditions alone are not very robust. better to use something
like the number of significant peaks in a horizontal projection as a third condition */
)
{
Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
}
}
rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));
I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0)
instead.
Python doesn't have matrices. You can use a list of lists or NumPy
The "best" way to do this is Post / Redirect / Get
http://en.wikipedia.org/wiki/Post/Redirect/Get
After the post send a 302 header pointing to the success page
Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
You can use this js code. Just change .post-thumb img
with your img
.
$('.post-thumb img').each(function(){ // Note: {.post-thumb img} is css selector of the image tag
var t = $(this),
s = 'url(' + t.attr('src') + ')',
p = t.parent(),
d = $('<div></div>');
t.hide();
p.append(d);
d.css({
'height' : 260, // Note: You can change it for your needs
'background-size' : 'cover',
'background-repeat' : 'no-repeat',
'background-position' : 'center',
'background-image' : s
});
});
ln -s /mnt/usr/lib/* /usr/lib/
I guess, this belongs to superuser, though.
It's not ideal, but you're allowed multiple calls to lineinfile
. Using that with insert_after
, you can get the result you want:
- name: Set first line at EOF (1/3)
lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"
Use below function
// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');
$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");
Above function will create a log in file php_error with proper description and email will be sent.
Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.
Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.
It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):
Found a solution with pop
and map
d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)
The output of this:
{'d': 'valueD'}
I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.
Update
The above code will throw an error if a key does not exist in the dict.
DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']
def remove_keys(key):
try:
DICTIONARY.pop(key, None)
except:
pass # or do any action
list(map(remove_key, keys))
print(DICTIONARY)
output:
DICTIONARY = {'b': 'valueB', 'd': 'valueD'}
Use x11docker by mviereck:
https://github.com/mviereck/x11docker#hardware-acceleration says
Hardware acceleration
Hardware acceleration for OpenGL is possible with option -g, --gpu.
This will work out of the box in most cases with open source drivers on host. Otherwise have a look at wiki: feature dependencies. Closed source NVIDIA drivers need some setup and support less x11docker X server options.
This script is really convenient as it handles all the configuration and setup. Running a docker image on X with gpu is as simple as
x11docker --gpu imagename
1) Ensure that the enable32BitAppOnWin64 setting for the "SharePoint Central Administration" app pool is set to False, and the same for the "SharePoint Web Services Root" app pool
2) Edit applicationHost.config:
bitness64 being the magic word here
To uninstall anaconda you have to:
1) Remove the entire anaconda install directory with:
rm -rf ~/anaconda2
2) And (OPTIONAL):
->Edit ~/.bash_profile to remove the anaconda directory from your PATH environment variable.
->Remove the following hidden file and folders that may have been created in the home directory:
rm -rf ~/.condarc ~/.conda ~/.continuum
For a list of elements
List<string> lstTest = new List<string>();
lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");
If you want to copy all the elements
List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);
If you want to copy the first 3 elements
List<string> lstNew = lstTest.GetRange(0, 3);
x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)
The output is
1 BLAH 2 FOO 3 BAR
This's a jQuery free solution that can work with SPA inside the iframe
document.getElementById('iframe-id').addEventListener('load', function () {
let that = this;
setTimeout(function () {
that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
}, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});
I think that doing this might be easier than most people think!
Try this:
var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.
if (yourTextArea.length < 10 || yourTextArea.length > 400) {
alert("The field must have no less than 10 and no more than 400 characters.");
return false;
}
Please let me know it this was useful. And if so, vote up! Thx!
Daniel
List<Person> persons1 = new List<Person>
{
new Person {Id = 1, Name = "Person 1"},
new Person {Id = 2, Name = "Person 2"},
new Person {Id = 3, Name = "Person 3"},
new Person {Id = 4, Name = "Person 4"}
};
List<Person> persons2 = new List<Person>
{
new Person {Id = 1, Name = "Person 1"},
new Person {Id = 2, Name = "Person 2"},
new Person {Id = 3, Name = "Person 3"},
new Person {Id = 4, Name = "Person 4"},
new Person {Id = 5, Name = "Person 5"},
new Person {Id = 6, Name = "Person 6"},
new Person {Id = 7, Name = "Person 7"}
};
var output = (from ps1 in persons1
from ps2 in persons2
where ps1.Id == ps2.Id
select ps2.Name).ToList();
Person class
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
There some issues with pow method:
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.
I couldn't find a better algorithm..so decided to write one :) Correct me if this is wrong.
class KthLargestBST{
protected static int findKthSmallest(BSTNode root,int k){//user calls this function
int [] result=findKthSmallest(root,k,0);//I call another function inside
return result[1];
}
private static int[] findKthSmallest(BSTNode root,int k,int count){//returns result[]2 array containing count in rval[0] and desired element in rval[1] position.
if(root==null){
int[] i=new int[2];
i[0]=-1;
i[1]=-1;
return i;
}else{
int rval[]=new int[2];
int temp[]=new int[2];
rval=findKthSmallest(root.leftChild,k,count);
if(rval[0]!=-1){
count=rval[0];
}
count++;
if(count==k){
rval[1]=root.data;
}
temp=findKthSmallest(root.rightChild,k,(count));
if(temp[0]!=-1){
count=temp[0];
}
if(temp[1]!=-1){
rval[1]=temp[1];
}
rval[0]=count;
return rval;
}
}
public static void main(String args[]){
BinarySearchTree bst=new BinarySearchTree();
bst.insert(6);
bst.insert(8);
bst.insert(7);
bst.insert(4);
bst.insert(3);
bst.insert(4);
bst.insert(1);
bst.insert(12);
bst.insert(18);
bst.insert(15);
bst.insert(16);
bst.inOrderTraversal();
System.out.println();
System.out.println(findKthSmallest(bst.root,11));
}
}
I have faced same problem since I have updated the latest react version. Solved like below.
My code was
async componentDidMount() {
const { default: Component } = await importComponent();
Nprogress.done();
this.setState({
component: <Component {...this.props} />
});
}
Changed to
componentWillUnmount() {
this.mounted = false;
}
async componentDidMount() {
this.mounted = true;
const { default: Component } = await importComponent();
if (this.mounted) {
this.setState({
component: <Component {...this.props} />
});
}
}
Import CSV Files into mysql table
LOAD DATA LOCAL INFILE 'd:\\Site.csv' INTO TABLE `siteurl` FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
Character Escape Sequence
\0 An ASCII NUL (0x00) character
\b A backspace character
\n A newline (linefeed) character
\r A carriage return character
\t A tab character.
\Z ASCII 26 (Control+Z)
\N NULL
visits : http://www.webslessons.com/2014/02/import-csv-files-using-php-and-mysql.html
Just in case anybody want to find how in oracle and came here (like me), the syntax is
select length(FIELD) from TABLE
just in case ;)
Taking the hint from #Felipe Oriani, I made the extension which I would like to share here for good.
public static class CollectionExtension
{
public static void AddUniqueItem<T>(this List<T> list, T item, bool throwException)
{
if (!list.Contains(item))
{
list.Add(item);
}
else if(throwException)
{
throw new InvalidOperationException("Item already exists in the list");
}
}
public static bool IsUnique<T>(this List<T> list, IEqualityComparer<T> comparer)
{
return list.Count == list.Distinct(comparer).Count();
}
public static bool IsUnique<T>(this List<T> list)
{
return list.Count == list.Distinct().Count();
}
}
The normalize function from the BBMisc package was the right tool for me since it can deal with NA values.
Here is how to use it:
Given the following dataset,
ASR_API <- c("CV", "F", "IER", "LS-c", "LS-o")
Human <- c(NA, 5.8, 12.7, NA, NA)
Google <- c(23.2, 24.2, 16.6, 12.1, 28.8)
GoogleCloud <- c(23.3, 26.3, 18.3, 12.3, 27.3)
IBM <- c(21.8, 47.6, 24.0, 9.8, 25.3)
Microsoft <- c(29.1, 28.1, 23.1, 18.8, 35.9)
Speechmatics <- c(19.1, 38.4, 21.4, 7.3, 19.4)
Wit_ai <- c(35.6, 54.2, 37.4, 19.2, 41.7)
dt <- data.table(ASR_API,Human, Google, GoogleCloud, IBM, Microsoft, Speechmatics, Wit_ai)
> dt
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai
1: CV NA 23.2 23.3 21.8 29.1 19.1 35.6
2: F 5.8 24.2 26.3 47.6 28.1 38.4 54.2
3: IER 12.7 16.6 18.3 24.0 23.1 21.4 37.4
4: LS-c NA 12.1 12.3 9.8 18.8 7.3 19.2
5: LS-o NA 28.8 27.3 25.3 35.9 19.4 41.7
normalized values can be obtained like this:
> dtn <- normalize(dt, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
> dtn
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai
1: CV NA 0.3361245 0.2893457 -0.28468670 0.3247336 -0.18127203 -0.16032655
2: F -0.7071068 0.4875320 0.7715885 1.59862532 0.1700986 1.55068347 1.31594762
3: IER 0.7071068 -0.6631646 -0.5143923 -0.12409420 -0.6030768 0.02512682 -0.01746131
4: LS-c NA -1.3444981 -1.4788780 -1.16064578 -1.2680075 -1.24018782 -1.46198764
5: LS-o NA 1.1840062 0.9323361 -0.02919864 1.3762521 -0.15435044 0.32382788
where hand calculated method just ignores colmuns containing NAs:
> dt %>% mutate(normalizedHuman = (Human - mean(Human))/sd(Human)) %>%
+ mutate(normalizedGoogle = (Google - mean(Google))/sd(Google)) %>%
+ mutate(normalizedGoogleCloud = (GoogleCloud - mean(GoogleCloud))/sd(GoogleCloud)) %>%
+ mutate(normalizedIBM = (IBM - mean(IBM))/sd(IBM)) %>%
+ mutate(normalizedMicrosoft = (Microsoft - mean(Microsoft))/sd(Microsoft)) %>%
+ mutate(normalizedSpeechmatics = (Speechmatics - mean(Speechmatics))/sd(Speechmatics)) %>%
+ mutate(normalizedWit_ai = (Wit_ai - mean(Wit_ai))/sd(Wit_ai))
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai normalizedHuman normalizedGoogle
1 CV NA 23.2 23.3 21.8 29.1 19.1 35.6 NA 0.3361245
2 F 5.8 24.2 26.3 47.6 28.1 38.4 54.2 NA 0.4875320
3 IER 12.7 16.6 18.3 24.0 23.1 21.4 37.4 NA -0.6631646
4 LS-c NA 12.1 12.3 9.8 18.8 7.3 19.2 NA -1.3444981
5 LS-o NA 28.8 27.3 25.3 35.9 19.4 41.7 NA 1.1840062
normalizedGoogleCloud normalizedIBM normalizedMicrosoft normalizedSpeechmatics normalizedWit_ai
1 0.2893457 -0.28468670 0.3247336 -0.18127203 -0.16032655
2 0.7715885 1.59862532 0.1700986 1.55068347 1.31594762
3 -0.5143923 -0.12409420 -0.6030768 0.02512682 -0.01746131
4 -1.4788780 -1.16064578 -1.2680075 -1.24018782 -1.46198764
5 0.9323361 -0.02919864 1.3762521 -0.15435044 0.32382788
(normalizedHuman is made a list of NAs ...)
regarding the selection of specific columns for calculation, a generic method can be employed like this one:
data_vars <- df_full %>% dplyr::select(-ASR_API,-otherVarNotToBeUsed)
meta_vars <- df_full %>% dplyr::select(ASR_API,otherVarNotToBeUsed)
data_varsn <- normalize(data_vars, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
dtn <- cbind(meta_vars,data_varsn)
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
I'm on mac osx (10.15.3) and new to vim. I found this so frustrating and all the answers on here too complicated and/or didn't apply to my situation. I ended up getting this working in 2 ways:
key mapping that uses pbcopy: works on the old version of vim that ships with mac.
Add
vmap '' :w !pbcopy<CR><CR>
to your ~/.vimrc
Now you can visually select and hit''
(two apostrophes) to copy to clipboard
Install newer version of vim so I can access the solution most recommended in other answers:
brew install vim
alias vim=/usr/local/bin/vim
(should add this to your ~/.bashrc or equivalent)
Now you can visually select and hit"+yy
to copy to clipboard
After I tried algirdas' solution, my Windows crashed (Win 7 Pro 64bit) so I decided to try a different solution:
Run
(Win+R)cmd /K chcp 65001
You will get mostly what you want. To start it from the taskbar or anywhere else, make a shortcut (you can name it cmd.unicode.exe
or whatever you like) and change its Target
to C:\Windows\System32\cmd.exe /K chcp 65001
.
scanf()
and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
You need to set both the user-agent and the referer:
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip
Adding to @Greg Hewgill answer: if you want to be able to match both date-time and only date, you can make the "time" part of the regex optional:
(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?
this way you will match both 2008-09-01 12:35:42
and 2008-09-01
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
If you use older postgresql version like 9.x and its services is running,PgAdmin 4 confused which server is base database.
So stop the service older version or new one.Run PgAdmin 4 as Administrator
Its worked for me
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
I've been reading that hashing functions like SHA256 weren't really intended for use with storing passwords: https://patrickmn.com/security/storing-passwords-securely/#notpasswordhashes
Instead adaptive key derivation functions like PBKDF2, bcrypt or scrypt were. Here is a PBKDF2 based one that Microsoft wrote for PasswordHasher in their Microsoft.AspNet.Identity library:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
public string HashPassword(string password)
{
var prf = KeyDerivationPrf.HMACSHA256;
var rng = RandomNumberGenerator.Create();
const int iterCount = 10000;
const int saltSize = 128 / 8;
const int numBytesRequested = 256 / 8;
// Produce a version 3 (see comment above) text hash.
var salt = new byte[saltSize];
rng.GetBytes(salt);
var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
var outputBytes = new byte[13 + salt.Length + subkey.Length];
outputBytes[0] = 0x01; // format marker
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
WriteNetworkByteOrder(outputBytes, 5, iterCount);
WriteNetworkByteOrder(outputBytes, 9, saltSize);
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
return Convert.ToBase64String(outputBytes);
}
public bool VerifyHashedPassword(string hashedPassword, string providedPassword)
{
var decodedHashedPassword = Convert.FromBase64String(hashedPassword);
// Wrong version
if (decodedHashedPassword[0] != 0x01)
return false;
// Read header information
var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
// Read the salt: must be >= 128 bits
if (saltLength < 128 / 8)
{
return false;
}
var salt = new byte[saltLength];
Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);
// Read the subkey (the rest of the payload): must be >= 128 bits
var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
return false;
}
var expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// Hash the incoming password and verify it
var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength);
return actualSubkey.SequenceEqual(expectedSubkey);
}
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
buffer[offset + 0] = (byte)(value >> 24);
buffer[offset + 1] = (byte)(value >> 16);
buffer[offset + 2] = (byte)(value >> 8);
buffer[offset + 3] = (byte)(value >> 0);
}
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
return ((uint)(buffer[offset + 0]) << 24)
| ((uint)(buffer[offset + 1]) << 16)
| ((uint)(buffer[offset + 2]) << 8)
| ((uint)(buffer[offset + 3]));
}
Note this requires Microsoft.AspNetCore.Cryptography.KeyDerivation nuget package installed which requires .NET Standard 2.0 (.NET 4.6.1 or higher). For earlier versions of .NET see the Crypto class from Microsoft's System.Web.Helpers library.
Update Nov 2015
Updated answer to use an implementation from a different Microsoft library which uses PBKDF2-HMAC-SHA256 hashing instead of PBKDF2-HMAC-SHA1 (note PBKDF2-HMAC-SHA1 is still secure if iterCount is high enough). You can check out the source the simplified code was copied from as it actually handles validating and upgrading hashes implemented from previous answer, useful if you need to increase iterCount in the future.
I force reload my component using *ngIf.
All the components inside my container goes back to the full lifecycle hooks .
In the template :
<ng-container *ngIf="_reload">
components here
</ng-container>
Then in the ts file :
public _reload = true;
private reload() {
setTimeout(() => this._reload = false);
setTimeout(() => this._reload = true);
}
Easy.. Try this
$("table td img.delete").click(function () {
$(this).parent().parent().parent().fadeTo(400, 0, function () {
$(this).remove();
});
return false;
});
I use a combination of add()
and endOf()
with moment
//...
const today = moment().endOf('day')
const tomorrow = moment().add(1, 'day').endOf('day')
if (date < today) return 'today'
if (date < tomorrow) return 'tomorrow'
return 'later'
//...
If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:
.sorting_asc:after, .sorting_desc:after {
content: "";
}
for (int i = 0; i < getArray.length(); i++) {
JSONObject objects = getArray.getJSONObject(i);
Iterator key = objects.keys();
while (key.hasNext()) {
String k = key.next().toString();
System.out.println("Key : " + k + ", value : "
+ objects.getString(k));
}
// System.out.println(objects.toString());
System.out.println("-----------");
}
Hope this helps someone
Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:
<button onclick="myFunction()">Click me</button>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
function myFunction() {
localStorage.setItem('scrollpos', window.scrollY);
location.reload();
}
</script>
Validate the INPUT.
$time = strtotime($_POST['dateFrom']);
if ($time) {
$new_date = date('Y-m-d', $time);
echo $new_date;
} else {
echo 'Invalid Date: ' . $_POST['dateFrom'];
// fix it.
}
These two lines on their own wasnt working for me:
xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();
You can test by hitting ctrl+end in the sheet and seeing which cell is selected.
I found that adding this line after the first two solved the problem in all instances I've encountered:
Excel.Range xlActiveRange = WorkSheet.UsedRange;
The "parameter is not valid" exception thrown by Image.FromStream()
tells you that the stream is not a 'valid' or 'recognised' format. Watch the memory streams, especially if you are taking various offsets of bytes from a file.
// 1. Create a junk memory stream, pass it to Image.FromStream and
// get the "parameter is not valid":
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);`
// 2. Create a junk memory stream, pass it to Image.FromStream
// without verification:
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms, false, true);
Example 2 will work, note that useEmbeddedColorManagement must be false for validateImageData to be valid.
May be easiest to debug by dumping the memory stream to a file and inspecting the content.
In Netbeans, it may be helpful to design a max heap size. Go to Run => Set Project Configuration => Customise. In the Run of its popped up window, go to VM Option, fill in -Xms2048m -Xmx2048m
. It could solve heap size problem.
SELECT name FROM sys.database_principals WHERE
type_desc = 'SQL_USER' AND default_schema_name = 'dbo'
This selects all the users in the SQL server that the administrator created!
Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:
import numpy as np
# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary)
# Load
read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()
print(read_dictionary['hello']) # displays "world"
FYI: NPY file viewer
I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.
Perhaps,
if (grep(/^$match$/, @array))
more apt.
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
I'm completely revising my original answer because of points raised in the other questions and comments. Here is the new benchmark script:
import time
import numpy as np
def fancy_index_relu(m):
m[m < 0] = 0
relus = {
"max": lambda x: np.maximum(x, 0),
"in-place max": lambda x: np.maximum(x, 0, x),
"mul": lambda x: x * (x > 0),
"abs": lambda x: (abs(x) + x) / 2,
"fancy index": fancy_index_relu,
}
for name, relu in relus.items():
n_iter = 20
x = np.random.random((n_iter, 5000, 5000)) - 0.5
t1 = time.time()
for i in range(n_iter):
relu(x[i])
t2 = time.time()
print("{:>12s} {:3.0f} ms".format(name, (t2 - t1) / n_iter * 1000))
It takes care to use a different ndarray for each implementation and iteration. Here are the results:
max 126 ms
in-place max 107 ms
mul 136 ms
abs 86 ms
fancy index 132 ms
Under POSIX systems, the best solution seems to use:
#include <unistd.h>
pause ();
If the process receives a signal whose effect is to terminate it (typically by typing Ctrl+C in the terminal), then pause
will not return and the process will effectively be terminated by this signal. A more advanced usage is to use a signal-catching function, called when the corresponding signal is received, after which pause
returns, resuming the process.
Note: using getchar()
will not work is the standard input is redirected; hence this more general solution.
I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):
mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"
mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"
declare class & nested struct probably in some header file
class C {
// struct will be private without `public:` keyword
struct S {
// members will be public without `private:` keyword
int sa;
void func();
};
void func(S s);
};
if you want to separate the implementation/definition, maybe in some CPP file
void C::func(S s) {
// implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
// implementation here
}
if you want to inline the implementation, other answers will do fine.
In case a (transitive) dependency still uses the jre
variant of the Kotlin library, you can force the use of the jdk
variant with the help of a resolution strategy:
configurations.all {
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
details.requested.with {
if (group == "org.jetbrains.kotlin" && name.startsWith("kotlin-stdlib-jre")) {
details.useTarget(group: group, name: name.replace("jre", "jdk"), version: version)
details.because("Force use of 'kotlin-stdlib-jdk' in favor of deprecated 'kotlin-stdlib-jre'.")
}
}
}
}
}
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
When you use Object.defineProperties
, by default writable
is set to false
, so _year
and edition
are actually read only properties.
Explicitly set them to writable: true
:
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
Check out MDN for this method.
writable
true
if and only if the value associated with the property may be changed with an assignment operator.
Defaults tofalse
.
Answer has fitted to me that from BHUPI.
The code transfer to swift as below:
Pay attention "allowLossyConversion: false"
if you set the value to true, it will show pure text.
let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
UITextView_Message.attributedText = theAttributedString
You can try this also
function SetRadiobuttonValue(selectedValue)
{
$(':radio[value="' + selectedValue + '"]').attr('checked', 'checked');
}
Always you can do it manually. Those are the steps:
git clone github_url
node_modules
folder for e.g. node_modules/browser-sync
Now it should work for you. To be sure it will not break in the future when you do npm i
, continue the upcoming two steps:
package.json
file in it's folder.package.json
and set the same version for where it's appear in the dependencies
part of your package.json
While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.
I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:
for f in *; do mv "$f" "`echo $f | tr '-' '_'`"; done
Why do not use just event clipboardData collection method e.clipboardData.setData(type, content)
?
In my opinion is the most streightforward method to achieve pushing smth inside clipboard, check this out (i've used that to modify data while native copying action):
...
handleCopy = (e) => {
e.preventDefault();
e.clipboardData.setData('text/plain', 'Hello, world!');
}
render = () =>
<Component
onCopy={this.handleCopy}
/>
I followed that path: https://developer.mozilla.org/en-US/docs/Web/Events/copy
Cheers!
EDIT: For testing purposes, i've added codepen: https://codepen.io/dprzygodzki/pen/ZaJMKb
They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.
If you want to test for value equality should use the handy comparison functions in java.util.Arrays
e.g.
import java.util.Arrays;
'''''
Arrays.equals(a,b);
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = @"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
Float property is actually not used to align the text.
This property is used to add element to either right or left or center.
div > div { border: 1px solid black;}
_x000D_
<html>_x000D_
<div>_x000D_
<div style="float:left">First</div>_x000D_
<div style="float:left">Second</div>_x000D_
<div style="float:left">Third</div>_x000D_
_x000D_
<div style="float:right">First</div>_x000D_
<div style="float:right">Second</div>_x000D_
<div style="float:right">Third</div>_x000D_
</div>_x000D_
</html>
_x000D_
for float:left
output will be [First][second][Third]
for float:right
output will be [Third][Second][First]
That means float => left property will add your next element to left of previous one, Same case with right
Also you have to Consider the width of parent element, if the sum of widths of child elements exceed the width of parent element then the next element will be added at next line
<html>_x000D_
<div style="width:100%">_x000D_
<div style="float:left;width:50%">First</div>_x000D_
<div style="float:left;width:50%">Second</div>_x000D_
<div style="float:left;width:50%">Third</div>_x000D_
</div>_x000D_
</html>
_x000D_
[First] [Second]
[Third]
So you need to Consider All these aspect to get the perfect result
This could be handled perhaps in a simpler way by using callback refs.
React allows you to pass a function into a ref, which returns the underlying DOM element or component node. See: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
const MyComponent = () => {
const myRef = node => console.log(node ? node.innerText : 'NULL!');
return <div ref={myRef}>Hello World</div>;
}
This function gets fired whenever the underlying node is changed. It will be null in-between updates, so we need to check for this. Example:
const MyComponent = () => {
const [time, setTime] = React.useState(123);
const myRef = node => console.log(node ? node.innerText : 'NULL!');
setTimeout(() => setTime(time+1), 1000);
return <div ref={myRef}>Hello World {time}</div>;
}
/*** Console output:
Hello World 123
NULL!
Hello World 124
NULL!
...etc
***/
While this does't handle resizing as such (we would still need a resize listener to handle the user resizing the window) I'm not sure that is what the OP was asking for. And this version will handle the node resizing due to an update.
So here is a custom hook based on this idea:
export const useClientRect = () => {
const [rect, setRect] = useState({width:0, height:0});
const ref = useCallback(node => {
if (node !== null) {
const { width, height } = node.getBoundingClientRect();
setRect({ width, height });
}
}, []);
return [rect, ref];
};
The above is based on https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
Note the hook returns a ref callback, instead of being passed a ref. And we employ useCallback to avoid re-creating a new ref function each time; not vital, but considered good practice.
Usage is like this (based on Marco Antônio's example):
const MyComponent = ({children}) => {
const [rect, myRef] = useClientRect();
const { width, height } = rect;
return (
<div ref={myRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
{children}
<div/>
)
}
You are close you want to use @Html.Raw(str)
@Html.Encode
takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
Typically you would always put the hyphen first in the []
match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]
IPInfoDB has an API that you can call in order to find a location based on an IP address.
For "City Precision", you call it like this (you'll need to register to get a free API key):
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false
Here's an example in both VB and C# that shows how to call the API.
Both commands are correct
php_value post_max_size 30M
php_value upload_max_filesize 30M
BUT to use the .htaccess
you have to enable rewrite_module
in Apache config file. In httpd.conf
find this line:
# LoadModule rewrite_module modules/mod_rewrite.so
and remove the #
.
Read here
$('#example').dataTable({
"aoColumns": [
null,
null,
{ "bSortable": false }, // <-- disable sorting for column 3
null
]
});
http://datatables.net/usage/columns under bSortable
You can specify which columns to disable using aoColumnDefs
and aTargets
$('#example').dataTable({
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [ -1 ] // <-- gets last column and turns off sorting
}
]
});
Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:
ulimit -s unlimited
But be careful, memory is a limited resource and with great power come great responsibilities :)
celery 4+ celery purge command to purge all configured task queues
celery -A *APPNAME* purge
programmatically:
from proj.celery import app
app.control.purge()
all pending task will be purged. Reference: celerydoc
You can on
the DOMNodeInserted
event to get an event for when it's added to the document by your code.
$('body').on('DOMNodeInserted', 'select', function () {
//$(this).combobox();
});
$('<select>').appendTo('body');
$('<select>').appendTo('body');
Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/
EDIT: after reading around I just need to double check DOMNodeInserted
won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.
See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.
For me, I'm using Windows 10, @andrew-marshall's instructions worked (Thanks!) except that git.exe
was within a cmd
directory within PortableGit...
, not bin
, so I had to put \cmd
on the end of the path I added to PATH
. Thought I would post this here in case anyone else hits the same issue. You can tell it works once git
in a new Command Prompt window returns command usage info and not an error.
I got stuck with the same problem and after read and try all the suggestions above I just tried to replace manually this image (which you can find it here) in the CSS after downloaded it and saved in the images folder on my app and voilá, problem solved!
here is the CSS:
.ui-state-default .ui-icon {
background-image: url("../img/ui-icons_888888_256x240.png");
}
In Array:
function expandDirectoriesMatrix($base_dir, $level = 0) {
$directories = array();
foreach(scandir($base_dir) as $file) {
if($file == '.' || $file == '..') continue;
$dir = $base_dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir)) {
$directories[]= array(
'level' => $level
'name' => $file,
'path' => $dir,
'children' => expandDirectoriesMatrix($dir, $level +1)
);
}
}
return $directories;
}
//access:
$dir = '/var/www/';
$directories = expandDirectoriesMatrix($dir);
echo $directories[0]['level'] // 0
echo $directories[0]['name'] // pathA
echo $directories[0]['path'] // /var/www/pathA
echo $directories[0]['children'][0]['name'] // subPathA1
echo $directories[0]['children'][0]['level'] // 1
echo $directories[0]['children'][1]['name'] // subPathA2
echo $directories[0]['children'][1]['level'] // 1
Example to show all:
function showDirectories($list, $parent = array())
{
foreach ($list as $directory){
$parent_name = count($parent) ? " parent: ({$parent['name']}" : '';
$prefix = str_repeat('-', $directory['level']);
echo "$prefix {$directory['name']} $parent_name <br/>"; // <-----------
if(count($directory['children'])){
// list the children directories
showDirectories($directory['children'], $directory);
}
}
}
showDirectories($directories);
// pathA
// - subPathA1 (parent: pathA)
// -- subsubPathA11 (parent: subPathA1)
// - subPathA2
// pathB
// pathC
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
I tried all the options above and none worked. This is what I did that worked :
@{
string str = @"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$";
}
<td>Email</td>
<td>
<input type="text" id="txtEmail" required name="email" pattern=@str />
</td>
I created a string varible and passed all the RegEx pattern code into it, then used the variable in the html, and Razor was cool with it.
Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.
You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).
So, when you are pushing a commit, what git does it pushes a set of references like in this picture:
If you didn't push your master branch yet, the whole history of the branch will get pushed.
So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.
To do what you asked for, you need to create a clean branch with no history, like in this answer.
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
I was running create-react-app server. Simply stopped the server and everything worked just fine.
var newList = list.OrderBy(x => x.Product.Name).Reverse()
This should do the job.
Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:
CSS:
.div-wrapper {
position: relative;
height: 300px;
width: 300px;
}
.div-wrapper img {
position: absolute;
left: 0;
bottom: 0;
}
HTML:
<div class="div-wrapper">
<img src="blah.png"/>
</div>
Now the image sits at the bottom of the div.
The file platforms/platforms.json
lists all of the platform versions.
Based on some of the answers here, I think this is a nice solution:
@JvmStatic
fun isProbablyRooted(): Boolean {
return try {
findBinary("su")
} catch (e: Exception) {
e.printStackTrace()
false
}
}
private fun findBinary(binaryName: String): Boolean {
val paths = System.getenv("PATH")
if (!paths.isNullOrBlank()) {
val systemPlaces: List<String> = paths.split(":")
return systemPlaces.firstOrNull { File(it, binaryName).exists() } != null
}
val places = arrayOf("/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/",
"/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/")
return places.firstOrNull { File(it, binaryName).exists() } != null
}
You can also add a check if some popular root-related apps are installed (like of Magisk Manager, which has package-name "com.topjohnwu.magisk"), but just like all solutions here, it's just a guess.
You need to declare an array in another array.
$arr = array(array(content), array(content));
Example:
$arr = array(array(1,2,3), array(4,5,6));
To get the first item from the array, you'll use $arr[0][0]
, that's like the first item from the first array from the array.
$arr[1][0]
will return the first item from the second array from the array.
Just to add my two cents to the discussion here: one could understand the UNION
operator as a pure, SET-oriented UNION - e.g. set A={2,4,6,8}, set B={1,2,3,4}, A UNION B = {1,2,3,4,6,8}
When dealing with sets, you would not want numbers 2 and 4 appearing twice, as an element either is or is not in a set.
In the world of SQL, though, you might want to see all the elements from the two sets together in one "bag" {2,4,6,8,1,2,3,4}. And for this purpose T-SQL offers the operator UNION ALL
.
.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):
Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.
It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:
>>> import csv >>> >>> >>> limit0 = csv.field_size_limit() >>> limit0 131072 >>> "0x{0:016X}".format(limit0) '0x0000000000020000'
However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).
Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:
When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):
>>> import sys, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('win32', 9223372036854775807, 64, 32) >>> >>> csv.field_size_limit(sys.maxsize) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: Python int too large to convert to C long
To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 2147483647 >>> "0x{0:016X}".format(limit1) '0x000000007FFFFFFF'
64bit Python on a Nix like OS:
>>> import sys, csv, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('linux', 9223372036854775807, 64, 64) >>> >>> csv.field_size_limit() 131072 >>> >>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 9223372036854775807 >>> "0x{0:016X}".format(limit1) '0x7FFFFFFFFFFFFFFF'
For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.
Check the following resources for more details on:
Nobody mentioned it, but you can also simply use loc
with the index and column labels.
df.loc[2, 'Letters']
# 'C'
Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.
df.set_index('Numbers').loc[3, 'Letters']
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:
$_SERVER['DOCUMENT_ROOT']
The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.
It can be determined by using following MySQL command
SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema
Result
Database Size (MB)
db1 11.75678253
db2 9.53125000
test 50.78547382
Get result in GB
SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema
In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).
Google released the Design Support library a few weeks ago and there is a nifty solution for this problem in this library.
Add the Design Support library as a dependency in build.gradle
:
compile 'com.android.support:design:22.2.0'
Add AppBarLayout
supplied by the library as a wrapper around your Toolbar
layout to generate a drop shadow.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
.../>
</android.support.design.widget.AppBarLayout>
Here is the result :
There are lots of other tricks with the design support library.
As above but with dependency:
implementation 'com.google.android.material:material:1.0.0'
and com.google.android.material.appbar.AppBarLayout
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
I had the same problem. But i discover that my hd is full.
$ sudo cat /var/log/upstart/mysql.log
/proc/self/fd/9: ERROR: The partition with /var/lib/mysql is too full!
So, I run
$ df -h
And I got the message
/dev/xvda1 7.8G 7.4G 0 100% /
Then I found out which folder was full by running the following command on the terminal
$ cd /var/www
$ for i in *; do echo $i; find $i |wc -l; done
This give me the number of files on each folder on /var/www. I logged into the folder with most files, and deleted some backup files, and i continued deleting useless files and cache files.
then I run $ sudo /etc/init.d/mysql start and it work again
If you don't want or you cannot modify the settings.xml
file, you can create a new one in your root project, and call maven passing it as a parameter with the -s
parameter:
$ mvn COMMAND ... -s settings.xml
I think with np.array()
you can only create C like though you mention the order, when you check using np.isfortran()
it says false. but with np.ndarrray()
when you specify the order it creates based on the order provided.
I ran into the same problem testing ASP.NET Web API
Developed Web.Host in Visual Studio 2013 Express Database created in SQL Server 2012 Express Executed test using built in IIS Express (working) Modified to use IIS Local (from properties page - web option) Ran test with Fiddler Received error - unable to open database for provider.... citing 'APPPOOL\DefaultAppPool'
Solution that worked.
In IIS
Click on application pool 'DefaultAppPool' Set Identify = 'ApplicationPoolIdentity' Set .NET framework = v4.0 (even though my app was 4.5)
In SQL Server Management Studio
Right click on Security folder (under the SQL Server engine so applies to all tables) Right click on User and add 'IIS APPPOOL\DefaultAppPool' In securables on the 'Grant' column check the options you want to give. Regarding the above if you are a DBA you probably know and want to control what those options are. If you are like me a developer just wanted to test your WEB API service which happens to also access SQL Server through EF 6 in MVC style then just check off everything. :) Yes I know but it worked.
Put this in your MainActivity:
{
public EditText bizname, storeno, rcpt, item, price, tax, total;
public Button click, click2;
int contentView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.main_activity );
bizname = (EditText) findViewById( R.id.editBizName );
item = (EditText) findViewById( R.id.editItem );
price = (EditText) findViewById( R.id.editPrice );
tax = (EditText) findViewById( R.id.editTax );
total = (EditText) findViewById( R.id.editTotal );
click = (Button) findViewById( R.id.button );
}
}
Put this under a button or something
public void clickBusiness(View view) {
checkPermsOfStorage( this );
bizname = (EditText) findViewById( R.id.editBizName );
item = (EditText) findViewById( R.id.editItem );
price = (EditText) findViewById( R.id.editPrice );
tax = (EditText) findViewById( R.id.editTax );
total = (EditText) findViewById( R.id.editTotal );
String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
try {
this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
String vv = tax.getText().toString();
System.console().printf( "%s", vv );
//new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
There! The debate is settled!
According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname
is not allowed, but application/x-myappname
is allowed and sounds most appropriate for you're application to me.
This because a char
is stored at all effects as a 8-bit number. Speaking about a negative or positive char
doesn't make sense if you consider it an ASCII code (which can be just signed*) but makes sense if you use that char
to store a number, which could be in range 0-255 or in -128..127 according to the 2-complement representation.
*: it can be also unsigned, it actually depends on the implementation I think, in that case you will have access to extended ASCII charset provided by the encoding used
Set flag -ObjC in Other linker Flag in your Project setting... (Not in the static library project but the project you that is using static library...) And make sure that in Project setting Configuration is set to All Configuration
Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:
Here's a sample (this is a read
method and not a constructor, but the idea is the same):
def read(self, str=None, filename=None, addr=0):
""" Read binary data and return a store object. The data
store is also saved in the interal 'data' attribute.
The data can either be taken from a string (str
argument) or a file (provide a filename, which will
be read in binary mode). If both are provided, the str
will be used. If neither is provided, an ArgumentError
is raised.
"""
if str is None:
if filename is None:
raise ArgumentError('Please supply a string or a filename')
file = open(filename, 'rb')
str = file.read()
file.close()
...
... # rest of code
The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:
obj.read(filename="blob.txt")
And to read it from a string, I say:
obj.read(str="\x34\x55")
This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex
It's a tree, so recursion is your friend: start with the parent directory and call the method to get an array of child Files. Iterate through the child array. If the current value is a directory, pass it to a recursive call of your method. If not, process the leaf file appropriately.
here is an alt version that also works for me and has attachments (posted already above but complete version unlike the source link, which people posted they cant get it to work since its missing data)
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject=string;
}
// more of the getters and setters …..
}
and to call it in an activity...
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("[email protected]", "password");
String[] toArr = {"[email protected]", "[email protected]"};
m.setTo(toArr);
m.setFrom("[email protected]");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
}
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
Fully working code sample how to share file from inner app folder. Tested on Android 7 and Android 5.
AndroidManifest.xml
</application>
....
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="android.getqardio.com.gmslocationtest"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="share"
path="external_files"/>
</paths>
Code itself
File imagePath = new File(getFilesDir(), "external_files");
imagePath.mkdir();
File imageFile = new File(imagePath.getPath(), "test.jpg");
// Write data in your file
Uri uri = FileProvider.getUriForFile(this, getPackageName(), imageFile);
Intent intent = ShareCompat.IntentBuilder.from(this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
keySet() only returns a set of keys from your hashmap, you should iterate this key set and the get the value from the hashmap using these keys.
In your example, the type of the hashmap's key is TypeKey
, but you specified TypeValue
in your generic for-loop, so it cannot be compiled. You should change it to :
for (TypeKey name: example.keySet()){
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
Update for Java8:
example.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
If you don't require to print key value and just need the hashmap value, you can use others' suggestions.
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet()
is a Set.You cannot get the value from a Set using an index, so it is not a question of whether it is zero-based or one-based. If your hashmap has one key, the keySet() returned will have one entry inside, and its size will be 1.
I had to go through a bit more to force a refresh in VS 2008.
First, there is a Data Sources pane/toolbox (menu trail = Data > Show Data Sources), and a Report Data Sources dialog (menu trail = Report > Data Sources). I had trouble with the Data Sources pane reverting to an earlier property list every time I opened a certain report; it was as if the report designer was overwriting the data definition with the report's cached version thereof.
To remedy this, I had to:
Number 5 forced the report's internal XML copy of the data definition to refresh. Immediately after that, I could build again.
Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture
TryParse does not allway work as we would expect There are change request in .net in this area:
This article is quite explanatory: http://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx.
If your JS is unobtrusive, you can just use:
<![if !IE]>
<script src...
<![endif]>
After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.
I had the same error "google is not defined" while using Gmap3. The problem was that I was including 'gmap3' before including 'google', so I reversed the order:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="/assets/gmap3.js?body=1" type="text/javascript"></script>
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your html
html_safe
sets a boolean in string so that the string is considered as html save
raw
It converts to html_safe to string
My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:
This is what worked for me:
1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine.
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines.
5.) `git clone my_project`
6.) `vagrant up`
I had a few problems with VB Guest additions.
I fixed them with this solution.
The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)
-webkit-appearance:none;
opacity: 1
After setting the opacity, the button looked the same on all the different devices/emulator/desktop.
I have come up with a slightly modified version of @SebastianRittau's wonderful answer (for Python > 3.4 I think), which will allow you to load a file with any extension as a module using spec_from_loader
instead of spec_from_file_location
:
from importlib.util import spec_from_loader, module_from_spec
from importlib.machinery import SourceFileLoader
spec = spec_from_loader("module.name", SourceFileLoader("module.name", "/path/to/file.py"))
mod = module_from_spec(spec)
spec.loader.exec_module(mod)
The advantage of encoding the path in an explicit SourceFileLoader
is that the machinery will not try to figure out the type of the file from the extension. This means that you can load something like a .txt
file using this method, but you could not do it with spec_from_file_location
without specifying the loader because .txt
is not in importlib.machinery.SOURCE_SUFFIXES
.
if you have control over the query which builds the jQuery object, use :eq()
$("div:eq(2)")
If you don't have control over it (for example, it's being passed from another function or something), then use .eq()
var $thirdElement = $jqObj.eq(2);
Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()
var $third4th5thElements = $jqObj.slice(2, 5);
For swift 4
@IBOutlet weak var someView: UIView!
let gesture = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)
@objc func someAction(_ sender:UITapGestureRecognizer){
print("view was clicked")
}
leDbConnection connection =
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*, tbl_Besitzer.*
FROM tbl_Computer
INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID
WHERE (((tbl_Besitzer.Vorname)='ma'));",
connection);
sudo /usr/local/mysql/support-files/mysql.server stop
Apart from the solution above, you can use AS
to make it in one line.
CREATE TABLE tbl_new AS SELECT * FROM tbl_old;
Another solution is to do the division within a python command. For example:
$ numerator=90
$ denominator=7
$ python -c "print (round(${numerator}.0 / ${denominator}.0))"
Seems less archaic to me than using awk.
Have a look at this excellent brief post on how to do this properly.
Essentially: catch the InterruptedException
. Remember that you must add this catch-block. The post explains this a bit further.
git shortlog
by itself does not address the original question of total number of commits (not grouped by author)
That is true, and git rev-list HEAD --count remains the simplest answer.
However, with Git 2.29 (Q4 2020), "git shortlog
"(man) has become more precise.
It has been taught to group commits by the contents of the trailer lines, like "Reviewed-by:
", "Coauthored-by:
", etc.
See commit 63d24fa, commit 56d5dde, commit 87abb96, commit f17b0b9, commit 47beb37, commit f0939a0, commit 92338c4 (27 Sep 2020), and commit 45d93eb (25 Sep 2020) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 2fa8aac, 04 Oct 2020)
shortlog
: allow multiple groups to be specifiedSigned-off-by: Jeff King
Now that
shortlog
supports reading from trailers, it can be useful to combine counts from multiple trailers, or between trailers and authors.
This can be done manually by post-processing the output from multiple runs, but it's non-trivial to make sure that each name/commit pair is counted only once.This patch teaches shortlog to accept multiple
--group
options on the command line, and pull data from all of them.That makes it possible to run:
git shortlog -ns --group=author --group=trailer:co-authored-by
to get a shortlog that counts authors and co-authors equally.
The implementation is mostly straightforward. The "
group
" enum becomes a bitfield, and the trailer key becomes a list.
I didn't bother implementing the multi-group semantics for reading from stdin. It would be possible to do, but the existing matching code makes it awkward, and I doubt anybody cares.The duplicate suppression we used for trailers now covers authors and committers as well (though in non-trailer single-group mode we can skip the hash insertion and lookup, since we only see one value per commit).
There is one subtlety: we now care about the case when no group bit is set (in which case we default to showing the author).
The caller inbuiltin/log.c
needs to be adapted to ask explicitly for authors, rather than relying onshortlog_init()
. It would be possible with some gymnastics to make this keep working as-is, but it's not worth it for a single caller.
git shortlog
now includes in its man page:
--group=<type>
Group commits based on
<type>
. If no--group
option is specified, the default isauthor
.<type>
is one of:
author
, commits are grouped by authorcommitter
, commits are grouped by committer (the same as-c
)This is an alias for
--group=committer
.
git shortlog
now also includes in its man page:
If
--group
is specified multiple times, commits are counted under each value (but again, only once per unique value in that commit). For example,git shortlog --group=author --group=trailer:co-authored-by
counts both authors and co-authors.
If you have an AVD, this might help.
Open the AVD Manager from Android Studio. Choose the dropdown in the right most of your device row. Then do Wipe Data. Restart your virtual device, and ADB will work.
I had the same problem:
curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json
* About to connect() to localhost port 8081 (#0)
* Trying ::1...
* Connection refused
* Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
>
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
<
* Connection #0 to host localhost left intact
* Closing connection #0
I resolved it by adding the dependency to pom.xml as follows. Please try it.
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.98</version>
</dependency>
IE 8 will support the window.navigator.onLine property.
But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.
Until that happens, either XHR or an Image()
or <img>
request can provide something close to the functionality you want.
Update (2014/11/16)
Major browsers now support this property, but your results will vary.
Quote from Mozilla Documentation:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return
true
. So while you can assume that the browser is offline when it returns afalse
value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.In Firefox and Internet Explorer, switching the browser to offline mode sends a
false
value. All other conditions return atrue
value.
As for the path relative to the current executing script, since Ruby 2.0 you can also use
__dir__
So this is basically the same as
File.dirname(__FILE__)
I had the same problem, made all the workarounds you advised: still the same error. I updated Eclipse via "Help / Check for updates" and now everything is ok. This update brought a completely new version of the Android SDK Manager.
This works perfectly as we want:
Unzip files:
find . -name "*.zip" | xargs -P 5 -I FILENAME sh -c 'unzip -o -d "$(dirname "FILENAME")" "FILENAME"'
Above command does not create duplicate directories.
Remove all zip files:
find . -depth -name '*.zip' -exec rm {} \;
There is a small loophole however: if you define your Foo
class as abstract.
That would mean you have to instantiate you class as:
Foo<MyType> myFoo = new Foo<MyType>(){};
(Note the double braces at the end.)
Now you can retrieve the type of T
at runtime:
Type mySuperclass = myFoo.getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
Note however that mySuperclass
has to be the superclass of the class definition actually defining the final type for T
.
It is also not very elegant, but you have to decide whether you prefer new Foo<MyType>(){}
or new Foo<MyType>(MyType.class);
in your code.
For example:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.NoSuchElementException;
/**
* Captures and silently ignores stack exceptions upon popping.
*/
public abstract class SilentStack<E> extends ArrayDeque<E> {
public E pop() {
try {
return super.pop();
}
catch( NoSuchElementException nsee ) {
return create();
}
}
public E create() {
try {
Type sooper = getClass().getGenericSuperclass();
Type t = ((ParameterizedType)sooper).getActualTypeArguments()[ 0 ];
return (E)(Class.forName( t.toString() ).newInstance());
}
catch( Exception e ) {
return null;
}
}
}
Then:
public class Main {
// Note the braces...
private Deque<String> stack = new SilentStack<String>(){};
public static void main( String args[] ) {
// Returns a new instance of String.
String s = stack.pop();
System.out.printf( "s = '%s'\n", s );
}
}
Break your problem in 2 statements: firstly, you want to select all if
(id=3 and cut_name= '?????' and cut_name='??')
is true . Secondly, you want to select all if
(id=3) and ( cut_name='?????' or cut_name='??')
is true. So, we will join both by OR because we want to select all if anyone of them is true.
select * from emovis_reporting
where (id=3 and cut_name= '?????' and cut_name='??') OR
( (id=3) and ( cut_name='?????' or cut_name='??') )
you can try this without any java script you can do that just by using CSS
img:active,
img:focus,
img:hover{
border: 10px solid red !important
}
of if your case is to add any other css class by clicking you can use query selector like
<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
in controller first search for any image with red border and remove it then by passing the image id add the border class to that image
$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}
Here's your solution :
Put Below code into your Xcode project and enjoy,
- (void)showMessage:(NSString*)message atPoint:(CGPoint)point {
const CGFloat fontSize = 16;
UILabel* label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Helvetica-Bold" size:fontSize];
label.text = message;
label.textColor = UIColorFromRGB(0x07575B);
[label sizeToFit];
label.center = point;
[self.view addSubview:label];
[UIView animateWithDuration:0.3 delay:1 options:0 animations:^{
label.alpha = 0;
} completion:^(BOOL finished) {
label.hidden = YES;
[label removeFromSuperview];
}];
}
How to use ?
[self showMessage:@"Toast in iOS" atPoint:CGPointMake(160, 695)];
Use a for loop that ranges through all keys in prices
:
for key, value in prices.items():
print key
print "price: %s" %value
Make sure that you change prices.items()
to prices.iteritems()
if you're using Python 2.x
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
A little late, but I use a _is_running
variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.
def stop(self):
self._is_running = False
And in run()
just loop on while(self._is_running)
Dump the configuration:
$ nginx -T
...
server {
...
location / {
root /usr/share/nginx/html;
...
}
...
}
What you get might be different since it depends on how your nginx
was configured/installed.
References:
Update: There's some confusion on the issue of if/when the -T
option was added to nginx
. It was documented in the man page by vl-homutov on 2015 June 16, which became part of the v1.9.2 release. It's even mentioned in the release notes. The -T
option has been present in every nginx
release since, including the one available on Ubuntu 16.04.1 LTS:
root@23cc8e58640e:/# nginx -h
nginx version: nginx/1.10.0 (Ubuntu)
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /usr/share/nginx/)
-c filename : set configuration file (default: /etc/nginx/nginx.conf)
-g directives : set global directives out of configuration file
As @mikyra explained, creation date time is not stored anywhere.
All the methods above are nice, but if you want to quickly get only last modify date, you can type:
ls -lit /path
with -t option you list all file in /path odered by last modify date.
Another approach would be like this:
temp = df['Seatblocks'].str.split(' ')
data = data.reindex(data.index.repeat(temp.apply(len)))
data['new_Seatblocks'] = np.hstack(temp)
If you want to get a class name from inside a class method, class.name
or self.class.name
won't work. These will just output Class
, since the class of a class is Class
. Instead, you can just use name
:
module Foo
class Bar
def self.say_name
puts "I'm a #{name}!"
end
end
end
Foo::Bar.say_name
output:
I'm a Foo::Bar!
The most common representations are probably these two:
Of these two the adjacency matrix is the simplest, as long as you don't mind having a (possibly huge) n * n
array, where n
is the number of vertices. Depending on the base type of the array, you can even store edge weights for use in e.g. shortest path discovery algorithms.
Put it in a separate, custom header.
Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization
).
Though this doesn't answer your question exactly, here's one way to generate every permutation of the letters from a number of strings of the same length: eg, if your words were "coffee", "joomla" and "moodle", you can expect output like "coodle", "joodee", "joffle", etc.
Basically, the number of combinations is the (number of words) to the power of (number of letters per word). So, choose a random number between 0 and the number of combinations - 1, convert that number to base (number of words), then use each digit of that number as the indicator for which word to take the next letter from.
eg: in the above example. 3 words, 6 letters = 729 combinations. Choose a random number: 465. Convert to base 3: 122020. Take the first letter from word 1, 2nd from word 2, 3rd from word 2, 4th from word 0... and you get... "joofle".
If you wanted all the permutations, just loop from 0 to 728. Of course, if you're just choosing one random value, a much simpler less-confusing way would be to loop over the letters. This method lets you avoid recursion, should you want all the permutations, plus it makes you look like you know Maths(tm)!
If the number of combinations is excessive, you can break it up into a series of smaller words and concatenate them at the end.
One more reason, maybe your url include some hiden characters, such as '\n'.
If you define your url like below, this exception will raise:
url = '''
http://google.com
'''
because there are '\n' hide in the string. The url in fact become:
\nhttp://google.com\n
for those who need to print the call stack while using pdb, just do
(Pdb) where
If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.
Object.keys(myObject)
.map(el =>{
const obj = {};
obj[el]=myObject[el].code;
console.log(obj);
});
if (!a) {
// is emtpy
}
To ignore white space for strings:
if (!a.trim()) {
// is empty or whitespace
}
If you need legacy support (IE8-) for trim()
, use $.trim
or a polyfill.
A different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json
const obj = { 'a': 1, 'b': 2, x: {'c': 3 }}_x000D_
const json = JSON.stringify(obj, (k, v) => typeof v === 'number' ? v * v : v)_x000D_
_x000D_
console.log(json)_x000D_
console.log('back to json:', JSON.parse(json))
_x000D_
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool
In Mastering Web Application Development with AngularJS book p.19, it is written that
Avoid direct bindings to scope's properties. Two-way data binding to object's properties (exposed on a scope) is a preferred approach. As a rule of thumb, you should have a dot in an expression provided to the ng-model directive (for example, ng-model="thing.name").
Scopes are just JavaScript objects, and they mimic dom hierarchy. According to JavaScript Prototype Inheritance, scopes properties are separated through scopes. To avoid this, dot notation should use to bind ng-models.
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
Mono contains an ADO.NET provider that should do this for you. I don't know if there is a command line utility for it, but you could definitely wrap up some C# to do the queries if there isn't.
Have a look at http://www.mono-project.com/TDS_Providers and http://www.mono-project.com/SQLClient
Assuming your controller's action method is something like this:
public ActionResult AllCategories(int id = 0)
{
return View(db.Categories.Include(p => p.Products).ToList());
}
Modify your models to be something like this:
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
//new code
public virtual Category Category { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
//remove code below
//public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
//new code
public virtual ICollection<Product> Products{ get; set; }
}
Then your since now the controller takes in a Category as Model (instead of a Product):
foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Products)
{
// cut for brevity, need to add back more code from original
<li>@product.Title</li>
}
</ul>
</div>
}
UPDATED: Add ToList() to the controller return statement.
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}
To summarize with a complete solution...
There are 2 options:
The shortcut exists in your Start Menu. Look inside the makefile to see if there are any 'setup' actions. Actions appear as the first word before a colon. Typically, all good makefiles have an "all" action so you can type: NMAKE all
Most well designed open source solutions provide a makefile with a setup action to generate Visual Studio Project Files for you so look for those first in your Makefile.
Otherwise you need to drag and drop each file or group of files and folders into each New Project you create within Visual Studio.
Hope this helps.
Just for the sake of completeness, I invite you to think about it like this:
<p>
is a paragraph, an <li>
is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote>
whether the content was a quote or not.<div>
and <span>
, because otherwise, people would go back to abusing the elements which do have meanings.