Borrowing from @ericbn I prefere defines like
#define DIV_ROUND_INT(n,d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d)))
or if you work only with unsigned ints
#define DIV_ROUND_UINT(n,d) ((((n) + (d)/2)/(d)))
You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");
Your query should look like
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You can check the below question for help
It's called dependency injection via constructor injection: class A
gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.
There's an interesting introduction on wikipedia.
For const-correctness I'd write:
using T = int;
class A
{
public:
A(const T &thing) : m_thing(thing) {}
// ...
private:
const T &m_thing;
};
but a problem with this class is that it accepts references to temporary objects:
T t;
A a1{t}; // this is ok, but...
A a2{T()}; // ... this is BAD.
It's better to add (requires C++11 at least):
class A
{
public:
A(const T &thing) : m_thing(thing) {}
A(const T &&) = delete; // prevents rvalue binding
// ...
private:
const T &m_thing;
};
Anyway if you change the constructor:
class A
{
public:
A(const T *thing) : m_thing(*thing) { assert(thing); }
// ...
private:
const T &m_thing;
};
it's pretty much guaranteed that you won't have a pointer to a temporary.
Also, since the constructor takes a pointer, it's clearer to users of A
that they need to pay attention to the lifetime of the object they pass.
Somewhat related topics are:
The short answer is for creating an attribute in c# you only need to inherit it from Attribute class, Just this :)
But here I'm going to explain attributes in detail:
basically attributes are classes that we can use them for applying our logic to assemblies, classes, methods, properties, fields, ...
In .Net, Microsoft has provided some predefined Attributes like Obsolete or Validation Attributes like ( [Required], [StringLength(100)], [Range(0, 999.99)]), also we have kind of attributes like ActionFilters in asp.net that can be very useful for applying our desired logic to our codes (read this article about action filters if you are passionate to learn it)
one another point, you can apply a kind of configuration on your attribute via AttibuteUsage.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
When you decorate an attribute class with AttributeUsage you can tell to c# compiler where I'm going to use this attribute: I'm going to use this on classes, on assemblies on properties or on ... and my attribute is allowed to use several times on defined targets(classes, assemblies, properties,...) or not?!
After this definition about attributes I'm going to show you an example: Imagine we want to define a new lesson in university and we want to allow just admins and masters in our university to define a new Lesson, Ok?
namespace ConsoleApp1
{
/// <summary>
/// All Roles in our scenario
/// </summary>
public enum UniversityRoles
{
Admin,
Master,
Employee,
Student
}
/// <summary>
/// This attribute will check the Max Length of Properties/fields
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
public class ValidRoleForAccess : Attribute
{
public ValidRoleForAccess(UniversityRoles role)
{
Role = role;
}
public UniversityRoles Role { get; private set; }
}
/// <summary>
/// we suppose that just admins and masters can define new Lesson
/// </summary>
[ValidRoleForAccess(UniversityRoles.Admin)]
[ValidRoleForAccess(UniversityRoles.Master)]
public class Lesson
{
public Lesson(int id, string name, DateTime startTime, User owner)
{
var lessType = typeof(Lesson);
var validRolesForAccesses = lessType.GetCustomAttributes<ValidRoleForAccess>();
if (validRolesForAccesses.All(x => x.Role.ToString() != owner.GetType().Name))
{
throw new Exception("You are not Allowed to define a new lesson");
}
Id = id;
Name = name;
StartTime = startTime;
Owner = owner;
}
public int Id { get; private set; }
public string Name { get; private set; }
public DateTime StartTime { get; private set; }
/// <summary>
/// Owner is some one who define the lesson in university website
/// </summary>
public User Owner { get; private set; }
}
public abstract class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class Master : User
{
public DateTime HireDate { get; set; }
public Decimal Salary { get; set; }
public string Department { get; set; }
}
public class Student : User
{
public float GPA { get; set; }
}
class Program
{
static void Main(string[] args)
{
#region exampl1
var master = new Master()
{
Name = "Hamid Hasani",
Id = 1,
DateOfBirth = new DateTime(1994, 8, 15),
Department = "Computer Engineering",
HireDate = new DateTime(2018, 1, 1),
Salary = 10000
};
var math = new Lesson(1, "Math", DateTime.Today, master);
#endregion
#region exampl2
var student = new Student()
{
Name = "Hamid Hasani",
Id = 1,
DateOfBirth = new DateTime(1994, 8, 15),
GPA = 16
};
var literature = new Lesson(2, "literature", DateTime.Now.AddDays(7), student);
#endregion
ReadLine();
}
}
}
In the real world of programming maybe we don't use this approach for using attributes and I said this because of its educational point in using attributes
First off, the obvious answer that no one has provided, you need to install Babel into your application:
npm install babel --save
(or babel-core
if you instead want to require('babel-core/polyfill')
).
Aside from that, I have a grunt task to transpile my es6 and jsx as a build step (i.e. I don't want to use babel/register
, which is why I am trying to use babel/polyfill
directly in the first place), so I'd like to put more emphasis on this part of @ssube's answer:
Make sure you require it at the entry-point to your application, before anything else is called
I ran into some weird issue where I was trying to require babel/polyfill
from some shared environment startup file and I got the error the user referenced - I think it might have had something to do with how babel orders imports versus requires but I'm unable to reproduce now. Anyway, moving import 'babel/polyfill'
as the first line in both my client and server startup scripts fixed the problem.
Note that if you instead want to use require('babel/polyfill')
I would make sure all your other module loader statements are also requires and not use imports - avoid mixing the two. In other words, if you have any import statements in your startup script, make import babel/polyfill
the first line in your script rather than require('babel/polyfill')
.
You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.
You need to use queue.delete now in order to delete it.
See the API documentation for details:
If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.
You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.
Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
You may also need to reset counter in onPause
to prevent cases when user presses home or navigates away by some other means after first back press. Otherwise, I don't see an issue.
If you need to insert node/element in some specific place , you can to do next steps
It is simple algorithm but should works...
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
Error message suggests that the client has closed the connection while the server is still trying to write out a response.
Refer to this link for more details:
I needed this feature, but also wanted to make sure I did not return lines with a prefix before the ABB.log:
grep "\WABB.log$" -w a.tmp
What am I doing incorrectly?
You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.
How can I receive a json object in the controller?
View:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
Controller:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
First thing you need to do here is correct the hibernate dialect version like @JavaLearner has explained. Then you have make sure that all the versions of hibernate dependencies you are using are upto date. Typically you would need: database driver like mysql-connector-java
, hibernate dependency: hibernate-core
and hibernate entity manager: hibernate-entitymanager
. Lastly don't forget to check that the database tables you are using are not the reserved words like order
, group
, limit
, etc. It might save you a lot of headache.
All you need just run a test wait till finish, after that go to Build Setting, Search in to Build Setting Inference, change swift 3 @objc Inference to (Default). that's all what i did and worked perfect.
Maybe you are looking for this plyr::revalue function:
mutate(dat, x = revalue(x, c("A" = "B")))
You can see plyr::mapvalues too.
In the first class, sayHi()
is actually an instance method which you are calling as a static method and you get away with it because sayHi()
never refers to $this
.
Static functions are associated with the class, not an instance of the class. As such, $this
is not available from a static context ($this
isn't pointing to any object).
you could use this formular to do the job -> get the CellValue for the specific row by typing: = indirect("$A&Cell()) depending on which column you have to check, you have to change the $A
For Example -> You could use a customized VBA Function in the Background:
Public Function IstDatum(Zelle) As Boolean IstDatum = False If IsDate(Zelle) Then IstDatum = True End Function
I need it to check for a date-entry in column A:
=IstDatum(INDIREKT("$A"&ZEILE()))
The "no frills" options are as follows:
ActiveSheet.Name = "New Name"
and
Sheets("Sheet2").Name = "New Name"
You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.
to change text color of Navigation Drawer
we use
app:itemTextColor="@color/white"
to change incon color of navigation Drawer
use
app:itemIconTint="@color/black"
<com.google.android.material.navigation.NavigationView
android:id="@+id/naView"
app:itemIconTint="@color/black"
android:layout_width="match_parent"
app:menu="@menu/navmenu"
app:itemTextColor="@color/white"
app:headerLayout="@layout/nav_header"
android:layout_height="match_parent"
app:itemTextAppearance="?android:textAppearanceMedium"
android:fitsSystemWindows="true"
android:layout_gravity="start"
/>
self.navigationController != nil
would mean it's in a navigation stack.
ps -axf | grep parent_pid
Above command prints respective processes generated from parent_pid
, hope it helps.
+++++++++++++++++++++++++++++++++++++++++++
root@root:~/chk_prgrm/lp#
parent...18685
child... 18686
root@root:~/chk_prgrm/lp# ps axf | grep frk
18685 pts/45 R 0:11 | \_ ./frk
18686 pts/45 R 0:11 | | \_ ./frk
18688 pts/45 S+ 0:00 | \_ grep frk
From the bash manpage:
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.
[...]
Or, if you are not sure of having bash
, consider using cut
.
If you are using responsive layout, try including this js on your code: https://github.com/scottjehl/Respond
declare @ery nvarchar(max)
declare @tab nvarchar(max) = 'myTable'
declare @qu nvarchar(max) = 'alter table '+@tab+' drop constraint '
select @ery = (select bj.name from sys.tables as tb
inner join sys.objects as bj
on tb.object_id = bj.parent_object_id
where tb.name = @tab and bj.type = 'PK')
exec(@qu+@ery)
Take a look.
If you're using Mongo on Meteor, you can use _ensureIndex
:
CollectionName._ensureIndex({field:1 }, {unique: true});
A thread safe rotation function is the following (it works much better):
-(UIImage*)imageByRotatingImage:(UIImage*)initImage fromImageOrientation:(UIImageOrientation)orientation
{
CGImageRef imgRef = initImage.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = orientation;
switch(orient) {
case UIImageOrientationUp: //EXIF = 1
return initImage;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
// Create the bitmap context
CGContextRef context = NULL;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (bounds.size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * bounds.size.height);
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
return nil;
}
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
CGColorSpaceRef colorspace = CGImageGetColorSpace(imgRef);
context = CGBitmapContextCreate (bitmapData,bounds.size.width,bounds.size.height,8,bitmapBytesPerRow,
colorspace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
if (context == NULL)
// error creating context
return nil;
CGContextScaleCTM(context, -1.0, -1.0);
CGContextTranslateCTM(context, -bounds.size.width, -bounds.size.height);
CGContextConcatCTM(context, transform);
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(context, CGRectMake(0,0,width, height), imgRef);
CGImageRef imgRef2 = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
UIImage * image = [UIImage imageWithCGImage:imgRef2 scale:initImage.scale orientation:UIImageOrientationUp];
CGImageRelease(imgRef2);
return image;
}
If you have installed mongodb community server via homebrew, then you can do:
brew services list
This will list the current services as below:
Name Status User Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
redis stopped
Then you can restart mongodb by first stopping and restart:
brew services stop mongodb
brew services start mongodb
Try adding these after <Playlist>
<AutoLoad>false</AutoLoad>
<AutoPlay>false</AutoPlay>
I have figured out that I can convert the keyCode of the event to a character by using the following function:
var char = String.fromCharCode(v_code);
From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).
Thanks for all your help guys.
Add another div
or img
to your main div
and blur that instead. jsfiddle
.blur {
background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
background-size:cover;
-webkit-filter: blur(13px);
-moz-filter: blur(13px);
-o-filter: blur(13px);
-ms-filter: blur(13px);
filter: blur(13px);
position:absolute;
width:100%;
height:100%;
}
You can set debug(functionName)
to debug functions as well.
https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints#function
Xcode::Install is a simple cli software that allow you to install/select a specific Xcode version.
You can install it using gem install xcode-install
Then you will be able to install a specific version with xcversion install 9.4.1
And if you have more than one version installed, you can switch version with xcversion select 9.4
You can find more information at https://github.com/KrauseFx/xcode-install
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.
package com.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class TestContacts extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur != null && pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
}
}
}
}
}
I assume you have defined custom adapter for your ListView.
If this is the case then you can assign onClickListener
for your button inside the custom adapter's getView()
method.
This solution will change the git file permissions from 100755 to 100644 and push changes back to the bitbucket remote repo.
Take a look at your repo's file permissions: git ls-files --stage
If 100755 and you want 100644
Then run this command: git ls-files --stage | sed 's/\t/ /g' | cut -d' ' -f4 | xargs git update-index --chmod=-x
Now check your repo's file permissions again: git ls-files --stage
Now commit your changes:
git status
git commit -m "restored proper file permissions"
git push
THE MOST ELEGANT METHOD :D
There is one easiest way to do that, no need any directives for that.
"element-that-toggle-your-dropdown" should be button tag. Use any method in (blur) attribute. That's all.
<button class="element-that-toggle-your-dropdown"
(blur)="isDropdownOpen = false"
(click)="isDropdownOpen = !isDropdownOpen">
</button>
This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()
Aside from the fact that for
...in
loops over all enumerable properties (which is not the same as "all array elements"!), see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, section 12.6.4 (5th edition) or 13.7.5.15 (7th edition):
The mechanics and order of enumerating the properties ... is not specified...
(Emphasis mine.)
That means if a browser wanted to, it could go through the properties in the order in which they were inserted. Or in numerical order. Or in lexical order (where "30" comes before "4"! Keep in mind all object keys -- and thus, all array indexes -- are actually strings, so that makes total sense). It could go through them by bucket, if it implemented objects as hash tables. Or take any of that and add "backwards". A browser could even iterate randomly and be ECMA-262 compliant, as long as it visited each property exactly once.
In practice, most browsers currently like to iterate in roughly the same order. But there's nothing saying they have to. That's implementation specific, and could change at any time if another way was found to be far more efficient.
Either way, for
...in
carries with it no connotation of order. If you care about order, be explicit about it and use a regular for
loop with an index.
There was a bug, but it was fixed in the meantime. :host { }
works fine now.
Also supported are
:host(selector) { ... }
for selector
to match attributes, classes, ... on the host element:host-context(selector) { ... }
for selector
to match elements, classes, ...on parent components
selector /deep/ selector
(alias selector >>> selector
doesn't work with SASS) for styles to match across element boundaries
UPDATE: SASS is deprecating /deep/
.
Angular (TS and Dart) added ::ng-deep
as a replacement that's also compatible with SASS.
UPDATE2: ::slotted
::slotted
is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
See also Load external css style into Angular 2 Component
/deep/
and >>>
are not affected by the same selector combinators that in Chrome which are deprecated.
Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.
This is also why /deep/
and >>>
don't work with ViewEncapsulation.Native
which enables native shadow DOM and depends on browser support.
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.
You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.
Just adding my case here as well:
I was using angular-ui-router with $state.go('new_state', {foo: "foo@bar"})
Once I added encodeURIComponent to the parameter, the problem was gone: $state.go('new_state', {foo: encodeURIComponent("foo@bar")})
.
What happened? The character "@" in the parameter value is not allowed in URLs. As a consequence, angular-ui-router created my controller twice: during first creation it passed the original "foo@bar", during second creation it would pass the encoded version "foo%40bar". Once I explicitly encoded the parameter as shown above, the problem went away.
You are not initializing connection.That's why this kind of error is coming to you.
Your code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
Corrected code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);
I have seen many answers to this question and found some answer is lengthy and some answer is a little bit wrong. I have created my own code by using the above IDs and class.
$('#ckbCheckAll').click(function(){
if($(this).prop("checked")) {
$(".checkBoxClass").prop("checked", true);
} else {
$(".checkBoxClass").prop("checked", false);
}
});
$('.checkBoxClass').click(function(){
if($(".checkBoxClass").length == $(".checkBoxClass:checked").length) {
$("#ckbCheckAll").prop("checked", true);
}else {
$("#ckbCheckAll").prop("checked", false);
}
});
In the above code, where user clicks on select all checkbox and all checkbox will be selected and vice versa and second code will work when the user selects checkbox one by one then select all checkbox will be checked or unchecked according to a number of checkboxes checked.
Sometimes you have what appears to be a tuple with a leading underscore as in
def foo(bar):
return _('my_' + bar)
In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports
from sphinx.locale import l_, _
and in sphinx.locale, _() is assigned as an alias of some localization function.
IDP Initiated SSO
From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html
In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.
Processing Steps:
SP Initiated SSO
From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST
In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.
Processing Steps:
Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)
The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.
(Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.
An intuitive script: dplyr::select_if(~!all(is.na(.)))
. It literally keeps only not-all-elements-missing columns. (to delete all-element-missing columns).
> df <- data.frame( id = 1:10 , nas = rep( NA , 10 ) , vals = sample( c( 1:3 , NA ) , 10 , repl = TRUE ) )
> df %>% glimpse()
Observations: 10
Variables: 3
$ id <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
$ nas <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
$ vals <int> NA, 1, 1, NA, 1, 1, 1, 2, 3, NA
> df %>% select_if(~!all(is.na(.)))
id vals
1 1 NA
2 2 1
3 3 1
4 4 NA
5 5 1
6 6 1
7 7 1
8 8 2
9 9 3
10 10 NA
You can use Edit > Column Editor...
to insert text at the current and following lines. The shortcut is Alt + C.
There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime()
and TimeUnit.NANOSECONDS
as the time unit. Why should I do this? Well, it is because System.nanoTime()
method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
For the same reason, it is recommended to avoid the use of the System.currentTimeMillis()
method for measuring elapsed time. This method returns the wall-clock
time, which may change based on many factors. This will be negative for your measurements.
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
So here you have one solution based on the System.nanoTime()
method, another one using Guava, and the final one Apache Commons Lang
public class TimeBenchUtil
{
public static void main(String[] args) throws InterruptedException
{
stopWatch();
stopWatchGuava();
stopWatchApacheCommons();
}
public static void stopWatch() throws InterruptedException
{
long endTime, timeElapsed, startTime = System.nanoTime();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
endTime = System.nanoTime();
// get difference of two nanoTime values
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchGuava() throws InterruptedException
{
// Creates and starts a new stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // optional
// get elapsed time, expressed in milliseconds
long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchApacheCommons() throws InterruptedException
{
StopWatch stopwatch = new StopWatch();
stopwatch.start();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // Optional
long timeElapsed = stopwatch.getNanoTime();
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
}
After urlDecode processes the text, it replaces all '+' chars with ' ' ... thus the error. You should simply call this statement to make it base 64 compatible again:
sEncryptedString = sEncryptedString.Replace(' ', '+');
Assuming that by "binary code" you mean just plain old data (sequences of bits, or bytes), and that by "letters" you mean characters, the answer is in two steps. But first, some background.
Okay now here are the two steps:
The data, if it is textual, must be accompanied somehow by a character encoding, something like UTF-8, Latin-1, US-ASCII, etc. Each character encoding scheme specifies in great detail how byte sequences are interpreted as codepoints (and conversely how codepoints are encoded as byte sequences).
Once the byte sequences are interpreted as codepoints, you have your characters, because each character has a specific codepoint.
A couple notes:
In other words, not every byte sequence means something as text.
How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job.
public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable)
{
firstDataTable.Merge(secondDataTable);
return secondDataTable.GetChanges();
}
You can read more about DataTable.Merge()
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
In RMI, with regards to ports there are two distinct mechanisms involved:
By default, the RMI Registry uses port 1099
Client and server (stubs, remote objects) communicate over random ports unless a fixed port has been specified when exporting a remote object. The communcation is started via a socket factory which uses 0 as starting port, which means use any port that's available between 1 and 65535.
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
You could also use get()
:
test::where('id' ,'>' ,0)->get('id');
UPDATE: (For versions >= 5.2)
The lists()
method was deprecated in the new versions >= 5.2
, now you could use pluck()
method instead :
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
I have found another way of forcing re-run CI builds and other triggers:
git commit --amend --no-edit
without any changes. This will recreate the last commit in the current branch.git push --force-with-lease origin pr-branch
.To be more precise the shebang #!
, when it is the first two bytes of an executable (x
mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve
don't mention the shebang.
It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).
A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python
) in the user's $PATH
is to use the env
program (always at /usr/bin/env
on all Linux) like e.g.
#!/usr/bin/env python
Any ELF executable can be an interpreter. You could even use #!/bin/cat
or #!/bin/true
if you wanted to! (but that would be often useless)
Rename the output.config produced by svcutil.exe to app.config. it worked for me.
It sounds like you want to list all the metrics?
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2
If you only want one Criteria1+Criteria2 combination, group them:
SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
)
ORDER BY Criteria1, Criteria2
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.
A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.
It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProduct(Product product)
{
if (ModelState.IsValid)
{
//your logic
}
return View(ModelName);
}
It is derived from System.Web.Mvc namespace.
And in your view, add this code to add the token so it is used to validate the form upon submission.
@Html.AntiForgeryToken()
Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.
I looked into this before buying a Mac Mini. The answer is, essentially, no. You pretty much have to buy a Leopard Mac to do iPhone SDK development for apps that run on non-jailbroken iPhones.
Not that it's 100% impossible, but it's 99.99% unreasonable. Like changing light bulbs with your feet.
Not only do you have to be in Xcode, but you have to get certificates into the Keychain manager to be able to have Xcode and the iPhone communicate. And you have to set all kinds of setting in Xcode just right.
I was having this issue and fixed it by going to: C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2 , then deleting collect2.exe
As mentioned in Gillian's answer, assigning none
to content
solves the problem:
p::after {
content: none;
}
Note that in CSS3, W3C recommended to use two colons (::
) for pseudo-elements like ::before
or ::after
.
From the MDN web doc on Pseudo-elements:
Note: As a rule, double colons (
::
) should be used instead of a single colon (:
). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the sake of compatibility. Note that::selection
must always start with double colons (::
).
Instant.now()
The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
An Instant
represents a moment on the timeline in UTC with a resolution of up to nanoseconds.
Instant instant = Instant.now();
The toString
method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.
String output = instant.toString();
2016-06-27T19:15:25.864Z
The Instant
class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.
OffsetDateTime
But Instant
has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant
to OffsetDateTime
. Specify an offset-from-UTC. In java.time that means a ZoneOffset
object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
2016-06-27T19:15:25.864Z
Or skip the Instant
class.
OffsetDateTime.now( ZoneOffset.UTC )
Now with an OffsetDateTime
object in hand, you can use DateTimeFormatter
to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter
.
ZonedDateTime
When you want to display wall-clock time for some particular time zone, apply a ZoneId
to get a ZonedDateTime
.
In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00
. So note how the time-of-day is four hours earlier in the output, 15
instead of 19
hours. Instant
and the ZonedDateTime
both represent the very same simultaneous moment, just viewed through two different lenses.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
2016-06-27T15:15:25.864-04:00[America/Montreal]
While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant )
and java.util.Date::toInstant
.
java.util.Date utilDate = java.util.Date.from( instant );
And going the other direction.
Instant instant= utilDate.toInstant();
Similarly, look for new methods added to GregorianCalendar
(subclass of Calendar
) to convert to and from java.time.ZonedDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Remove all listeners in element by one js line:
element.parentNode.innerHTML += '';
Using ASP.Net Post call, this worked for me.
StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
var values = new Dictionary<string, string>
{
{ "client_id", <Your Client Id> },
{ "client_secret", <Your Client Secret> },
{ "refresh_token", <Your Saved Refresh Token> },
{ "grant_type", "refresh_token"}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(getNewToken.ToString(), content);
You can use this simple plugin to add scrollUp
and scrollDown
to your jQuery
https://github.com/phpust/JQueryScrollDetector
var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {
$(this).scroll(function(){
// get current scroll top
var st = $(this).scrollTop();
var $this = $(this);
// fix for page loads
if (lastScrollTop !=0 )
{
// if it's scroll up
if (st < lastScrollTop){
action = "scrollUp";
}
// else if it's scroll down
else if (st > lastScrollTop){
action = "scrollDown";
}
}
// set the current scroll as last scroll top
lastScrollTop = st;
// check if scrollTimeout is set then clear it
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
// wait until timeout done to overwrite scrolls output
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
$(window).scrollEnd(function(){
if(action!="stopped"){
//call the event listener attached to obj.
$(document).trigger(action);
}
}, timeout);
use <br/>
tag
Example:
<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>
Go to Hbase home directory and run this command,
./bin/hbase org.apache.hadoop.hbase.mapreduce.RowCounter 'namespace:tablename'
This will launch a mapreduce job and the output will show the number of records existing in the hbase table.
Reducing the RAM size in the AVD settings worked for me. The AVD being slow can eat up a lot of RAM, so keeping it at a minimum is feasible.
how about this:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
You can simply add DISTINCT in front.
SELECT GROUP_CONCAT(DISTINCT categories SEPARATOR ' ')
if you want to sort,
SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ')
You can just create an Image
object and put the base64 as its src
, including the data:image...
part like this:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
It's what they call "Data URIs" and here's the compatibility table for inner peace.
You can also force to table columns in table using force: true
, if you table is already exist.
example:
ActiveRecord::Schema.define(version: 20080906171750) do
create_table "authors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
You can use aggregate to calculate the means:
means<-aggregate(df,by=list(df$gender),mean)
Group.1 tea coke beer water gender
1 1 87.70171 27.24834 24.27099 37.24007 1
2 2 24.73330 25.27344 25.64657 24.34669 2
Get rid of the Group.1 column
means<-means[,2:length(means)]
Then you have reformat the data to be in long format:
library(reshape2)
means.long<-melt(means,id.vars="gender")
gender variable value
1 1 tea 87.70171
2 2 tea 24.73330
3 1 coke 27.24834
4 2 coke 25.27344
5 1 beer 24.27099
6 2 beer 25.64657
7 1 water 37.24007
8 2 water 24.34669
Finally, you can use ggplot2 to create your plot:
library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
geom_bar(stat="identity",position="dodge")+
scale_fill_discrete(name="Gender",
breaks=c(1, 2),
labels=c("Male", "Female"))+
xlab("Beverage")+ylab("Mean Percentage")
You can use the flatCollect()
pattern from Eclipse Collections.
MutableList<List<Object>> list = Lists.mutable.empty();
MutableList<Object> flat = list.flatCollect(each -> each);
If you can't change list from List
:
List<List<Object>> list = new ArrayList<>();
List<Object> flat = ListAdapter.adapt(list).flatCollect(each -> each);
Note: I am a contributor to Eclipse Collections.
When We Add First Fragment --> Second Fragment using add() method
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click First
Fragment",Toast.LENGTH_LONG).show();
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
// .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
});
When we use add() in fragment
E/Keshav SecondFragment: onAttach
E/Keshav SecondFragment: onCreate
E/Keshav SecondFragment: onCreateView
E/Keshav SecondFragment: onActivityCreated
E/Keshav SecondFragment: onStart
E/Keshav SecondFragment: onResume
When we use replace() in fragment
going to first fragment to second fragment in First -->Second using replace() method
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click First Fragment",Toast.LENGTH_LONG).show();
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
// .add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
});
E/Keshav SecondFragment: onAttach
E/Keshav SecondFragment: onCreate
E/Keshav FirstFragment: onPause -------------------------- FirstFragment
E/Keshav FirstFragment: onStop --------------------------- FirstFragment
E/Keshav FirstFragment: onDestroyView -------------------- FirstFragment
E/Keshav SecondFragment: onCreateView
E/Keshav SecondFragment: onActivityCreated
E/Keshav SecondFragment: onStart
E/Keshav SecondFragment: onResume
In case of Replace First Fragment these method is extra called ( onPause,onStop,onDestroyView is extra called )
E/Keshav FirstFragment: onPause
E/Keshav FirstFragment: onStop
E/Keshav FirstFragment: onDestroyView
swift 3
pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'
File json format:
{
"codeAd": {
"dateExpire": "2017/12/11",
"codeRemoveAd":"1231243134"
}
}
import Alamofire
import SwiftyJSON
private func downloadJson() {
Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
debugPrint(response)
if let json = response.data {
let data = JSON(data: json)
print("data\(data["codeAd"]["dateExpire"])")
print("data\(data["codeAd"]["codeRemoveAd"])")
}
}
}
You can try this, it is fully customizable.
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
child: SizedBox(width: 56, height: 56, child: Icon(Icons.menu)),
onTap: () {},
),
),
)
Output:
You have the following options:
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace('want', 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"_x000D_
console.log(new_text)
_x000D_
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace(/want/g, 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well_x000D_
console.log(new_text)
_x000D_
var text = "this is some sample text that i want to replace and this i WANT to replace as well.";_x000D_
var new_text = text.replace(/want/gi, 'dont want');_x000D_
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well_x000D_
console.log(new_text)
_x000D_
More info -> here
Try this:
true
select cast(salesDate as date) [date] from sales where salesDate = '2010/11/11'
false
select cast(salesDate as date) [date] from sales where salesDate = '11/11/2010'
Below command worked for me docker build -t docker-whale -f Dockerfile.txt .
var xxx = require("../lib/your-library.js")
or
import xxx from "../lib/your-library.js" //get default export
import {specificPart} from '../lib/your-library.js' //get named export
import * as _name from '../lib/your-library.js' //get full export to alias _name
Here is how to do it using TCP IP protocol :
// Printer IP Address and communication port
string ipAddress = "10.3.14.42";
int port = 9100;
// ZPL Command(s)
string ZPLString =
"^XA" +
"^FO50,50" +
"^A0N50,50" +
"^FDHello, World!^FS" +
"^XZ";
try
{
// Open connection
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
client.Connect(ipAddress, port);
// Write ZPL String to connection
System.IO.StreamWriter writer =
new System.IO.StreamWriter(client.GetStream());
writer.Write(ZPLString);
writer.Flush();
// Close Connection
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
Source : ZEBRA WEBSITE
For micro-optimisation freaks:
if ($num % 6 != 0)
$num += 6 - $num % 6;
More evaluations of %
, but less branching/looping. :-P
Better yet, consider sp_getapplock
which is designed for this. Or use SET LOCK_TIMEOUT
Otherwise, you'd have to do something with sys.dm_tran_locks
which I'd use only for DBA stuff: not for user defined concurrency.
You can also use INT_MAX:
http://www.cplusplus.com/reference/climits/
it's equivalent to using numeric_limits.
At a company where I used to work we stored 155 million images in an Oracle 8i (then 9i) database. 7.5TB worth.
You can simply try it with a jenkinsfile. Create a Jenkins job with following pipeline script.
pipeline {
agent any
parameters {
booleanParam(defaultValue: true, description: '', name: 'userFlag')
}
stages {
stage('Trigger') {
steps {
script {
println("triggering the pipeline from a rest call...")
}
}
}
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
}
}
}
}
Build the job once manually to get it configured & just create a http POST request to the Jenkins job as follows.
The format is http://server/job/myjob/buildWithParameters?PARAMETER=Value
curl http://admin:test123@localhost:30637/job/apd-test/buildWithParameters?userFlag=false --request POST
scp file user@host:/path/on/host
Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.
Try like below with Gson
Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
Try this:
$('#ddlCodes').change(function() {
var option = this.options[this.selectedIndex];
$('#txtEntry2').text($(option).text());
});
If you can't use JodaTime, you can do the following:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.
You don't even need to cast, it is implicit.
int i = 3;
float f = i;
A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
You can just pass it
def my_function(my_data):
my_data["schoolname"] = "something"
print my_data
or if you really want to
def my_function(**kwargs):
kwargs["schoolname"] = "something"
print kwargs
Try this piece of code:
try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);
String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);
String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}
The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).
All you have to do add .reset_index(inplace=True)
after the name of the DataFrame:
df.reset_index(inplace=True)
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
Use LayoutParams. If you are using a LinearLayout you have to import android.widget.LinearLayout.LayoutParams, else import the proper version of LayoutParams for the layout you're using, or it will cause a ClassCastException, then:
LayoutParams layoutParams = new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
NB: Note that you can use also imageView.setLeft(int dim), BUT THIS WON'T set the position of the component, it will set only the position of the left border of the component, the rest will remain at the same position.
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
Another approach is to add a toString()
method to your Car
class and just let the toString()
method of ArrayList do all the work.
@Override
public String toString()
{
return "Car{" +
"make=" + make +
", registration='" + registration + '\'' +
'}';
}
You don't get one car per line in the output, but it is quick and easy if you just want to see what is in the array.
List<Car> cars = c1.getAll();
System.out.println(cars);
Output would be something like this:
[Car{make=FORD, registration='ABC 123'},
Car{make=TOYOTA, registration='ZYZ 999'}]
well i might be late on this but i would like to share something:
Given the input: System.out.println(isGreaterThanZero(-1));
public static boolean isGreaterThanZero(Integer value) {
return value == null?false:value.compareTo(0) > 0;
}
Returns false
public static boolean isGreaterThanZero(Integer value) {
return value == null?false:value.intValue() > 0;
}
Returns true So i think in yourcase 'compareTo' will be more accurate.
Try this, but i don't sure that will work every where :)
public enum MyEnum {
A("Start There"),
B("Start Here");
MyEnum(String name) {
try {
Field fieldName = getClass().getSuperclass().getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(this, name);
fieldName.setAccessible(false);
} catch (Exception e) {}
}
}
Pass an argument to round containing the number of decimal places to round to
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
this is one of the ways you can use this function, it is when you want access a variable of another class and change the output based on that variable.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let something = segue.destination as! someViewController
something.aVariable = anotherVariable
}
Another alternative to simulating a F5 key press would be to simply host the WebBrowser control in the Window Forms application. You use the WebBrowser.Navigate method to load your web page and then use a standard Timer and on each tick of the timer you just re-Navigate to the url which will reload the page.
For the text color add:
android:textColor="<hex color>"
For the background color add:
android:background="<hex color>"
From API 21 you can use:
android:backgroundTint="<hex color>"
android:backgroundTintMode="<mode>"
Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
Assuming, as seems to be the case, ${triningIdArray}
is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
For whom is using GitLab runners:
./gitlab-runner.exe install --user ".\ENTER-YOUR-USERNAME" --password "ENTER-YOUR-PASSWORD"
(I had to stop and uninstall first)sn -i certificate.pfx VS_KEY_C***6
the container name is suggested in the failed Job output on GitLab (msbuild output)
What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.
Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.
The return value of os.system
is OS-dependant.
On Unix, the return value is a 16-bit number that contains two different pieces of information. From the documentation:
a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)
So if the signal number (low byte) is 0, it would, in theory, be safe to shift the result by 8 bits (result >> 8
) to get the error code. The function os.WEXITSTATUS
does exactly this. If the error code is 0, that usually means that the process exited without errors.
On Windows, the documentation specifies that the return value of os.system
is shell-dependant. If the shell is cmd.exe
(the default one), the value is the return code of the process. Again, 0 would mean that there weren't errors.
For others error codes:
I have same issue . it's solved my problem . If you init your git . you have to do on Terminal
1) git add .
2)git commit -m "first commit"
For send to bitbucket
3) git push -u origin --all # pushes up the repo and its refs for the first time
WOW, I gotta say: keep it simple:
MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));
Result: True
and:
MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));
Result: 10.00:00:00
The DateTime object has all the builtin logic to handle the Boolean result.
There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor)
and .AddFromFile(Filename)
. Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile
because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.
The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)
If you are having problems getting the code to run, there are two possible issues.
Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
As a similar approach to the accepted answer that might be considered a bit more readable, elegant, and general (YMMV), you can leverage the map
method:
# OP example
df['var3'].map(lambda n: '{:,.2%}'.format(n))
# also works on a series
series_example.map(lambda n: '{:,.2%}'.format(n))
Performance-wise, this is pretty close (marginally slower) than the OP solution.
As an aside, if you do choose to go the pd.options.display.float_format
route, consider using a context manager to handle state per this parallel numpy example.
Here's another version of XMLillies w/ domi's LI change that uses a search string instead of a path level. I think this is a little more obvious what's happening for my use case.
statsApp.directive('activeTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
if (attrs.href!=undefined) { // this directive is called twice for some reason
// The activeTab attribute should contain a path search string to match on.
// I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
if ($location.path().indexOf(attrs.activeTab) >= 0) {
element.parent().addClass("active");//parent to get the <li>
} else {
element.parent().removeClass("active");
}
}
});
}
};
});
HTML now looks like:
<ul class="nav nav-tabs">
<li><a href="#/news" active-tab="/news">News</a></li>
<li><a href="#/some/nested/photos/rawr" active-tab="/photos">Photos</a></li>
<li><a href="#/contact" active-tab="/contact">Contact</a></li>
</ul>
Start Activity2 with startActivityForResult
and use setResult
method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult
for updating TextView
with EditText
data from Activity2.
For example:
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult
for sending data back:
Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult
:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strEditText = data.getStringExtra("editTextValue");
}
}
}
If you can, also use SharedPreferences for sharing data between Activities.
I faced with the same problem and this worked.
Controller
return Redirect::back()->withInput()->withErrors(array('user_name' => $message));
View
<div>{{{ $errors->first('user_name') }}}</div>
I was trying the white-space: pre-wrap;
technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre>
tags and the following css and everything was good to go..
pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}
We can maintain dynamic height for collection view cell without xib(only using storyboard).
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:@"Your long string goes here" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]}];
CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return CGSizeMake(cellWidth, cellRect.size.height);
}
Make sure that numberOfLines in IB should be 0.
There are some good answers for it. I want to explain it through demo per Doc
CMD
defines default commands and/or parameters for a container. CMD is an instruction that is best to use if you need a default command which users can easily override. If a Dockerfile has multiple CMDs, it only applies the instructions from the last one.ENTRYPOINT
is preferred when you want to define a container with a specific executable.You cannot override an ENTRYPOINT
when starting a container unless you add the --entrypoint
flag.
Docker file
FROM centos:8.1.1911
CMD ["echo", "Hello Docker"]
Run result
$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname # hostname is exec to override CMD
244be5006f32
Docker file
FROM centos:8.1.1911
ENTRYPOINT ["echo", "Hello Docker"]
Run result
$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname # hostname as parameter to exec
Hello Docker hostname
Docker file
FROM centos:8.1.1911
ENTRYPOINT ["echo", "Hello"]
CMD ["Docker"]
Run result
$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> Ben
Hello Ben
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
Try with these commands that have been useful with those errors
path\project\storage\framework\views...
php artisan view:clear
path\project\storage\framework/sessions...
php artisan config:cache
Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.
Have a look at XPCOM, there might be something that you can use if Firefox 3 is used by a client.
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
I've recently started using IntelliJ on my projects. However, some of my colleagues still use Eclipse on the same projects. Today, I've got the very same error after executing the jar-file created by my IntelliJ. While all the solutions in here talking about almost the same thing, none of them worked for me easily (possibly because I don't use ANT, maven build gave me other errors which referred me to http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException, and also I couldn't figure out what are the signed jars by myself!)
Finally, this helped me
zip -d demoSampler.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*SF'
Guess what's been removed from my jar file?!
deleting: META-INF/ECLIPSE_.SF
deleting: META-INF/ECLIPSE_.RSA
It seems that the issue was relevant to some eclipse-relevant files.
I solved this problem by using: chown -R etc/asterisk chown -R var/lib/asterisk
this is bacause, as said here, I wasn't running as administrator. So, I made my user as owner of the Asterisk directories.
Solution: Give up!
Hear me out, I spent about two whole days trying to make MySQL work to no avail, always stuck with permission errors, none of which were fixed by the answers in this thread. It got to the point that I thought if I continued I'd go insane.
Out of patience for making it work, I sent the command to install SQLite, only using 450KB, and it worked perfectly right from the word go.
If you don't have the patience of a saint, go with SQLite and save yourself a lot of time, effort, pain, and storage space..!
Another option is using eval and parse, as in
d = 5
for (i in 1:10){
eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}
It depends what you're going for. I believe the closest thing JS has to print is:
document.write( produceMessage() );
However, it may be more prudent to place the value inside a span or a div of your choosing like:
document.getElementById("mySpanId").innerHTML = produceMessage();
Alternatively you can also,
1) Navigate to that method by Ctrl+Click on the method. The new tab/window will opened with text "Source not found" and button "Attach Source.." in it
2) Click the button "Attach Source.."
3) New window pops up. Click the button "External Folder"
4) Locate the JavaFX javadoc folder. If you are on Windows with default installation settings, then the folder path is C:\Program Files\Oracle\JavaFX 2.0 SDK\docs
Auto detect your proxy settings and inject them in all your vagrant VM
install the proxy plugin
vagrant plugin install vagrant-proxyconf
add this conf to you private/user VagrantFile (it will be executed for all your projects) :
vi $HOME/.vagrant.d/Vagrantfile
Vagrant.configure("2") do |config|
puts "proxyconf..."
if Vagrant.has_plugin?("vagrant-proxyconf")
puts "find proxyconf plugin !"
if ENV["http_proxy"]
puts "http_proxy: " + ENV["http_proxy"]
config.proxy.http = ENV["http_proxy"]
end
if ENV["https_proxy"]
puts "https_proxy: " + ENV["https_proxy"]
config.proxy.https = ENV["https_proxy"]
end
if ENV["no_proxy"]
config.proxy.no_proxy = ENV["no_proxy"]
end
end
end
now up your VM !
If you need to use trim in select query, you can also use regular expressions
SELECT * FROM table_name WHERE field RLIKE ' * query-string *'
return rows with field like ' query-string '
Why cant we just use eval()?
def install():
print "In install"
New method
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
And then you call the method as below
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
This gives the output as
In install
In install with options a b
This will take care of the empty td:
<td style="min-width: 20px;"></td>
A lot contributions on this thread already, just summarize a sequence diagram to illustrate it in another way.
The is also a good link about this topic, https://web.stanford.edu/~ouster/cgi-bin/cs142-fall10/lecture.php?topic=cookie
Probably I have found myself:
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
In XCode 7 you can update your bundle identifier by double clicking your target and changing the name.
Difference between each annotation are :
+-------------------------------------------------------------------------------------------------------+
¦ Feature ¦ Junit 4 ¦ Junit 5 ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed. ¦ @BeforeClass ¦ @BeforeAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some initialization code ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class. ¦ @AfterClass ¦ @AfterAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some cleanup code. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method. ¦ @Before ¦ @BeforeEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to reinitialize some class attributes used by the methods. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method. ¦ @After ¦ @AfterEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to roll back database modifications. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
Most of annotations in both versions are same, but few differs.
Order of Execution.
Dashed box -> optional annotation.
I'm pretty sure you shouldn't need to set a position:
$("#dialog").dialog();
I did have a look at the article, and also checked what it says on the official jquery-ui site about positioning a dialog : and in it were discussed 2 states of: initialise and after initialise.
Code examples - (taken from jQuery UI 2009-12-03)
Initialize a dialog with the position option specified.
$('.selector').dialog({ position: 'top' });
Get or set the position option, after init.
//getter
var position = $('.selector').dialog('option', 'position');
//setter
$('.selector').dialog('option', 'position', 'top');
I think that if you were to remove the position attribute you would find it centers by itself else try the second setter option where you define 3 elements of "option" "position" and "center".
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
jScrollPane is a good solution to cross browser scrollbars and degrades nicely.
Here you go:
https://support.google.com/docs/answer/3093281
This is all the documentation that Google provides.
Another way to download file is to write the stream content to the response's body directly:
[HttpGet("pdfstream/{id}")]
public async Task GetFile(long id)
{
var stream = GetStream(id);
Response.StatusCode = (int)HttpStatusCode.OK;
Response.Headers.Add( HeaderNames.ContentDisposition, $"attachment; filename=\"{Guid.NewGuid()}.pdf\"" );
Response.Headers.Add( HeaderNames.ContentType, "application/pdf" );
await stream.CopyToAsync(Response.Body);
await Response.Body.FlushAsync();
}
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.
The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.
-a "From: Foo Bar <[email protected]>"
You can add Apache Commons Lang
in Gradle like compile 'org.apache.commons:commons-lang3:3.4'
And use WordUtils.capitalizeFully(name)
Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.
PowerShell - List local user accounts
Fast way
Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | select name, fullname
Slow way
Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname
From here and here: (after i googled your title)
- Alternate key - An alternate key is any candidate key which is not selected to be the primary key
- Candidate key - A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table.
- Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes.
- Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book). In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation.
- Superkey - A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
- Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization
The only good way I found was to use Javascript to move a tooltip <div>
around. Obviously this only works if you have SVG inside an HTML document - not standalone. And it requires Javascript.
function showTooltip(evt, text) {_x000D_
let tooltip = document.getElementById("tooltip");_x000D_
tooltip.innerHTML = text;_x000D_
tooltip.style.display = "block";_x000D_
tooltip.style.left = evt.pageX + 10 + 'px';_x000D_
tooltip.style.top = evt.pageY + 10 + 'px';_x000D_
}_x000D_
_x000D_
function hideTooltip() {_x000D_
var tooltip = document.getElementById("tooltip");_x000D_
tooltip.style.display = "none";_x000D_
}
_x000D_
#tooltip {_x000D_
background: cornsilk;_x000D_
border: 1px solid black;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
}
_x000D_
<div id="tooltip" display="none" style="position: absolute; display: none;"></div>_x000D_
_x000D_
<svg>_x000D_
<rect width="100" height="50" style="fill: blue;" onmousemove="showTooltip(evt, 'This is blue');" onmouseout="hideTooltip();" >_x000D_
</rect>_x000D_
</svg>
_x000D_
POSTMAN : A google chrome extension
Use postman to send message instead of server. Postman settings are as follows :
Request Type: POST
URL: https://android.googleapis.com/gcm/send
Header
Authorization : key=your key //Google API KEY
Content-Type : application/json
JSON (raw) :
{
"registration_ids":["yours"],
"data": {
"Hello" : "World"
}
}
on success you will get
Response :
{
"multicast_id": 6506103988515583000,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1432811719975865%54f79db3f9fd7ecd"
}
]
}
A keystore contains private keys, and the certificates with their corresponding public keys.
A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.
You can achieve by this RunTime Attributes
we can make custom button.just see screenshot attached.
kindly pay attention :
in runtime attributes to change color of border follow this instruction
create category class of CALayer
in h file
@property(nonatomic, assign) UIColor* borderIBColor;
in m file:
-(void)setBorderIBColor:(UIColor*)color {
self.borderColor = color.CGColor;
}
-(UIColor*)borderIBColor {
return [UIColor colorWithCGColor:self.borderColor];
}
now onwards to set border color check screenshot
thanks
git fsck --unreachable | grep commit
should show the sha1, although the list it returns might be quite large. git show <sha1>
will show if it is the commit you want.
git cherry-pick -m 1 <sha1>
will merge the commit onto the current branch.
I was getting this exception and the "solution" I found was through Netbeans IDE, simply:
I don't know WHY this worked, but it did!
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
First I added a to_dict method to my model ;
def to_dict(self):
return {"name": self.woo, "title": self.foo}
Then I have this;
class DjangoJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, models.Model):
return obj.to_dict()
return JSONEncoder.default(self, obj)
dumps = curry(dumps, cls=DjangoJSONEncoder)
and at last use this class to serialize my queryset.
def render_to_response(self, context, **response_kwargs):
return HttpResponse(dumps(self.get_queryset()))
This works quite well
it would be great if somebody told to put gif into any folder instead of assets folder
You can't do this directly. However, you can use Linq to do this:
List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();
If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:
List<int> termsLst = terms.ToList();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
terms = termsLst.ToArray();
Note: don't miss adding 'using System.Linq;' at the begaining of the file.
let path = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
Resorting to using .htaccess
to rewrite the URLs for static HTML is generally not only unnecessary, but also bad for you website's performance. Enabling .htaccess
is also an unnecessary security vulnerability - turning it off eliminates a significant number of potential issues. The same rules for each .htaccess
file can instead go in a <Directory>
section for that directory, and it will be more performant if you then set AllowOverride None
because it won't need to check each directory for a .htaccess
file, and more secure because an attacker can't change the vhost config without root access.
If you don't need .htaccess
in a VPS environment, you can disable it entirely and get better performance from your web server.
All you need to do is move your individual files from a structure like this:
index.html
about.html
products.html
terms.html
To a structure like this:
index.html
about/index.html
products/index.html
terms/index.html
Your web server will then render the appropriate pages - if you load /about/
, it will treat that as /about/index.html
.
This won't rewrite the URL if anyone visits the old one, though, so it would need redirects to be in place if it was retroactively applied to an existing site.
(Not everyone likes doing things through the git command line interface)
Once this has been set up, you only need to do steps 7-13 from then on.
Fetch > checkout master branch > reset to their master > Push changes to server
Double click on your "master" branch to check it out if it is not checked out already.
Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.
Right click on the commit > "Reset current branch to this commit".
In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).
Your Done!
To show the values from 2 tables in a pre-defined way, use a VIEW
autoconf
and automake
:configure
, make
and sudo make install
:./configure # Creates Makefile (from Makefile.in).
make # Creates the application (from the Makefile just created).
sudo make install # Installs the application
# Often, by default its files are installed into /usr/local
Notation below is roughly: inputs --> programs --> outputs
DEVELOPER runs these:
configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in
depreciated. Use configure.ac)
Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)
INSTALLER runs these:
Makefile.in -> configure -> Makefile (*.in = input file)
Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)
"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."
"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."
Manuals:
GNU AutoTools (The definitive manual on this stuff)
m4 (used by autoconf)
Free online tutorials:
The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)
From this my generated configure is over 41k lines of code.
And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)
You can also do:
echo "hello
world"
This works both inside a script and from the command line.
In the command line, press Shift+Enter to do the line breaks inside the string.
This works for me on my macOS and my Ubuntu 18.04
If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.
In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).
If you suspect a memory leak, use a profiler to find which object occupies all the available memory.
To disable the complete select2 box, that is no deletion of already selected values and no new insertion, use:
$("id-select2").prop("disabled", true);
where id-select2
is the unique id of select2. you can also use any particular class if defined to address the dropdown.
However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.
if you are like me, simply add
"use Response;"
above your class ...extends contoller. this should do.
with this you can now use:
$response = Response::json($posts, 200);
instead of:
$response = \Response::json($posts, 200);
I tried this and it worked :
git stash && git add . && git stash pop
git stash
will only put all modified tracked files into separate stack, then left over files are untracked files. Then by doing git add .
will stage all files untracked files, as required. Eventually, to get back all modified files from stack by doing git stash pop
Just here to show my implementation for @herman solution
ZoneId americaLaPazZone = ZoneId.of("UTC-04:00");
static Date firstDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime initialDate = baseMonth.atDay(firstDayOfMonth).atStartOfDay();
return Date.from(initialDate.atZone(americaLaPazZone).toInstant());
}
static Date lastDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime lastDate = baseMonth.atEndOfMonth().atTime(23, 59, 59);
return Date.from(lastDate.atZone(americaLaPazZone).toInstant());
}
static LocalDate convertToLocalDateWithTimezone(Date date) {
return LocalDateTime.from(date.toInstant().atZone(americaLaPazZone)).toLocalDate();
}
You can't put a border on a tr element. This worked for me in firefox and IE 11:
<td style='border-bottom:1pt solid black'>
Simple solution if your are using express and doing
const router = express.Router();
make sure to
module.exports = router ;
at the end of your page
docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)
-f force
-a all
-q in the mode
One of the simplest way is to use flatten()
, like this example :
import numpy as np
batch_y =train_output.iloc[sample, :]
batch_y = np.array(batch_y).flatten()
My array it was like this :
0
0 6
1 6
2 5
3 4
4 3
.
.
.
After using flatten()
:
array([6, 6, 5, ..., 5, 3, 6])
It's also the solution of errors of this type :
Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)'
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
You need to remove the scanner closing lines: scan.close();
It happened to me before and that was the reason.
Easiest way, especially if in MSDN,,wasted hours of my time, stupid MS
http://support.microsoft.com/kb/2900662/en-us?sd=rss
Move points into test:
def test():
points = 0
addpoint = raw_input ("type ""add"" to add a point")
...
or use global statement, but it is bad practice. But better way it move points to parameters:
def test(points=0):
addpoint = raw_input ("type ""add"" to add a point")
...
The singular form dtype
is used to check the data type for a single column. And the plural form dtypes
is for data frame which returns data types for all columns. Essentially:
For a single column:
dataframe.column.dtype
For all columns:
dataframe.dtypes
Example:
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')
df.dtypes
#A int64
#B bool
#C object
#dtype: object
I got here because I wanted to create a range between -10 and 10 in increments of 0.1 using list comprehension. Instead of doing an overly complicated function like most of the answers above I just did this
simple_range = [ x*0.1 for x in range(-100, 100) ]
By changing the range count to 100 I now get my range of -10 through 10 by using the standard range function. So if you need it by 0.2 then just do range(-200, 200) and so on etc
You should read that, it's still valid.
You'll adapt the function you use depending on your needs.
Basically:
if you already load all entries, say User.all
, then you should use length
to avoid another db query
if you haven't anything loaded, use count
to make a count query on your db
if you don't want to bother with these considerations, use size
which will adapt
Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:
driver.manage().timeouts().implicitlyWait( ... )
I think this is what you want:
document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';
Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)
Class re-declaration will be the problem. check duplicate class and build.
There are many possible pitfalls for writing micro-benchmarks in Java.
First: You have to calculate with all sorts of events that take time more or less random: Garbage collection, caching effects (of OS for files and of CPU for memory), IO etc.
Second: You cannot trust the accuracy of the measured times for very short intervals.
Third: The JVM optimizes your code while executing. So different runs in the same JVM-instance will become faster and faster.
My recommendations: Make your benchmark run some seconds, that is more reliable than a runtime over milliseconds. Warm up the JVM (means running the benchmark at least once without measuring, that the JVM can run optimizations). And run your benchmark multiple times (maybe 5 times) and take the median-value. Run every micro-benchmark in a new JVM-instance (call for every benchmark new Java) otherwise optimization effects of the JVM can influence later running tests. Don't execute things, that aren't executed in the warmup-phase (as this could trigger class-load and recompilation).