At the end of the this answer to the question of how to think in Angular if you have a jQuery background, the top post from Josh David Miller summarizes:
Don't even use jQuery. Don't even include it. It will hold you back. And when you come to a problem that you think you know how to solve in jQuery already, before you reach for the
$
, try to think about how to do it within the confines the AngularJS. If you don't know, ask! 19 times out of 20, the best way to do it doesn't need jQuery and to try to solve it with jQuery results in more work for you.
Now if you want a grid with tons of features and options for customization, jQuery DataTables is one of the best. The Angular-only grids I have seen don't come close to what jQuery DataTables can do.
However, jQuery DataTables does not integrate well with AngularJS. (There have been various efforts, but none offer seamless integration.)
Perhaps that leaves a person with two options.
The first is to go with a pure Angular grid that is not as feature rich as DataTables. I agree with @Moonstom about getting fed up with the other Angular grids out there, and trNgGrid does look nice.
The second option is to say: this is one of those rare 1 out of 20 cases where you should use jQuery and go with the jQuery DataTables plug-in, because the efforts to re-invent the wheel with the pure Angular grids have yielded a less robust wheel than DataTables.
It would be nice if it were otherwise, but I just have not seen the Angular ecosystem come up with as strong a grid as jQuery DataTables, and it is not as if a good data grid is a nice-to-have in a web app: a good grid is an essential.
As of the 0.17.0 release, the sort
method was deprecated in favor of sort_values
. sort
was completely removed in the 0.20.0 release. The arguments (and results) remain the same:
df.sort_values(['a', 'b'], ascending=[True, False])
You can use the ascending argument of sort
:
df.sort(['a', 'b'], ascending=[True, False])
For example:
In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
a b
2 1 4
7 1 3
1 1 2
3 1 2
4 3 2
6 4 4
0 4 3
9 4 3
5 4 1
8 4 1
As commented by @renadeen
Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.
that is, if you want to reuse df1 as a sorted DataFrame:
df1 = df1.sort(['a', 'b'], ascending=[True, False])
or
df1.sort(['a', 'b'], ascending=[True, False], inplace=True)
After inspecting an SSIS Package(due to a SQL Server executing commands really slow), that was set up in a client of ours about 5-4 years before the time of me writing this, I found out that there were the below tasks: 1) insert data from an XML file into a table called [Importbarcdes].
2) merge command on an another target table, using as source the above mentioned table.
3) "delete from [Importbarcodes]", to clear the table of the row that was inserted after the XML file was read by the task of the SSIS Package.
After a quick inspection all statements(SELECT, UPDATE, DELETE etc.) on the table ImportBarcodes that had only 1 row, took about 2 minutes to execute.
Extended Events showed a whole lot PAGEIOLATCH_EX wait notifications.
No indexes were present of the table and no triggers were registered.
Upon close inspection of the properties of the table, in the Storage Tab and under general section, the Data Space field showed more than 6 GIGABYTES of space allocated in pages.
What happened:
The query ran for a good portion of time each day for the last 4 years, inserting and deleting data in the table, leaving unused pagefiles behind with out freeing them up.
So, that was the main reason of the wait events that were captured by the Extended Events Session and the slowly executed commands upon the table.
Running ALTER TABLE ImportBarcodes REBUILD
fixed the issue freeing up all the unused space. TRUNCATE TABLE ImportBarcodes
did a similar thing, with the only difference of deleting all pagefiles and data.
Check out Fancybox. If you need the video to autoplay this example site was helpful!
in case you are interested only in column names then use this :
names(dplyr::select_if(train,is.numeric))
Just like @mark 's answer, we can create a Snippets in Chrome DevTools, to override
the default JavaScript. Finally, we can see what effects they have on the page.
The problem with 500 errors (with CodeIgniter), with different apache settings, it displays 500 error when there's an error with PHP configuration.
Here's how it can trigger 500 error with CodeIgniter:
Please check your apache error logs, there should be some interesting information in there.
If you're using python3, you can try this too:
python3 -m pip install --upgrade Scrapy --trusted-host pypi.org --trusted-host files.pythonhosted.org
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
try to remove these files manually
In my case I just removed all build
directories from project and subprojects
HTML 5 invites you give add a lot of semantic value to your code. What's more, there are natives solution to embed multimedia content.
The rest is important, but it's more technical sugar that will save you from doing the same stuff with a client programming language.
Another option either using Double
or double
is use Double.valueOf(double d).intValue();
. Simple and clean
If UAC is enabled on the computer, something like this should work:
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
WScript.Quit
End If
'actual code
/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
/* Portrait */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (orientation: portrait)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
/* Landscape */
@media only screen
and (min-width: 1024px)
and (max-height: 1366px)
and (orientation: landscape)
and (-webkit-min-device-pixel-ratio: 1.5) {
}
I don't have an iPad Pro but this works for me in the Chrome simulator.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
var $this = this; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
}, 0);
I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code
Edit :
here's an online example, just for you :)
Demo
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
canvas.width = video.videoWidth;_x000D_
canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
var $this = this; //cache_x000D_
(function loop() {_x000D_
if (!$this.paused && !$this.ended) {_x000D_
ctx.drawImage($this, 0, 0);_x000D_
setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
}_x000D_
})();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
<video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
<canvas id="canvas"></canvas>_x000D_
<label>_x000D_
<br />Try to play me :)</label>_x000D_
<br />_x000D_
</div>
_x000D_
BOOST_PP_STRINGIZE
seems a excellent solution for C++, but not for regular C.
Here is my solution for GNU CPP:
/* Some test definition here */
#define DEFINED_BUT_NO_VALUE
#define DEFINED_INT 3
#define DEFINED_STR "ABC"
/* definition to expand macro then apply to pragma message */
#define VALUE_TO_STRING(x) #x
#define VALUE(x) VALUE_TO_STRING(x)
#define VAR_NAME_VALUE(var) #var "=" VALUE(var)
/* Some example here */
#pragma message(VAR_NAME_VALUE(NOT_DEFINED))
#pragma message(VAR_NAME_VALUE(DEFINED_BUT_NO_VALUE))
#pragma message(VAR_NAME_VALUE(DEFINED_INT))
#pragma message(VAR_NAME_VALUE(DEFINED_STR))
Above definitions result in:
test.c:10:9: note: #pragma message: NOT_DEFINED=NOT_DEFINED
test.c:11:9: note: #pragma message: DEFINED_BUT_NO_VALUE=
test.c:12:9: note: #pragma message: DEFINED_INT=3
test.c:13:9: note: #pragma message: DEFINED_STR="ABC"
For "defined as interger", "defined as string", and "defined but no value" variables , they work just fine. Only for "not defined" variable, they displayed exactly the same as original variable name. You have to used to it -- or maybe someone can provide a better solution.
Just checked out P4merge since I heard about it in another blog article:
Very slick interface, and FREE! I've been a faithful Araxis Merge user, but considering this is free and awesome, I'd encourage you to check it out.
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj
and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.
In VB like this:
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
in C# like this:
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
We used DBVisualizer for that.
Description: The references graph is a great feature as it automatically renders all primary/foreign key mappings (also called referential integrity constraints) in a graph style. The table nodes and relations are layed out automatically, with a number of layout modes available. The resulting graph is unique as it displays all information in an optimal and readable layout. from its site
The GroupBox has a Validated event for this purpose, if you are using WinForms.
private void grpBox_Validated(object sender, EventArgs e)
{
GroupBox g = sender as GroupBox;
var a = from RadioButton r in g.Controls
where r.Checked == true select r.Name;
strChecked = a.First();
}
Not sure if it's really a problem, but I see you have the same name for your binding configuration ().
I usually try to call my endpoints something like "UserServiceBasicHttp" or something similar (the "Binding" really doesn't have anything to do here), and I try to call my binding configurations something with "....Configuration", e.g. "UserServiceDefaultBinding", to avoid any potential name clashes.
Marc
.success()
only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.
The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.
promise.done(doneCallback).fail(failCallback)
.done() has only one callback and it is the success callback
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
Problem is that none of mentioned functions is realiable and for some string and font will return incorrect height value. Especially will fail for attributed texts.
The only realiable solution is here: https://stackoverflow.com/a/4214978/699944 and the point is to use CoreText to manually calculate height of every line to get right size. There is no other known way to do this.
There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.
The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:
element:before{
content: "_";
opacity: 0;
}
As of 3.6 (probably works with slightly older 3.x as well), this is my solution:
import locale
locale.setlocale(locale.LC_ALL, '')
def number_format(n, dec_precision=4):
precision = len(str(round(n))) + dec_precision
return format(float(n), f'.{precision}n')
The purpose of the precision
calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).
The dec_precision
argument adds additional precision to use for decimal points. Since this makes use of the n
format, no insignificant zeros will be added (unlike f
formats). n
also will take care of rendering already-round integers without a decimal.
n
does require float
input, thus the cast.
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
I had a similar requirement to dump the contents of json file for logging, something quick and easy:
print(json.dumps(json.load(open(os.path.join('<myPath>', '<myjson>'), "r")), indent = 4 ))
if you use it often then put it in a function:
def pp_json_file(path, file):
print(json.dumps(json.load(open(os.path.join(path, file), "r")), indent = 4))
Import the view controller class which you want to show and use the following code
KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
calling a function is simple ..
myFunction();
so your code will be something like..
$(function(){
$('#elementID').click(function(){
myFuntion(); //this will call your function
});
});
$(function(){
$('#elementID').click( myFuntion );
});
or with some condition
if(something){
myFunction(); //this will call your function
}
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.
I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:
When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:
context.save();
context.translate(newx, newy);
context.rotate(-Math.PI/2);
context.textAlign = "center";
context.fillText("Your Label Here", labelXposition, 0);
context.restore();
.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".
From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.
CREATE VIEW lock_monitor AS(
SELECT
COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
blockeda.query as blocked_query, blockedl.mode as blocked_mode,
blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
( (blockingl.transactionid=blockedl.transactionid) OR
(blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);
SELECT * from lock_monitor;
As the query is long but useful, the article author has created a view for it to simplify it's usage.
ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
public static int getDrawable(Context context, String name)//method to get id
{
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name, //return id
"your drawable", context.getPackageName());
}
image.setImageResource(int Id);//set id using this method
Now a days phonegap and cordova is owned by Adobe. Only name conversation was different. For install plugin functionality , we should use same command for phonegap and cordova too.
Command : cordova plugin add cordova-plugin-photo-library
Here,
You can also find more plugin from https://cordova.apache.org/docs/en/latest/
echo date('y-m-d'); // Today
This will return today's date.
I was able to make the navigation bar transparent by adding a new .transparent class to the .navbar and setting the CSS like this:
.navbar.transparent.navbar-inverse .navbar-inner {
border-width: 0px;
-webkit-box-shadow: 0px 0px;
box-shadow: 0px 0px;
background-color: rgba(0,0,0,0.0);
background-image: -webkit-gradient(linear, 50.00% 0.00%, 50.00% 100.00%, color-stop( 0% , rgba(0,0,0,0.00)),color-stop( 100% , rgba(0,0,0,0.00)));
background-image: -webkit-linear-gradient(270deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
background-image: linear-gradient(180deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
}
My markup is like this
<div class="navbar transparent navbar-inverse">
<div class="navbar-inner">....
1. Remove data-toggle="dropdown" attribute (so click will not open dropdown menu)
2. Add :hover pseudo-class to show dropdown-menu
.dropdown:hover .dropdown-menu {display: block;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Pricing</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
$(this.parentNode).addClass('newClass');
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
r = 13 + 7.*rand(100,1);
Where 100,1 is the size of the desidered vector
Inside cmd
, run command pip install tk
and Tkinter should install.
Just use "justify-content-center" in the row's class attribute.
<div class="container">
<div class="row justify-content-center">
<h1>This is a header</h1>
</div>
</div>
You can use git filter-branch for that. e.g.
git filter-branch --parent-filter \
'if test $GIT_COMMIT != <sha1ofB>; then cat; fi'
This results in AB-C throwing away the commit log of A.
Here I came up with universal method to navigate from any place to root.
You create a new Class file with this class, so that it's accessible from anywhere in your project:
import UIKit
class SharedControllers
{
static func navigateToRoot(viewController: UIViewController)
{
var nc = viewController.navigationController
// If this is a normal view with NavigationController, then we just pop to root.
if nc != nil
{
nc?.popToRootViewControllerAnimated(true)
return
}
// Most likely we are in Modal view, so we will need to search for a view with NavigationController.
let vc = viewController.presentingViewController
if nc == nil
{
nc = viewController.presentingViewController?.navigationController
}
if nc == nil
{
nc = viewController.parentViewController?.navigationController
}
if vc is UINavigationController && nc == nil
{
nc = vc as? UINavigationController
}
if nc != nil
{
viewController.dismissViewControllerAnimated(false, completion:
{
nc?.popToRootViewControllerAnimated(true)
})
}
}
}
Usage from anywhere in your project:
{
...
SharedControllers.navigateToRoot(self)
...
}
i didn't have time to dig why the setBounds() method is not working on bitmap drawable as expected but i have little tweaked @androbean-studio solution to do what setBounds should do...
/**
* Created by ceph3us on 23.05.17.
* file belong to pl.ceph3us.base.android.drawables
* this class wraps drawable and forwards draw canvas
* on it wrapped instance by using its defined bounds
*/
public class WrappedDrawable extends Drawable {
private final Drawable _drawable;
protected Drawable getDrawable() {
return _drawable;
}
public WrappedDrawable(Drawable drawable) {
super();
_drawable = drawable;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
//update bounds to get correctly
super.setBounds(left, top, right, bottom);
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setBounds(left, top, right, bottom);
}
}
@Override
public void setAlpha(int alpha) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setAlpha(alpha);
}
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setColorFilter(colorFilter);
}
}
@Override
public int getOpacity() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getOpacity()
: PixelFormat.UNKNOWN;
}
@Override
public void draw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.draw(canvas);
}
}
@Override
public int getIntrinsicWidth() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getBounds().width()
: 0;
}
@Override
public int getIntrinsicHeight() {
Drawable drawable = getDrawable();
return drawable != null ?
drawable.getBounds().height()
: 0;
}
}
usage:
// get huge drawable
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper
wrappedDrawable.setBounds(0,0,32,32);
// use wrapped drawable
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);
results
It appears from your question that you already have a second set of DNS servers available that reference the development site instead of the live site.
I would suggest that you simply run a standard SOCKS proxy either on that DNS server system or on a low-end spare system and have that system configured to use the development DNS server. You can then tell Firefox to use that proxy instead of downloading pages directly.
Doing it this way, the actual DNS lookups will be done on the proxy machine and not on the machine that's running the web browser.
A very simple yet effective solution to update your fragment views. Use setUserVisibleHint()
method. It will be called upon when the fragment is about to be visible to user. There you can update our view (setText()
or setVisibility()
etc.)
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//Write your code to be executed when it is visible to user
}
}
It worked in my case. Hope it helps!
Any logic having to do with what is displayed in the view should be delegated to a helper method, as methods in the model are strictly for handling data.
Here is what you could do:
# In the helper...
def link_to_thing(text, thing)
(thing.url?) ? link_to(text, thing_path(thing)) : link_to(text, thing.url)
end
# In the view...
<%= link_to_thing("text", @thing) %>
use:
$scope.users.length;
Instead of:
$scope.users.lenght;
And next time "spell-check" your code.
I met this problem because I use request.js which writen base on axios
And I already set a defaults.headers in request.js
import axios from 'axios'
const request = axios.create({
baseURL: '',
timeout: 15000
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
here is how I solve this
instead of
request.post('/manage/product/upload.do',
param,config
)
I use axios directly send request,and didn't add config
axios.post('/manage/product/upload.do',
param
)
hope this can solve your problem
below is an generic example
//base class
class A {
// The virtual method
protected virtualStuff1?():void;
public Stuff2(){
//Calling overridden child method by parent if implemented
this.virtualStuff1 && this.virtualStuff1();
alert("Baseclass Stuff2");
}
}
//class B implementing virtual method
class B extends A{
// overriding virtual method
public virtualStuff1()
{
alert("Class B virtualStuff1");
}
}
//Class C not implementing virtual method
class C extends A{
}
var b1 = new B();
var c1= new C();
b1.Stuff2();
b1.virtualStuff1();
c1.Stuff2();
For storing a single row output into a variable from the select into query :
declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';
this will store the value of a single record into the variable v_username.
For storing multiple rows output into a variable from the select into query :
you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;
You can't: DataFrame
columns are Series
, by definition. That said, if you make the dtype
(the type of all the elements) datetime-like, then you can access the quantities you want via the .dt
accessor (docs):
>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205 76032930 2015-01-24 00:05:27.513000
232 76032930 2015-01-24 00:06:46.703000
233 76032930 2015-01-24 00:06:56.707000
413 76032930 2015-01-24 00:14:24.957000
565 76032930 2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205 76032930 1
232 76032930 1
233 76032930 1
413 76032930 1
565 76032930 1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205 76032930 5
232 76032930 6
233 76032930 6
413 76032930 14
565 76032930 23
dtype: int64
If you're stuck using an older version of pandas
, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:
>>> df["TimeReviewed"].apply(lambda x: x.year)
205 76032930 2015
232 76032930 2015
233 76032930 2015
413 76032930 2015
565 76032930 2015
Name: TimeReviewed, dtype: int64
For me, I changed C:\apps\Java\jdk1.8_162\bin\javac.exe to C:\apps\Java\jdk1.8_162\bin\javacpl.exe Since there was no executable with that name in the bin folder. That worked.
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.
If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat
to parse these kinds of strings.
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Lets see some simple examples of both __getattr__
and __getattribute__
magic methods.
__getattr__
Python will call __getattr__
method whenever you request an attribute that hasn't already been defined. In the following example my class Count has no __getattr__
method. Now in main when I try to access both obj1.mymin
and obj1.mymax
attributes everything works fine. But when I try to access obj1.mycurrent
attribute -- Python gives me AttributeError: 'Count' object has no attribute 'mycurrent'
class Count():
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent) --> AttributeError: 'Count' object has no attribute 'mycurrent'
Now my class Count has __getattr__
method. Now when I try to access obj1.mycurrent
attribute -- python returns me whatever I have implemented in my __getattr__
method. In my example whenever I try to call an attribute which doesn't exist, python creates that attribute and set it to integer value 0.
class Count:
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
def __getattr__(self, item):
self.__dict__[item]=0
return 0
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent1)
__getattribute__
Now lets see the __getattribute__
method. If you have __getattribute__
method in your class, python invokes this method for every attribute regardless whether it exists or not. So why we need __getattribute__
method? One good reason is that you can prevent access to attributes and make them more secure as shown in the following example.
Whenever someone try to access my attributes that starts with substring 'cur' python raises AttributeError
exception. Otherwise it returns that attribute.
class Count:
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
Important: In order to avoid infinite recursion in __getattribute__
method, its implementation should always call the base class method with the same name to access any attributes it needs. For example: object.__getattribute__(self, name)
or super().__getattribute__(item)
and not self.__dict__[item]
If your class contain both getattr and getattribute magic methods then __getattribute__
is called first. But if __getattribute__
raises
AttributeError
exception then the exception will be ignored and __getattr__
method will be invoked. See the following example:
class Count(object):
def __init__(self,mymin,mymax):
self.mymin=mymin
self.mymax=mymax
self.current=None
def __getattr__(self, item):
self.__dict__[item]=0
return 0
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self,item)
# or you can use ---return super().__getattribute__(item)
# note this class subclass object
obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
The size_t
type is meant to specify the size of something so it's natural to use it, for example, getting the length of a string and then processing each character:
for (size_t i = 0, max = strlen (str); i < max; i++)
doSomethingWith (str[i]);
You do have to watch out for boundary conditions of course, since it's an unsigned type. The boundary at the top end is not usually that important since the maximum is usually large (though it is possible to get there). Most people just use an int
for that sort of thing because they rarely have structures or arrays that get big enough to exceed the capacity of that int
.
But watch out for things like:
for (size_t i = strlen (str) - 1; i >= 0; i--)
which will cause an infinite loop due to the wrapping behaviour of unsigned values (although I've seen compilers warn against this). This can also be alleviated by the (slightly harder to understand but at least immune to wrapping problems):
for (size_t i = strlen (str); i-- > 0; )
By shifting the decrement into a post-check side-effect of the continuation condition, this does the check for continuation on the value before decrement, but still uses the decremented value inside the loop (which is why the loop runs from len .. 1
rather than len-1 .. 0
).
Sometimes the files are actually located at ~/
. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.
cd ~/
vim .bashrc
Paste the following...
if test -t 1; then
exec zsh
fi
Save/close Vim.
Restart the terminal
You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com
ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.
I hope this helps with the dynamic website you have got.
Sub multiplechrome()
Dim WebUrl As String
Dim i As Integer
For i = 1 To ActiveSheet.Cells(1, 2).Value
WebUrl = "http://" & Cells(i, 1).Value & """"
Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)
Next
End Sub
Concerning the (somewhat off topic I know but since it was brought up earlier) XNA vs OpenGL choice, it might be beneficial in several cases to go with OpenGL instead of XNA (and in other XNA instead of OpenGL...).
If you are going to run the applications on Linux or Mac using Mono, it might be a good choice to go with OpenGL. Also, which isn't so widely known I think, if you have customers that are going to run your applications in a Citrix environment, then DirectX/Direct3D/XNA won't be as economical a choice as OpenGL. The reason for this is that OpenGL applications can be co-hosted on a lesser number of servers (due to performance issues a single server cannot host an infinite number of application instances) than DirectX/XNA applications which demands dedicated virtual servers to run in hardware accelerated mode. Other requirements exists like supported graphics cards etc but I will keep to the XNA vs OpenGL issue. As an IT Architect, Software developer etc this will have to be considered before choosing between OpenGL and DirectX/XNA...
A side note is that WebGL is based on OpenGL ES3 afaik...
As a further note, these are not the only considerations, but they might make the choice easier for some...
Change this line:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
If you need to log an error to Apache error log you can try this:
error_log( print_r($multidimensionalarray, TRUE) );
you can use angular's filter
https://docs.angularjs.org/api/ng/filter/filter
in your controller:
$filter('filter')(myArray, {'id':73})
or in your HTML
{{ myArray | filter : {'id':73} }}
Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update
).
But unfortunately there is no way to clone
/ mirror / update
the hooks, as I wanted...
I have found this very interesting thread about cloning/mirroring the hooks:
http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread
I learned:
The hooks are not considered part of the repository contents.
There is more data, like the .git/description
folder, which does not get cloned, just as the hooks.
The default hooks that appear in the hooks
dir comes from the TEMPLATE_DIR
There is this interesting template
feature on git.
So, I may either ignore this "clone the hooks thing", or go for a rsync
strategy, given the purposes of my mirror (backup + source for other clones, only).
Well... I will just forget about hooks cloning, and stick to the git remote update
way.
clone
/ update
process, but also stashes, rerere, etc... So, for a strict backup, rsync
or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update
.Thanks! Improved a bit of my own "git-fu"... :-)
You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!
<a href="#">
<img src="p.png"></img>
</a>
You must set up your system proxy You have to go through this path controlpanel>>internet option>>connnection>>LAN settings>> proxy no tik:use proxy server
When jQuery is not present you get $ is undefined
and not your message.
Did you check if you don't have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.
Slightly out of the question, but I can't resist to write a shorter code to your class assignment:
var i = 1;
$("ol li").each(function(){
$(this).addClass('olli' + i++);
});
public class Randoms {
static int z, a = 1111, b = 9999, r;
public static void main(String ... args[])
{
rand();
}
public static void rand() {
Random ran = new Random();
for (int i = 1; i == 1; i++) {
z = ran.nextInt(b - a + 1) + a;
System.out.println(z);
randcheck();
}
}
private static void randcheck() {
for (int i = 3; i >= 0; i--) {
if (z != 0) {
r = z % 10;
arr[i] = r;
z = z / 10;
}
}
for (int i = 0; i <= 3; i++) {
for (int j = i + 1; j <= 3; j++) {
if (arr[i] == arr[j]) {
rand();
}
}
}
}
}
When the color of text is dark, in Safari and Chrome, I have better result with the text-stroke css property.
-webkit-text-stroke: 0.5px #000;
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.
So if you say
for c in session.query(Stuff).all():
c.foo = c.foo+1
session.commit()
it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.
Instead you should do this:
session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()
This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.
In the almost-released 0.5 series you could also use this method for updating:
session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()
That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False
to the update statement and get rid of that select.
You can implement your own modulus function to do that for you:
double dmod(double x, double y) {
return x - (int)(x/y) * y;
}
Then you can simply use dmod(6.3, 2)
to get the remainder, 0.3
.
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
if you want your check box to keep its height and width but only be invisible:
.hiddenCheckBox{
visibility: hidden;
}
if you want your check box to be invisible without any with and height:
.hiddenCheckBox{
display: none;
}
Just learned about InitCap()
.
Here is some sample code:
SELECT ID
,InitCap(LastName ||', '|| FirstName ||' '|| Nvl(MiddleName,'')) AS RecipientName
FROM SomeTable
Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.
Your code will result in compiler errors. Your first code fragment:
char buf[10] ; buf = ''
is doubly illegal. First, in C, there is no such thing as an empty char
. You can use double quotes to designate an empty string, as with:
char* buf = "";
That will give you a pointer to a NUL
string, i.e., a single-character string with only the NUL
character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL
character, you have to specify it:
char buf = '\0';
The backslash is necessary to disambiguate from character '0'
.
char buf = 0;
accomplishes the same thing, but the former is a tad less ambiguous to read, I think.
Secondly, you cannot initialize arrays after they have been defined.
char buf[10];
declares and defines the array. The array identifier buf
is now an address in memory, and you cannot change where buf
points through assignment. So
buf = // anything on RHS
is illegal. Your second and third code fragments are illegal for this reason.
To initialize an array, you have to do it at the time of definition:
char buf [10] = ' ';
will give you a 10-character array with the first char being the space '\040'
and the rest being NUL
, i.e., '\0'
. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0
. There will not be any "random content".
If you declare and define the array but don't initialize it, as in the following:
char buf [10];
you will have random content in all the elements.
Also, you can check the compatibility troubleshooting
Check the detail steps, and other ways to always open VS as Admin at Visual Studio requires the application to have elevated permissions.
You can set RequestParam, using generic class Integer instead of int, it will resolve your issue.
@RequestParam(value= "i", defaultValue = "20") Integer i
Robert Martin has an excellent paper on the Liskov Substitution Principle. It discusses subtle and not-so-subtle ways in which the principle may be violated.
Some relevant parts of the paper (note that the second example is heavily condensed):
A Simple Example of a Violation of LSP
One of the most glaring violations of this principle is the use of C++ Run-Time Type Information (RTTI) to select a function based upon the type of an object. i.e.:
void DrawShape(const Shape& s) { if (typeid(s) == typeid(Square)) DrawSquare(static_cast<Square&>(s)); else if (typeid(s) == typeid(Circle)) DrawCircle(static_cast<Circle&>(s)); }
Clearly the
DrawShape
function is badly formed. It must know about every possible derivative of theShape
class, and it must be changed whenever new derivatives ofShape
are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.Square and Rectangle, a More Subtle Violation.
However, there are other, far more subtle, ways of violating the LSP. Consider an application which uses the
Rectangle
class as described below:class Rectangle { public: void SetWidth(double w) {itsWidth=w;} void SetHeight(double h) {itsHeight=w;} double GetHeight() const {return itsHeight;} double GetWidth() const {return itsWidth;} private: double itsWidth; double itsHeight; };
[...] Imagine that one day the users demand the ability to manipulate squares in addition to rectangles. [...]
Clearly, a square is a rectangle for all normal intents and purposes. Since the ISA relationship holds, it is logical to model the
Square
class as being derived fromRectangle
. [...]
Square
will inherit theSetWidth
andSetHeight
functions. These functions are utterly inappropriate for aSquare
, since the width and height of a square are identical. This should be a significant clue that there is a problem with the design. However, there is a way to sidestep the problem. We could overrideSetWidth
andSetHeight
[...]But consider the following function:
void f(Rectangle& r) { r.SetWidth(32); // calls Rectangle::SetWidth }
If we pass a reference to a
Square
object into this function, theSquare
object will be corrupted because the height won’t be changed. This is a clear violation of LSP. The function does not work for derivatives of its arguments.[...]
Check this:
a = [*(1..10), :top, *10.downto( 1 )]
You need to delete your old db folder and recreate new one. It will resolve your issue.
It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:
Code:
Array.prototype.findFirstSubstring = function(s) {
for(var i = 0; i < this.length;i++)
{
if(this[i].indexOf(s) !== -1)
return i;
}
return -1;
};
Usage:
i.findFirstSubstring('height');
Returns:
-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2
)
For Java, there is a java.util.BitSet
.
https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html
cardinality(): Returns the number of bits set to true in this BitSet.
The BitSet is memory efficient since it's stored as a Long.
I was having the same issue, and for me it worked by simply concatenating https:${image.getAttribute('src')}
try this:
var span = document.getElementById("span");
span.style.fontSize = "25px";
span.innerHTML = "String";
<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});
I think this simple solution may be.
You can use the DataColumnCollection of Your datatable to check if the column is in the collection.
Something like:
DataColumnCollection Columns = dtItems.Columns;
if (Columns.Contains(ColNameToCheck))
{
row["ColNameToCheck"] = "Checked";
}
Use this:
return this.RedirectToAction<AccountController>(m => m.LogIn());
That file will allow all crawlers access
User-agent: *
Allow: /
This basically allows all user agents (the *) to all parts of the site (the /).
I would just recommend creating a new virtual environment and installing all the packages from the start as the wheels for some packages might have been installed for the previous version of the Python. I believe this is the safest way and you have two options.
Creating a new virtual environment with venv
:
python3.6 -m venv -n new_env
source venv_env/bin/activate
Creating a conda
environment:
conda create -n new_env python=3.6
conda activate new_env
The packages you install in an environment are built based on the Python version of the environment and if you do not carefully modify the existing environment, then, you can cause some incompatibilities between packages. That is why I would recommend a using a new environment built with Python 3.6.
This example should work fine. I have added streamhandler for console. Console log and file handler data should be similar.
# MUTHUKUMAR_TIME_DATE.py #>>>>>>>> file name(module)
import sys
import logging
import logging.config
# ================== Logger ================================
def Logger(file_name):
formatter = logging.Formatter(fmt='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S') # %I:%M:%S %p AM|PM format
logging.basicConfig(filename = '%s.log' %(file_name),format= '%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S', filemode = 'w', level = logging.INFO)
log_obj = logging.getLogger()
log_obj.setLevel(logging.DEBUG)
# log_obj = logging.getLogger().addHandler(logging.StreamHandler())
# console printer
screen_handler = logging.StreamHandler(stream=sys.stdout) #stream=sys.stdout is similar to normal print
screen_handler.setFormatter(formatter)
logging.getLogger().addHandler(screen_handler)
log_obj.info("Logger object created successfully..")
return log_obj
# =======================================================
MUTHUKUMAR_LOGGING_CHECK.py #>>>>>>>>>>> file name
# calling **Logger** function
file_name = 'muthu'
log_obj =Logger(file_name)
log_obj.info("yes hfghghg ghgfh".format())
log_obj.critical("CRIC".format())
log_obj.error("ERR".format())
log_obj.warning("WARN".format())
log_obj.debug("debug".format())
log_obj.info("qwerty".format())
log_obj.info("asdfghjkl".format())
log_obj.info("zxcvbnm".format())
# closing file
log_obj.handlers.clear()
OUTPUT:
2019/07/13 23:54:40 MUTHUKUMAR_TIME_DATE,line: 17 INFO | Logger object created successfully..
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 8 INFO | yes hfghghg ghgfh
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 9 CRITICAL | CRIC
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 10 ERROR | ERR
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 11 WARNING | WARN
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 12 DEBUG | debug
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 13 INFO | qwerty
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 14 INFO | asdfghjkl
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 15 INFO | zxcvbnm
Thanks,
sudo su
then
npm install nodemon
worked for me
Try setting a height on your td elements.
vertical-align: middle;
means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.
The full URL is available as request.url
, and the query string is available as request.query_string.decode()
.
Here's an example:
from flask import request
@app.route('/adhoc_test/')
def adhoc_test():
return request.query_string
To access an individual known param passed in the query string, you can use request.args.get('param')
. This is the "right" way to do it, as far as I know.
ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.
The error is also caused by quirky handling of quotes and single qutoes. To include single quotes inside the query, use doubled single quotes.
This won't work
select dbms_xmlgen.getxml("Select ....") XML from dual;
or this either
select dbms_xmlgen.getxml('Select .. where something='red'..') XML from dual;
but this DOES work
select dbms_xmlgen.getxml('Select .. where something=''red''..') XML from dual;
Anyone looking for a jquery "combo box" seems to be directed to this question. My post is for people coming to this page to find a "traditional" combo box, rather than an answer to the original question. The above solutions all focus on using the input as a means to filtering and autocompleting to an existing select value. (great for large datasets)
If you're looking for the traditional combo box, which is simply "Type something or select from these pre-defined values" (no we won't hide the ones that don't match while you're typing), all you may need to do is
<select id="combo4" style="width: 200px;"
onchange="$('input#text4').val($(this).val());">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
<input id="text4"
style="margin-left: -203px; width: 180px; height: 1.2em; border: 0;" />
See http://bit.wisestamp.com/uncategorized/htmljquery-editable-combo-2/
Should be easy to wrap this into a plugin that converts an existing select tag, though I haven't seen that done yet.
P.S.: The main problem I see with "jQuery Editable Combobox" is that it remains a select list, and it is not obvious at all that you can just start typing something new.
controller_name
holds the name of the controller used to serve the current view.
Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url
method:
from django.urls import reverse
def get_admin_url(self):
return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
args=[self.id])
Another Solution is to:
Select Project -> Target -> Build phase -> Compile source -> search for the file which is mentioned in the 3rd last error line (In your case BFAppLinkReturnToRefererView.o).
Then you will see either 1 or 2 files in search result.
Remove one of them and compile again. It should recompile now because there is only one file left and no more conflicts for build.
If that doesnt work the file probably has errors in it and you should remove all of them and then recompile. It should work again.
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue
Use "fontPath" attribute directly in xml file.
for use in style.xml
<item name="fontPath">fonts/ProximaNovaSemibold.ttf</item>
for use in direct layout file
fontPath="fonts/ProximaNovaBold.ttf"
(Note : No need to use app/android attribute in prefix)
Swift 4 & 5
Change the direction of UIButton image (RTL and LTR)
extension UIButton {
func changeDirection(){
isArabic ? (self.contentHorizontalAlignment = .right) : (self.contentHorizontalAlignment = .left)
// left-right margin
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
}
Public Class Form1
Private animatedimage As New Bitmap("C:\MyData\Search.gif")
Private currentlyanimating As Boolean = False
Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Invalidate()
End Sub
Private Sub AnimateImage()
If currentlyanimating = True Then
ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
currentlyanimating = False
End If
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
AnimateImage()
ImageAnimator.UpdateFrames(animatedimage)
e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BtnStop.Enabled = False
End Sub
Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click
currentlyanimating = False
ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
BtnStart.Enabled = True
BtnStop.Enabled = False
End Sub
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
currentlyanimating = True
AnimateImage()
BtnStart.Enabled = False
BtnStop.Enabled = True
End Sub
End Class
The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.
First, you can use special formal parameter syntax *
. If the function definition has a formal parameter preceded by a single *
, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **
, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.
For instance, here's a function opt_fun
which takes two positional parameters x1
and x2
, and looks for another keyword parameter named "optional".
>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
... if ('optional' in keyword_parameters):
... print 'optional parameter found, it is ', keyword_parameters['optional']
... else:
... print 'no optional parameter, sorry'
...
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry
Second, you can supply a default parameter value of some value like None
which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
You can use aspnet_compiler for this:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v /Virtual/Application/Path/Or/Path/In/IIS/Metabase -p C:\Path\To\Your\WebProject -f -errorstack C:\Where\To\Put\Compiled\Site
where "/Virtual/Application/Path/Or/Path/In/IIS/Metabase" is something like this: "/MyApp" or "/lm/w3svc2/1/root/"
Also there is a AspNetCompiler Task on MSDN, showing how to integrate aspnet_compiler with MSBuild:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="PrecompileWeb">
<AspNetCompiler
VirtualPath="/MyWebSite"
PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
TargetPath="c:\precompiledweb\MyWebSite\"
Force="true"
Debug="true"
/>
</Target>
</Project>
Two approaches:
When you login: you can to create a copy_my_files.bat
file into your All Programs > Startup
folder with this content (its a plain text document):
xcopy c:\folder\*.* d:\another_folder\.
Use xcopy c:\folder\*.* d:\another_folder\. /Y
to overwrite the file without any prompt.
Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher
You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
span {
font-size:12px;
}
a {
color:green;
}
.test1>a:hover span {
display:none;
}
.test1>a:hover:before {
color:red;
content:"Apple";
}
</style>
</head>
<body>
<div class="test1">
<a href="#"><span>Google</span></a>
</div>
<div class="test2">
<a href="#"><span>Apple</span></a>
</div>
</body>
</html>
Note: The hover:before switch works only on the .test1 class
Try This
<!DOCTYPE html>
<html>
<head>
<title>Sticky Header and Footer</title>
<style type="text/css">
/* Reset body padding and margins */
body {
margin:0;
padding:0;
}
/* Make Header Sticky */
#header_container {
background:#eee;
border:1px solid #666;
height:60px;
left:0;
position:fixed;
width:100%;
top:0;
}
#header {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/
#container {
margin:0 auto;
overflow:auto;
padding:80px 0;
width:940px;
}
#content {
}
/* Make Footer Sticky */
#footer_container {
background:#eee;
border:1px solid #666;
bottom:0;
height:60px;
left:0;
position:fixed;
width:100%;
}
#footer {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
</style>
</head>
<body>
<!-- BEGIN: Sticky Header -->
<div id="header_container">
<div id="header">
Header Content
</div>
</div>
<!-- END: Sticky Header -->
<!-- BEGIN: Page Content -->
<div id="container">
<div id="content">
content
<br /><br />
blah blah blah..
...
</div>
</div>
<!-- END: Page Content -->
<!-- BEGIN: Sticky Footer -->
<div id="footer_container">
<div id="footer">
Footer Content
</div>
</div>
<!-- END: Sticky Footer -->
</body>
</html>
Have you tried setting the spacing to zero?
/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}
string.translate with table=None works fine.
>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
Generally this kind of error comes with human mistakes like if we change the namespace in some improper way, or changing folder names from explorer for current project etc, where compiler is unable to detect sometimes.
I came across the same error, to resolve which I tried few steps. Please follow all the steps :
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "**Client**", "**Client** \ **Client**.csproj", "{4503E259-0E3B-414A-9074-F251684322A5}"
EndProject
Check again Foldernames (I have highlighted in BOLD) and make it similar to what you did in step 2.
Clean the whole solution again
Build The Solution (If doesn't work try building individual after cleaning again)
Just an update, its seem that PHP guys are working on supporting thread and its available now.
Here is the link to it: http://php.net/manual/en/book.pthreads.php
In android studio emulator to run an apk file just drag the apk into the emulator.The emulator will install the apk
ad 1. It does not implement its methods.
ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap
is an interface that extends Map
. A client not interested in the sorting aspect can code against Map
and handle all the instances of for example TreeMap
, which implements SortedMap
. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap
interface.
In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.
SELECT TRUNC(SYSDATE,'D') "1ST_DAY", TRUNC(SYSDATE,'D') + 6 LAST_DAY FROM DUAL
For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:
def is_string(obj):
try:
obj + ''
return True
except TypeError:
return False
wisefish was close with the duck-typing before he switched to the isinstance
approach, except that +=
has a different meaning for lists than +
does.
export default function DataTable({ col, row }) {
const [datatable, setDatatable] = React.useState({});
useEffect(() => {
setDatatable({
columns: col,
rows: row,
});
/// do any thing else
}, [row]);
return (
<MDBDataTableV5
hover
entriesOptions={[5, 20, 25]}
entries={5}
pagesAmount={4}
data={datatable}
/>
);
}
this example use useEffect
to change state when props
change.
VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.
There is currently no way to disable this behaviour.
I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.
@Directive({
selector: "[tabindex]"
})
export class TabindexDirective {
constructor(private elementHost: ElementRef) {}
@HostListener("focus")
setInputFocus(): void {
this.elementHost.nativeElement.classList.add("has-focus");
}
@HostListener("blur")
setInputFocusOut(): void {
this.elementHost.nativeElement.classList.remove("has-focus");
}
}
I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)
mkdir build-dir
go inside it
cd build-dir
then run cmake
and point to the parent directory
cmake ..
and finally run make
make
Notice that make
and cmake
are different programs. cmake
is a Makefile
generator, and the make
utility is governed by a Makefile
textual file. See cmake & make wikipedia pages.
NB: On Windows, cmake
might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)
jww is right — you're referencing the wrong intermediate certificate.
As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt
Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose
.
We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .
). Once the named image is specified, our docker-compose
always builds off of the specific image. This allows a couple of different possibilities:
1- You can ensure that where ever you run your docker-compose
from, you will always be using the latest version of that specific image.
2- You can specify multiple named images in your docker-compose
file and let them be auto-wired through the previous build step.
So, if your image is already built, you can name the image with docker-compose
. Remove build
and specify image:
wildfly:
image: my_custom_wildfly_image
container_name: wildfly_server
ports:
- 9990:9990
- 80:8080
environment:
- MYSQL_HOST=mysql_server
- MONGO_HOST=mongo_server
- ELASTIC_HOST=elasticsearch_server
volumes:
- /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
links:
- mysql:mysql_server
- mongo:mongo_server
- elasticsearch:elasticsearch_server
The difference between struct and class keywords in C++ is that, when there is no specific specifier on particular composite data type then by default struct or union is the public keywords that merely considers data hiding but class is the private keyword that considers the hiding of program codes or data. Always some programmers use struct for data and class for code sake. For more information contact other sources.
It can work as easy as this, choose the location you want, in this case I choose D3
Sheets("Put your Sheet's name here").Range("D3") = Now
Example, my sheet is called Sources
Sheets("Sources").Range("D3") = Now
AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.
assert(x>10);
Output:
AssertionError
If x is not greater than 10 then you will get runtime exception saying AssertionError.
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
say you have
and you want to pass data to component2.ts.
in component1.ts is a variable with data say
//component1.ts
item={name:"Nelson", bankAccount:"1 million dollars"}
//component1.html
//the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to
//do with this , replace that with the url you are navigating to
<a
mat-button
[queryParams]="{ params: item | json}"
routerLink="/meter-readings/{{item.meterReadingId}}"
routerLinkActive="router-link-active">
View
</a>
//component2.ts
import { ActivatedRoute} from "@angular/router";
import 'rxjs/add/operator/filter';
/*class name etc and class boiler plate */
data:any //will hold our final object that we passed
constructor(
private route: ActivatedRoute,
) {}
ngOnInit() {
this.route.queryParams
.filter(params => params.reading)
.subscribe(params => {
console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR
//OBJECT
this.data = JSON.parse(params.item) ;
console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1
//million dollars"}
});
}
Some packages like javax.swing
were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.
By convention, all the standard extensions start with an X
while they can get promoted to first-class over time like what happened for javax.swing
.
Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?
To use mvn deploy:deploy-file, must add ~./m2/settings.xml
<settings>
<servers>
<server>
<id>nexus-repo</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
</settings>
command:
mvn deploy:deploy-file -DgroupId=com.example \
-DartifactId=my-app \
-Dversion=2.0.0 \
-Dpackaging=jar \
-Dfile=my-app.jar \
-DgeneratePom=true \
-DrepositoryId=nexus-repo \
-Durl=http://localhost:8081/repository/maven-releases/
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
As mentioned by Tom, background-color: rgba(229,229,229, 0.85)
can do the trick.
Place that on the style of the parent element and child wont be affected.
$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});
Whether you use currentframe().f_back
depends on whether you are using a
function or not.
Calling inspect directly:
from inspect import currentframe, getframeinfo
cf = currentframe()
filename = getframeinfo(cf).filename
print "This is line 5, python says line ", cf.f_lineno
print "The filename is ", filename
Calling a function that does it for you:
from inspect import currentframe
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
print "This is line 7, python says line ", get_linenumber()
I have the same problem (MSB3021) with WPF project in VS2008 (on Windows 7 x32). The problem appearing if i try to re-run application too quick after previous run. After a few minutes exe-file unlocked by itself and i can re-run application again. But such a long pause angers me. The only thing that really helped me was running VS as Administrator.
This might not be applicable to all scenarios, but I found that the position: sticky
(same thing with position: fixed
) only works on old iPhones when the scrolling container is not the body, but inside something else.
Example pseudo html:
body <- scrollbar
relative div
sticky div
The sticky div will be sticky on desktop browsers, but with certain devices, tested with: Chromium: dev tools: device emultation: iPhone 6/7/8, and with Android 4 Firefox, it will not.
What will work, however, is
body
div overflow=auto <- scrollbar
relative div
sticky div
The only problem with threads is accessing the same object from different threads without synchronization.
If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.
The following code does what is required
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}
Pushing and popping registers are behind the scenes equivalent to this:
push reg <= same as => sub $8,%rsp # subtract 8 from rsp
mov reg,(%rsp) # store, using rsp as the address
pop reg <= same as=> mov (%rsp),reg # load, using rsp as the address
add $8,%rsp # add 8 to the rsp
Note this is x86-64 At&t syntax.
Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.
You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,
If you want to explore options of communicating between components and feel like it is getting harder and harder, then you might consider adopting a good design pattern: Flux.
It is simply a collection of rules that defines how you store and mutate application wide state, and use that state to render components.
There are many Flux implementations, and Facebook's official implementation is one of them. Although it is considered the one that contains most boilerplate code, but it is easier to understand since most of the things are explicit.
Some of Other alternatives are flummox fluxxor fluxible and redux.
The 'aar' bundle is the binary distribution of an Android Library Project. .aar file
consists a JAR file and some resource files. You can convert it
as .jar file using this steps
1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using
any winrar or zip Extractor software.
2) Now you will get a .zip file. Right click on the .zip file and select "Extract files".
Will get a folder which contains "classes.jar, resource, manifest, R.java,
proguard(optional), libs(optional), assets(optional)".
3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.
Note: If you want to get only .jar file from your .aar file use the above way. Suppose If you want to include the manifest.xml and resources with your .jar file means you can just right click on your .aar file and save it as .jar file directly instead of saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.
Use the Reformat and Compile plugin (inspired by the Save Actions plugin of Alexandre DuBreuil):
https://plugins.jetbrains.com/plugin/8231?pr=idea_ce
At the moment I am only offering a jar file, but this is the most important part of the code:
private final static Set<Document> documentsToProcess = new HashSet<Document>();
private static VirtualFile[] fileToCompile = VirtualFile.EMPTY_ARRAY;
// The plugin extends FileDocumentManagerAdapter.
// beforeDocumentSaving calls reformatAndCompile
private static void reformatAndCompile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final PsiFile psiFile) {
documentsToProcess.add(document);
if (storage.isEnabled(Action.compileFile) && isDocumentActive(project, document)) {
fileToCompile = isFileCompilable(project, psiFile.getVirtualFile());
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (documentsToProcess.contains(document)) {
documentsToProcess.remove(document);
if (storage.isEnabled(Action.optimizeImports)
|| storage.isEnabled(Action.reformatCode)) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
if (storage.isEnabled(Action.optimizeImports)) {
new OptimizeImportsProcessor(project, psiFile)
.run();
}
if (storage.isEnabled(Action.reformatCode)) {
new ReformatCodeProcessor(
project,
psiFile,
null,
ChangeListManager
.getInstance(project)
.getChange(psiFile.getVirtualFile()) != null)
.run();
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(psiFile);
}
});
}
});
}
}
if (fileToCompile.length > 0) {
if (documentsToProcess.isEmpty()) {
compileFile(project, fileToCompile);
fileToCompile = VirtualFile.EMPTY_ARRAY;
}
} else if (storage.isEnabled(Action.makeProject)) {
if (documentsToProcess.isEmpty()) {
makeProject(project);
}
} else {
saveFile(project, document, psiFile.getVirtualFile());
}
}
}, project.getDisposed());
}
private static void makeProject(@NotNull final Project project) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).make(null);
}
}, project.getDisposed());
}
private static void compileFile(
@NotNull final Project project,
@NotNull final VirtualFile[] files) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).compile(files, null);
}
}, project.getDisposed());
}
private static void saveFile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final VirtualFile file) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
if (fileDocumentManager.isFileModified(file)) {
fileDocumentManager.saveDocument(document);
}
}
}, project.getDisposed());
}
sudo apt install libssl-dev
works on ubuntu 18.04.
If you want only those commits which are done by you in a particular branch, use the below command.
git log branch_name --author='Dyaniyal'
If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.
<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>
inet_ntoa()
works for IPv4; inet_ntop()
works for both IPv4 and IPv6.
Given an input struct sockaddr *res
, here are two snippets of code (tested on macOS):
#include <arpa/inet.h>
struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
char *s = inet_ntoa(addr_in->sin_addr);
printf("IP address: %s\n", s);
#include <arpa/inet.h>
#include <stdlib.h>
char *s = NULL;
switch(res->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
s = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res;
s = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
printf("IP address: %s\n", s);
free(s);
You need to just replace '
with ''
inside your string
SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'
You can also use REPLACE(@name, '''', '''''')
if generating the SQL dynamically
If you want to escape inside a like statement then you need to use the ESCAPE syntax
It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
There's a nice bookmarklet called Visual Event that can show you all the events attached to an element. It has color-coded highlights for different types of events (mouse, keyboard, etc.). When you hover over them, it shows the body of the event handler, how it was attached, and the file/line number (on WebKit and Opera). You can also trigger the event manually.
It can't find every event because there's no standard way to look up what event handlers are attached to an element, but it works with popular libraries like jQuery, Prototype, MooTools, YUI, etc.
similar to above, I got the dart sdk path from a project I created with flutter(not cloned) by going to Android Studio Preferences | Languages & Frameworks | Dart. Then similarly in the cloned project go to Preferences | Languages & Frameworks | Dart and "Enable Dart support for the project..." and enter the path you saved.
site-packages is just the location where Python installs its modules.
No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).
Programmatically you can find it this way:
import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages
'/Users/foo/.envs/env1/lib/python2.7/site-packages'
I'm now getting this in $HOME/.pip/pip.log
:
Could not fetch URL https://pypi.python.org/simple/: HTTP Error 403: TLSv1.2+ is required
I don't have a straightforward solution for this, but I'm mentioning it as something to watch out for before you waste time on trying some of the other solutions here.
trusted-host
didn't change anything (dunno where I picked this up)For what it's worth my openssl
is too old to even have ssl.OPENSSL_VERSION
so maybe that's really the explanation here.
In the end, wiping my virtual environment and recreating it with virtualenv --setuptools env
seems to have fixed at least the major blockers.
This is on a really old Debian box, Python 2.6.6.
Using selenium with Python, you start the driver with extensions disabled like this:
from selenium import webdriver
options = webdriver.chrome.options.Options()
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options)
The popup 'Disable developer mode extensions' will not pop up.
Ruby version: 2.7.1 gem version: 3.1.3
You need to check the extension that could not be installed, and find the reasons.
Read the mkmf.log file showed at the installation error under "To see why this extension failed to compile, please check the mkmf.log which can be found here" , perhaps there is a missing lib ( sometimes iconv ), and you must install it.
You can search the extension with your package manager(apt, yum, pacman...) too.
gem install rails
Showed me:
To see why this extension failed to compile, please check the mkmf.log which can be found here: /home/user/.gem/ruby/2.7.0/extensions/x86_64-linux/2.7.0/nokogiri-1.10.9/mkmf.log
Go to: https://aur.archlinux.org/packages/ruby-nokogiri/
make
installedgit clone
the packagecd
to packagemakepkg
the packageHope to help!
The preflight is being triggered by your Content-Type of application/json
. The simplest way to prevent this is to set the Content-Type to be text/plain
in your case. application/x-www-form-urlencoded
& multipart/form-data
Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.
If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.
Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:
Following Mark Rushakoff's tip above, here is my mapping:
" vertical to horizontal ( | -> -- )
noremap <c-w>- <c-w>t<c-w>K
" horizontal to vertical ( -- -> | )
noremap <c-w>\| <c-w>t<c-w>H
noremap <c-w>\ <c-w>t<c-w>H
noremap <c-w>/ <c-w>t<c-w>H
Edit: use Ctrl-w r to swap two windows if they are not in the good order.
Here is a server-centric approach:
<html ng-app="project">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
// Create your module
var dependencies = [];
var app = angular.module('project', dependencies);
// Create a 'defaults' service
app.value("defaults", /* your server-side JSON here */);
// Create a controller that uses the service
app.controller('PageController', function(defaults, $scope) {
// Populate your model with the service
$scope.card = defaults;
});
</script>
<body>
<div ng-controller="PageController">
<!-- Bind with the standard ng-model approach -->
<input type="text" ng-model="card.description">
</div>
</body>
</html>
It's the same basic idea as the more popular answers on this question, except $provide.value registers a service that contains your default values.
So, on the server, you could have something like:
{
description: "Visa-4242"
}
And put it into your page via the server-side tech of your choice. Here's a Gist: https://gist.github.com/exclsr/c8c391d16319b2d31a43
char*
and char[]
are different types, but it's not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an expression of type char[]
is provided where one of type char*
is expected, the compiler automatically converts the array into a pointer to its first element.
Your example function printSomething
expects a pointer, so if you try to pass an array to it like this:
char s[10] = "hello";
printSomething(s);
The compiler pretends that you wrote this:
char s[10] = "hello";
printSomething(&s[0]);
A simple example loading images into the tiles.
import 'package:flutter/material.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white30,
child: GridView.count(
crossAxisCount: 4,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: <String>[
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
].map((String url) {
return GridTile(
child: Image.network(url, fit: BoxFit.cover));
}).toList()),
);
}
}
The Flutter Gallery app contains a real world example, which can be found here.
use this:
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
There are some great suggestions here.
I think it's worth noting that you can treat an ActiveRecord model as a hash like so:
@customer = Customer.new( name: "John Jacob" )
@customer.name # => "John Jacob"
@customer[:name] # => "John Jacob"
@customer['name'] # => "John Jacob"
Therefore, instead of generating a hash of the attributes, you can use the object itself as a hash.
Yes you can. Example :
DELETE TableA
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
During debug, break on all exceptions thrown. Debug->Exceptions
Check all 'Thrown' exceptions. F5, the code will stop on the offending line.
You can use readfile and output the image headers which you can get from getimagesize like this:
$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);
The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.
This is also a very useful function if you are looking for a rows or data with where condition affected
function num_rows($table)
{
return $this->db->affected_rows($table);
}
This may not be the exact answer for the OP, but is the answer to the Title of the question: How to Update Gradle in Android Studio (AS):
Open the command prompt - start → Run → cmd
, or start menu → All Programs → Accessories → Command Prompt.
Type
netstat -aon | findstr '[port_number]'
Replace the [port_number]
with the actual port number that you want to check and hit Enter.
Type
tasklist | findstr '[PID]'
Replace the [PID]
with the number from the above step and hit Enter.
Link to something more sensible than the top of the page in the first place. Then cancel the default event.
See rule 2 of pragmatic progressive enhancement.
The onbeforeunload
Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).
Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.
Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):
function enableBeforeUnload() {
window.onbeforeunload = function (e) {
return "Discard changes?";
};
}
function disableBeforeUnload() {
window.onbeforeunload = null;
}
Then define a form like this:
<form method="POST" action="" onsubmit="disableBeforeUnload();">
<textarea name="text"
onchange="enableBeforeUnload();"
onkeyup="enableBeforeUnload();">
</textarea>
<button type="submit">Save</button>
</form>
This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.
It looks like NUnit Framework 2.6.4 does not work well with NUnit Test Adapter. In the website it mentions the test adapter will only work with NUnit Framework 2.6.3.
This was my problem: 1. I had downloaded NUnit and NUnit Test Adapter separately through Nuget in the VS2012. Somehow NUnit got updated to 2.6.4 Suddenly i did not see my test cases listed.
Fix:
Uninstall Nuget and Nuget Test adapter
a. Go to Tools> Nuget > Nuget Pkg manager > Manage Nuget Pkg for Solution
b. List installed packages
c. Click manage
d. Un-check your projects
Install NUnit Test Adapter including NUnit 2.6.3 Framework
Clean/Rebuild solution
Open Test > Test Explorer > Run All
I see all the test cases
Hope this helps
Add this in your AndroidManifest.xml :
android:windowSoftInputMode="stateHidden|adjustResize"
It works perfectly. :)
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
It is possible and you don't need to code it on your own.
Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...
Its just done for you with the application Nostalk from Android Market. Just give it a try ...
Put this below code in your Activity
in Android Manifest
.
android:configChanges="orientation"
This will not restart your activity when you would change orientation.
Open the mysql terminal:
el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>
Drop the function if it already exists
mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Create the function
mysql> create function hello(id INT)
-> returns CHAR(50)
-> return 'foobar';
Query OK, 0 rows affected (0.01 sec)
Create a simple table to test it out with
mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)
Insert three values into the table yar
mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
Select all the values from yar, run our function hello each time:
mysql> select id, hello(5) from yar;
+------+----------+
| id | hello(5) |
+------+----------+
| 5 | foobar |
| 7 | foobar |
| 9 | foobar |
+------+----------+
3 rows in set (0.01 sec)
Verbalize and internalize what just happened:
You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50)
containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5)
for each row returned by yar.
I just found all the above examples just too confusing, so I wrote my own. Code fragments are fine if you know what you're doing, but what about people like me who don't?
Want a cut-n-paste solution instead? Well here it is!
Create a new java file and call it Keystore. Then paste in this code:
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class Keystore { //Did you remember to vote up my example?
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
Log.v("Keystore","NEW STORE");
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
Editor editor = SP.edit();
editor.putString(key, value);
editor.commit(); // Stop everything and do an immediate save!
// editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above. This is the preferred way of saving.
}
public String get(String key) {//Log.v("Keystore","GET from "+key);
return SP.getString(key, null);
}
public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
Editor editor = SP.edit();
editor.putInt(key, num);
editor.commit();
}
public void clear(){ // Delete all shared preferences
Editor editor = SP.edit();
editor.clear();
editor.commit();
}
public void remove(){ // Delete only the shared preference that you want
Editor editor = SP.edit();
editor.remove(filename);
editor.commit();
}
}
Now save that file and forget about it. You're done with it. Now go back into your activity and use it like this:
public class YourClass extends Activity{
private Keystore store;//Holds our key pairs
public YourSub(Context context){
store = Keystore.getInstance(context);//Creates or Gets our key pairs. You MUST have access to current context!
int= store.getInt("key name to get int value");
string = store.get("key name to get string value");
store.putInt("key name to store int value",int_var);
store.put("key name to store string value",string_var);
}
}
One is assigning a value while the other is adding to the Dictionary a new Key and Value.
I was not satisfied, so I finally used this:
>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)
I don't know if it's quicker, but it looks more effective ;)
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
Your code seems correct. I would presume it is something to do with the fact you are using a .png and the way the browser redraws the object upon rotation is inefficient, causing the hang (what browser are you testing under?)
If possible replace the .png with something native.
see; http://kilianvalkhof.com/2010/css-xhtml/css3-loading-spinners-without-images/
Chrome gives me no pauses using this method.
I know I am posting this answer little late, but I felt it is worth using Google's fuse location provider service to get the current location.
Main features of this api are :
1.Simple APIs: Lets you choose your accuracy level as well as power consumption.
2.Immediately available: Gives your apps immediate access to the best, most recent location.
3.Power-efficiency: It chooses the most efficient way to get the location with less power consumptions
4.Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
It is flexible in while updating in location also.
If you want current location only when your app starts then you can use getLastLocation(GoogleApiClient)
method.
If you want to update your location continuously then you can use requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener)
You can find a very nice blog about fuse location here and google doc for fuse location also can be found here.
Update
According to developer docs starting from Android O they have added new limits on background location.
If your app is running in the background, the location system service computes a new location for your app only a few times each hour. This is the case even when your app is requesting more frequent location updates. However if your app is running in the foreground, there is no change in location sampling rates compared to Android 7.1.1 (API level 25).
There are at least five six ways. The preferred way depends on what your use case is.
Simply add an asdict()
method.
Based on the problem description I would very much consider the asdict
way of doing things suggested by other answers. This is because it does not appear that your object is really much of a collection:
class Wharrgarbl(object):
...
def asdict(self):
return {'a': self.a, 'b': self.b, 'c': self.c}
Using the other options below could be confusing for others unless it is very obvious exactly which object members would and would not be iterated or specified as key-value pairs.
Inherit your class from 'typing.NamedTuple'
(or the mostly equivalent 'collections.namedtuple'
), and use the _asdict
method provided for you.
from typing import NamedTuple
class Wharrgarbl(NamedTuple):
a: str
b: str
c: str
sum: int = 6
version: str = 'old'
Using a named tuple is a very convenient way to add lots of functionality to your class with a minimum of effort, including an _asdict
method. However, a limitation is that, as shown above, the NT will include all the members in its _asdict
.
If there are members you don't want to include in your dictionary, you'll need to modify the _asdict
result:
from typing import NamedTuple
class Wharrgarbl(NamedTuple):
a: str
b: str
c: str
sum: int = 6
version: str = 'old'
def _asdict(self):
d = super()._asdict()
del d['sum']
del d['version']
return d
Another limitation is that NT is read-only. This may or may not be desirable.
Implement __iter__
.
Like this, for example:
def __iter__(self):
yield 'a', self.a
yield 'b', self.b
yield 'c', self.c
Now you can just do:
dict(my_object)
This works because the dict()
constructor accepts an iterable of (key, value)
pairs to construct a dictionary. Before doing this, ask yourself the question whether iterating the object as a series of key,value pairs in this manner- while convenient for creating a dict
- might actually be surprising behavior in other contexts. E.g., ask yourself the question "what should the behavior of list(my_object)
be...?"
Additionally, note that accessing values directly using the get item obj["a"]
syntax will not work, and keyword argument unpacking won't work. For those, you'd need to implement the mapping protocol.
Implement the mapping protocol. This allows access-by-key behavior, casting to a dict
without using __iter__
, and also provides unpacking behavior ({**my_obj}
) and keyword unpacking behavior if all the keys are strings (dict(**my_obj)
).
The mapping protocol requires that you provide (at minimum) two methods together: keys()
and __getitem__
.
class MyKwargUnpackable:
def keys(self):
return list("abc")
def __getitem__(self, key):
return dict(zip("abc", "one two three".split()))[key]
Now you can do things like:
>>> m=MyKwargUnpackable()
>>> m["a"]
'one'
>>> dict(m) # cast to dict directly
{'a': 'one', 'b': 'two', 'c': 'three'}
>>> dict(**m) # unpack as kwargs
{'a': 'one', 'b': 'two', 'c': 'three'}
As mentioned above, if you are using a new enough version of python you can also unpack your mapping-protocol object into a dictionary comprehension like so (and in this case it is not required that your keys be strings):
>>> {**m}
{'a': 'one', 'b': 'two', 'c': 'three'}
Note that the mapping protocol takes precedence over the __iter__
method when casting an object to a dict
directly (without using kwarg unpacking, i.e. dict(m)
). So it is possible- and sometimes convenient- to cause the object to have different behavior when used as an iterable (e.g., list(m)
) vs. when cast to a dict
(dict(m)
).
EMPHASIZED: Just because you CAN use the mapping protocol, does NOT mean that you SHOULD do so. Does it actually make sense for your object to be passed around as a set of key-value pairs, or as keyword arguments and values? Does accessing it by key- just like a dictionary- really make sense?
If the answer to these questions is yes, it's probably a good idea to consider the next option.
Look into using the 'collections.abc
' module.
Inheriting your class from 'collections.abc.Mapping
or 'collections.abc.MutableMapping
signals to other users that, for all intents and purposes, your class is a mapping * and can be expected to behave that way.
You can still cast your object to a dict
just as you require, but there would probably be little reason to do so. Because of duck typing, bothering to cast your mapping object to a dict
would just be an additional unnecessary step the majority of the time.
This answer might also be helpful.
As noted in the comments below: it's worth mentioning that doing this the abc way essentially turns your object class into a dict
-like class (assuming you use MutableMapping
and not the read-only Mapping
base class). Everything you would be able to do with dict
, you could do with your own class object. This may be, or may not be, desirable.
Also consider looking at the numerical abcs in the numbers
module:
https://docs.python.org/3/library/numbers.html
Since you're also casting your object to an int
, it might make more sense to essentially turn your class into a full fledged int
so that casting isn't necessary.
Look into using the dataclasses
module (Python 3.7 only), which includes a convenient asdict()
utility method.
from dataclasses import dataclass, asdict, field, InitVar
@dataclass
class Wharrgarbl(object):
a: int
b: int
c: int
sum: InitVar[int] # note: InitVar will exclude this from the dict
version: InitVar[str] = "old"
def __post_init__(self, sum, version):
self.sum = 6 # this looks like an OP mistake?
self.version = str(version)
Now you can do this:
>>> asdict(Wharrgarbl(1,2,3,4,"X"))
{'a': 1, 'b': 2, 'c': 3}
Use typing.TypedDict
, which has been added in python 3.8.
NOTE: option 6 is likely NOT what the OP, or other readers based on the title of this question, are looking for. See additional comments below.
class Wharrgarbl(TypedDict):
a: str
b: str
c: str
Using this option, the resulting object is a dict
(emphasis: it is not a Wharrgarbl
). There is no reason at all to "cast" it to a dict (unless you are making a copy).
And since the object is a dict
, the initialization signature is identical to that of dict
and as such it only accepts keyword arguments or another dictionary.
>>> w = Wharrgarbl(a=1,b=2,b=3)
>>> w
{'a': 1, 'b': 2, 'c': 3}
>>> type(w)
<class 'dict'>
Emphasized: the above "class" Wharrgarbl
isn't actually a new class at all. It is simply syntactic sugar for creating typed dict
objects with fields of different types for the type checker.
As such this option can be pretty convenient for signaling to readers of your code (and also to a type checker such as mypy) that such a dict
object is expected to have specific keys with specific value types.
But this means you cannot, for example, add other methods, although you can try:
class MyDict(TypedDict):
def my_fancy_method(self):
return "world changing result"
...but it won't work:
>>> MyDict().my_fancy_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'my_fancy_method'
* "Mapping" has become the standard "name" of the dict
-like duck type
My guess is you are using a Set<Role>
in the User
class annotated with @OneToMany
. Which means one User
has many Role
s. But on the same field you use the @Column
annotation which makes no sense. One-to-many relationships are managed using a separate join table or a join column on the many side, which in this case would be the Role class. Using @JoinColumn
instead of @Column
would probably fix the issue, but it seems semantically wrong. I guess the relationship between role and user should be many-to-many.
You must create a new date object and set it as minDate
when you initialize the datepickers
<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>
var dateToday = new Date();
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
minDate: dateToday,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
Edit - from your comment now it works as expected http://jsfiddle.net/nicolapeluchetti/dAyzq/1/
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
For example you have a NSString
with special characters in NSString
strChangetoJSON.
Then you can convert that string to JSON response using above code.