You have a multiple options:
First, you can use kill. But you need the pid of your process, which you can get by using ps, pidof or pgrep.
ps -A // to get the pid, can be combined with grep
-or-
pidof <name>
-or-
pgrep <name>
kill <pid>
It is possible to kill a process by just knowing the name. Use pkill or killall.
pkill <name>
-or-
killall <name>
All commands send a signal to the process. If the process hung up, it might be neccessary to send a sigkill to the process (this is signal number 9, so the following examples do the same):
pkill -9 <name>
pkill -SIGKILL <name>
You can use this option with kill
and killall
, too.
Read this article about controlling processes to get more informations about processes in general.
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
I tried pretty much all the suggestions made here but none worked. For us the issue was temperamental and became worse and worse the larger the repos became (on our Jenkins Windows build slave).
It ended up being the version of ssh being used by git. Git was configured to use some version of Open SSH, specified in the users .gitconfig file via the core.sshCommand variable. Removing that line fixed it. I believe this is because Windows now ships with a more reliable / compatible version of SSH which gets used by default.
white-space: nowrap;
: Will never break text, will keep other defaults
white-space: pre;
: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
Bootstrap 3.1.1 has a .center-block
class for centering divs. See: http://getbootstrap.com/css/#helper-classes-center.
Center content blocks Set an element to
display: block
and center viamargin
. Available as a mixin and class.
<div class="center-block">...</div>
Or, as others have already said, use the .text-center
class to centre text.
# THIS WORK FOR ME
# Get all diferent values
df3 = pd.merge(df1, df2, how='outer', indicator='Exist')
df3 = df3.loc[df3['Exist'] != 'both']
# If you like to filter by a common ID
df3 = pd.merge(df1, df2, on="Fruit", how='outer', indicator='Exist')
df3 = df3.loc[df3['Exist'] != 'both']
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
Open the Windows > Preferences menu.
Expand the Run/Debug > Console preferences.
Set the Console buffer size (characters)
to something much bigger. 2147383647
/ ~2GB is the upper limit (or 1000000
/ ~1MB in older releases). Or just uncheck the Limit console output
.
Go to Project-><Projectname> Properties
. Then click on the Debug
tab, and fill in your arguments in the textbox called Command line arguments
.
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
I've extended the accepted answer a little using Swift's extension functionality as well as an enum.
Oh and if you are using Storyboard like I do, make sure to call gradientBackground(from:to:direction:)
in viewDidLayoutSubviews()
or later.
Swift 3
enum GradientDirection {
case leftToRight
case rightToLeft
case topToBottom
case bottomToTop
}
extension UIView {
func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [color1.cgColor, color2.cgColor]
switch direction {
case .leftToRight:
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
case .rightToLeft:
gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
case .bottomToTop:
gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
default:
break
}
self.layer.insertSublayer(gradient, at: 0)
}
}
-a option?
Cf. man page:
-a file
Attach the given file to the message.
Result:
Content-Type: text/html: No such file or directory
I had this same issue with dynamic tables. (Tables that are assumed to have an id to be able to join but without any assumption for the rest of the fields.) In this case you don't know the aliases before hand.
In such cases you can first get the table column names for all dynamic tables:
$tblFields = array_keys($zendDbInstance->describeTable($tableName));
Where $zendDbInstance is an instance of Zend_Db or you can use one of the functions here to not rely on Zend php pdo: get the columns name of a table
Then for all dynamic tables you can get the aliases and use $tableName.* for the ones you don't need aliases:
$aliases = "";
foreach($tblKeys as $field)
$aliases .= $tableName . '.' . $field . ' AS ' . $tableName . '_' . $field . ',' ;
$aliases = trim($aliases, ',');
You can wrap this whole process up into one generic function and just have cleaner code or get more lazy if you wish :)
i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
The only way I've figured out how to do this is to have two properties for my class. One as the boolean for the programming API which is not included in the mapping. It's getter and setter reference a private char variable which is Y/N. I then have another protected property which is included in the hibernate mapping and it's getters and setters reference the private char variable directly.
EDIT: As has been pointed out there are other solutions that are directly built into Hibernate. I'm leaving this answer because it can work in situations where you're working with a legacy field that doesn't play nice with the built in options. On top of that there are no serious negative consequences to this approach.
Looks like this trick works in SQL Server and is shorter (based in previous answers)
SELECT 1.0*MyInt1/MyInt2
Or:
SELECT (1.0*MyInt1)/MyInt2
SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort
class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.
Example Code:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:
x <- character(10)
document.body.innerHTML = '';
does clear the body
, yeah. But it clears the innerHTML
as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body
, it tries to clear the body
, but there's nothing to clear.
If you want to clear the body
, you have to run the code after the body
has been filled with content. You can do this by either placing the <script>
block as the last child of body
, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded
event.
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
I found that as of May, 2012, if you set the frame size so that the minimum pixel area (width • height) is above a certain threshold, it bumps the quality up from 360p to 480p, if you're video is at least 640 x 360.
I've discovered that setting a frame size to 780 x 480 for the embed frame triggers the 480p quality, without distorting the video (scaling up). 640 x 585 also works in this manner. I also used the &hd=1
parameter, but I doubt this has much control if your video is not uploaded in HD (720p or higher).
For instance:
<iframe width="780" height="480" src="http://www.youtube.com/embed/[VIDEO-ID]?rel=0&fs=1&showinfo=0&autohide=1&hd=1"></iframe>
Of course, the drawback is that by setting these static frame dimensions, you will most likely get black bars on the sides or above and below, depending on what you prefer.
If you didn't care about the controls being cut-off, you could go on to use CSS and overflow: hidden
to crop the black bars out of the frame, providing you know the exact dimensions of the video.
Hope this helps, and hope the Embed method soon gets discrete quality parameters again one day!
In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.
Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.
Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.
Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
$scope.class = "red";_x000D_
$scope.changeClass = function(){_x000D_
if ($scope.class === "red")_x000D_
$scope.class = "blue";_x000D_
else_x000D_
$scope.class = "red";_x000D_
};_x000D_
});
_x000D_
.red{_x000D_
color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
<div ng-class="class">{{class}}</div>_x000D_
<button ng-click="changeClass()">Change Class</button> _x000D_
</body>
_x000D_
Here is the example working on jsFiddle
Please see a link for more details.
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
You could start by reading the documentation for Date. Then you realize that Date’s methods are all deprecated and turn to Calender instead.
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.DAY_OF_MONTH));
This can be done with something like this:
# foo.py
class Foo:
def method_1():
results = uses_some_other_method()
# testing.py
from mock import patch
@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
foo = Foo()
the_value = foo.method_1()
assert the_value == "specific_value"
Here's a source that you can read: Patching in the wrong place
PropertyInfo.SetValue() can assign ints to enums, ints to nullable ints, enums to nullable enums, but not ints to nullable enums.
enumProperty.SetValue(obj, 1, null); //works
nullableIntProperty.SetValue(obj, 1, null); //works
nullableEnumProperty.SetValue(obj, MyEnum.Foo, null); //works
nullableEnumProperty.SetValue(obj, 1, null); // throws an exception !!!
Full description here
Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();
If you are expecting 4
as output then try this:
char a[]={0x00,0xdc,0x01,0x04};
In Anon's answer:
"If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__
, you must call it yourself, since that will not happen automatically"
It's incredible: he is wording exactly the contrary of the principle of inheritance.
It is not that "something from super's __init__
(...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__
is overriden by the definition of the derived-clas __init__
So then, WHY defining a derived_class' __init__
, since it overrides what is aimed at when someone resorts to inheritance ??
It's because one needs to define something that is NOT done in the base-class' __init__
, and the only possibility to obtain that is to put its execution in a derived-class' __init__
function.
In other words, one needs something in base-class' __init__
in addition to what would be automatically done in the base-classe' __init__
if this latter wasn't overriden.
NOT the contrary.
Then, the problem is that the desired instructions present in the base-class' __init__
are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__
, in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__
.
That's exactly what is said in the official doc:
An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance
That's all the story:
when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__
function in the derived class
when the aim is to REPLACE the initialization performed by the base-class, __init__
must be defined in the derived-class
when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__
must be defined , comprising an explicit call to the base-class __init__
What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.
Usually, when you create a Java project you want to use functionalities made in another Java projects. For example, if your project wants to send one email you dont need to create all the necessary code for doing that. You can bring a java library that does the most part of the work. Maven is a building tool that will help you in several tasks. One of those tasks is to bring these external dependencies or artifacts to your project in an automatic way ( only with some configuration in a XML file ). Of course Maven has more details but, for your question this is enough. And, of course too, Maven can build your project as an artifact (usually a jar file ) that can be used or imported in other projects.
This website has several articles talking about Maven :
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
The return
there is returning from the lambda expression rather than from the containing method. Instead of forEach
you need to filter
the stream:
players.stream().filter(player -> player.getName().contains(name))
.findFirst().orElse(null);
Here filter
restricts the stream to those items that match the predicate, and findFirst
then returns an Optional
with the first matching entry.
This looks less efficient than the for-loop approach, but in fact findFirst()
can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny()
instead of findFirst()
if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery
You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/
All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter
<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">
and run js function
app_handle_listing_horisontal_scroll($('#table-listing'))
'Create a class to hold the pair...
Public Class ColumnValue
Public ColumnName As String
Public ColumnValue As New Object
End Class
'Build the pair...
For Each row In [YourDataTable].Rows
For Each item As DataColumn In row.Table.Columns
Dim rowValue As New ColumnValue
rowValue.ColumnName = item.Caption
rowValue.ColumnValue = row.item(item.Ordinal)
RowValues.Add(rowValue)
rowValue = Nothing
Next
' Now you can grab the value by the column name...
Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select p.ColumnValue).FirstOrDefault
Next
I found out about this one (Unzip package on NuGet) today, since I ran into a hard bug in DotNetZip, and I realized there hasn't been really that much work done on DotNetZip for the last two years.
The Unzip package is lean, and it did the job for me - it didn't have the bug that DotNetZip had. Also, it was a reasonably small file, relying upon the Microsoft BCL for the actual decompression. I could easily make adjustments which I needed (to be able to keep track of the progress while decompressing). I recommend it.
A string is a collection of char's (16bit unsigned). So if you are going to convert negative numbers into a string, they'll be lost in translation.
Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.
Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:
<projectDescription>
<name>Project-Name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
2- Now instead of "Project-Name", write your project name, maybe current directory name
3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )
4- Now go to Eclips and open project and add your files to it.
Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.
Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.
I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.
<ul id="category-tabs">
<li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
<ul>
<li><a href="javascript:void">item 1</a></li>
<li><a href="javascript:void">item 2</a></li>
<li><a href="javascript:void">item 3</a></li>
</ul>
</li> </ul>
//Jquery
$(document).ready(function() {
$('li').click(function() {
$('i').toggleClass('fa-plus-square fa-minus-square');
});
});
A small powershell to get needed information for also visual studio extension :
function Get-VSMarketPlaceExtension {
[CmdLetBinding()]
Param(
[Parameter(ValueFromPipeline = $true,Mandatory = $true)]
[string[]]
$extensionName
)
begin {
$body=@{
filters = ,@{
criteria =,@{
filterType=7
value = $null
}
}
flags = 1712
}
}
process {
foreach($Extension in $extensionName) {
$response = try {
$body.filters[0].criteria[0].value = $Extension
$Query = $body|ConvertTo-JSON -Depth 4
(Invoke-WebRequest -Uri "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=6.0-preview" -ErrorAction Stop -Body $Query -Method Post -ContentType "application/json")
} catch [System.Net.WebException] {
Write-Verbose "An exception was caught: $($_.Exception.Message)"
$_.Exception.Response
}
$statusCodeInt = [int]$response.StatusCode
if ($statusCodeInt -ge 400) {
Write-Warning "Erreur sur l'appel d'API : $($response.StatusDescription)"
return
}
$ObjResults = ($response.Content | ConvertFrom-Json).results
If ($ObjResults.resultMetadata.metadataItems.count -ne 1) {
Write-Warning "l'extension '$Extension' n'a pas été trouvée."
return
}
$Extension = $ObjResults.extensions
$obj2Download = ($Extension.versions[0].properties | Where-Object key -eq 'Microsoft.VisualStudio.Services.Payload.FileName').value
[PSCustomObject]@{
displayName = $Extension.displayName
extensionId = $Extension.extensionId
deploymentType = ($obj2Download -split '\.')[-1]
version = [version]$Extension.versions[0].version
LastUpdate = [datetime]$Extension.versions[0].lastUpdated
IsValidated = ($Extension.versions[0].flags -eq "validated")
extensionName = $Extension.extensionName
publisher = $Extension.publisher.publisherName
SourceURL = $Extension.versions[0].assetUri +"/" + $obj2Download
FileName = $obj2Download
}
}
}
}
This use marketplace API to get extension information. Exemple of usage and results :
>Get-VSMarketPlaceExtension "ProBITools.MicrosoftReportProjectsforVisualStudio"
displayName : Microsoft Reporting Services Projects
extensionId : 85e42f76-6afa-4a68-afb5-033d1fe08d7b
deploymentType : vsix
version : 2.6.7
LastUpdate : 13/05/2020 22:23:45
IsValidated : True
extensionName : MicrosoftReportProjectsforVisualStudio
publisher : ProBITools
SourceURL : https://probitools.gallery.vsassets.io/_apis/public/gallery/publisher/ProBITools/extension/MicrosoftReportProjectsforVisualStudio/2.6.7/assetbyname/Microsoft.DataTools.ReportingServices.vsix
FileName : Microsoft.DataTools.ReportingServices.vsix
All flags value are available here
Thanks to m4js7er and Adam Haynes for inspiration
Use try block in your code like
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
You can check the details here as well
If you go to C:\Windows\system32\Windowspowershell\v1.0
(and C:\Windows\syswow64\Windowspowershell\v1.0
on x64 machines) in Windows Explorer and double-click powershell.exe
you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe
can be set independently from the default properties.
To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.
Running start powershell
from cmd.exe should start a new console with your default settings.
Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).
On Debian, change /etc/php5/conf.d/suhosin.ini
;suhosin.memory_limit = 0
to
suhosin.memory_limit = 2G
Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:
Changed the way the memory_limit protection is implemented
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
I had this issue with an MVC project and here is how I fixed it.
Find :
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
Change to:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.bundle.min.js"));
This will set the bundle file to load. It is already in the correct order. You just have to make sure that you are rendering this bundle in your view.
a=(b c d)
if printf '%s\0' "${a[@]}" | grep -Fqxz c
then
echo 'array “a” contains value “c”'
fi
If you prefer you can use equivalent long options:
--fixed-strings --quiet --line-regexp --null-data
Make sure to add @XmlSeeAlso tag with your specific classes used inside JaxbList. It is very important else it throws HttpMessageNotWritableException
I was struggling with this - you can style the background of the dialog using android:alertDialogStyle="@style/AlertDialog"
in your theme, but it ignores any text settings you have. As @rflexor said above it cannot be done with the SDK prior to Honeycomb (well you could use Reflection
).
My solution, in a nutshell, was to style the background of the dialog using the above, then set a custom title and content view (using layouts that are the same as those in the SDK).
My wrapper:
import com.mypackage.R;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAlertDialogBuilder extends AlertDialog.Builder {
private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;
public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;
View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);
View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);
}
@Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
@Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}
@Override
public CustomAlertDialogBuilder setMessage(int textResId) {
mMessage.setText(textResId);
return this;
}
@Override
public CustomAlertDialogBuilder setMessage(CharSequence text) {
mMessage.setText(text);
return this;
}
@Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
@Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
}
alert_dialog_title.xml (taken from the SDK)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/title_template"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dip"
android:layout_marginBottom="9dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="6dip"
android:paddingRight="10dip"
android:src="@drawable/ic_dialog_alert" />
<TextView android:id="@+id/alertTitle"
style="@style/?android:attr/textAppearanceLarge"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
android:src="@drawable/divider_horizontal_bright" />
</LinearLayout>
alert_dialog_message.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="12dip"
android:paddingLeft="14dip"
android:paddingRight="10dip">
<TextView android:id="@+id/message"
style="?android:attr/textAppearanceMedium"
android:textColor="@color/dark_grey"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" />
</ScrollView>
Then just use CustomAlertDialogBuilder
instead of AlertDialog.Builder
to create your dialogs, and just call setTitle
and setMessage
as usual.
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
Try using qx{command}
rather than backticks. To me, it's a bit better because: you can do SQL with it and not worry about escaping quotes and such. Depending on the editor and screen, my old eyes tend to miss the tiny back ticks, and it shouldn't ever have an issue with being overloaded like using angle brackets versus glob.
I have the same problem.
And got the solution turning on the ASP Net from Turn Windows feature on or off
menu.
In fact, cross-domain AJAX (XMLHttp) requests are not allowed because of security reasons (think about fetching a "restricted" webpage from the client-side and sending it back to the server – this would be a security issue).
The only workaround are callbacks. This is: creating a new script object and pointing the src to the end-side JavaScript, which is a callback with JSON values (myFunction({data}), myFunction is a function which does something with the data (for example, storing it in a variable).
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
You can use list slicing to archive your goal:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist
Outputs:
[6, 7, 8, 9]
Or del
if you only want to use one list:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist
Outputs:
[6, 7, 8, 9]
Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e
f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)
Here is the way to achieve it - though I do not yet know how to add the alias in this case
See the example below - Using Maps
val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))
val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)
val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")
claimRDD2DF1.groupBy("pid").agg(exprs) show false
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
I got a easy solution which will select from database table and let you do easily.
SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'
You can easily add a space there if you try
SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'
Here you can combine as much as your table have.
Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'Email Address';
$mail->Password = 'Email Account Password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
Example script and full source code can be found from here - How to Send Email from Localhost in PHP
Yes,
You are trying to access an element of the list that does not exist.
MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
Have you got an off-by-one error?
Simply forcefully kill the process ID, the hadoop job will also be killed automatically . Use this command:
kill -9 <process_id>
eg: process ID no: 4040 namenode
username@hostname:~$ kill -9 4040
Try adding the profile
attribute to your head
tag and use "image/x-icon"
for the type
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
If the above code doesn't work, try using the full icon path for the href
attribute:
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
Either:
,[\s\S]*$
or ,.*$
to match everything after the first comma (see explanation for which one to use); or
[^,]*$
to match everything after the last comma (which is probably what you want).
You can use, for example, /[^,]*/.exec(s)[0]
in JavaScript, where s is the original string. If you wanted to use multiline mode and find all matches that way, you could use s.match(/[^,]*/mg)
to get an array (if you have more than one of your posted example lines in the variable on separate lines).
[\s\S]
is a character class that matches both whitespace and non-whitespace characters (i.e. all of them). This is different from .
in that it matches newlines.[^,]
is a negated character class that matches everything except for commas.*
means that the previous item can repeat 0 or more times.$
is the anchor that requires that the end of the match be at the end of the string (or end of line if using the /m multiline flag).For the first match, the first regex finds the first comma ,
and then matches all characters afterward until the end of line [\s\S]*$
, including commas.
The second regex matches as many non-comma characters as possible before the end of line. Thus, the entire match will be after the last comma.
For those looking for a cross-platform way that works on both Windows and Mac, the following works:
Sub CreateDir(strPath As String)
Dim elm As Variant
Dim strCheckPath As String
strCheckPath = ""
For Each elm In Split(strPath, Application.PathSeparator)
strCheckPath = strCheckPath & elm & Application.PathSeparator
If (Len(strCheckPath) > 1 And Not FolderExists(strCheckPath)) Then
MkDir strCheckPath
End If
Next
End Sub
Function FolderExists(FolderPath As String) As Boolean
FolderExists = True
On Error Resume Next
ChDir FolderPath
If Err <> 0 Then FolderExists = False
On Error GoTo 0
End Function
I figured it out. json_encode handles objects differently than strings. I cast the object to a string and it works now.
foreach($xml->children() as $state)
{
$states[]= array('state' => (string)$state->name);
}
echo json_encode($states);
This is my way to setup Servlet as welcome page.
I share for whom concern.
web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>servlet.Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
Servlet class
@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
}
}
Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :
-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440
LEA (Load Effective Address) is a shift-and-add instruction. It was added to 8086 because hardware is there to decode and calculate adressing modes.
Use replace method of string like the following way:
String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);
Output:
abcd
$('#dialog').draggable({ handle: "#tblOverlay" , scroll: false });
// Pop up Window
<div id="dialog">
<table id="tblOverlay">
<tr><td></td></tr>
<table>
</div>
Options:
You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.
function change() {
alert("a");
var scope = angular.element($("#outer")).scope();
scope.$apply(function(){
scope.msg = 'Superhero';
})
}
Demo: Fiddle
please fill the @likeTablename param for search table.
now this parameter set to %tbltrans% for search all table contain tbltrans in name.
set @likeTablename to '%' to show all table.
declare @AllTableNames nvarchar(max);
select @AllTableNames=STUFF((select ' SELECT TABLE_CATALOG collate DATABASE_DEFAULT+''.''+TABLE_SCHEMA collate DATABASE_DEFAULT+''.''+TABLE_NAME collate DATABASE_DEFAULT as tablename FROM '+name+'.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' union '
FROM master.sys.databases
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
set @AllTableNames=left(@AllTableNames,len(@AllTableNames)-6)
declare @likeTablename nvarchar(200)='%tbltrans%';
set @AllTableNames=N'select tablename from('+@AllTableNames+N')at where tablename like '''+N'%'+@likeTablename+N'%'+N''''
exec sp_executesql @AllTableNames
For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes
instead of yAxes
. Note that an array (and plural) is used for yAxes
(or xAxes
), because you may as well have multiple axes.
I spent a few hours trying to fix the issue and I finally got it - the SQL Server Browser was "Stopped". The fix is to change it to "Automatic" mode:
If it is disabled, go to Control Panel->Administrative Tools->Services, and look for the SQL Server Agent. Right-click, and select "Properties." From the "Startup Type" dropdown, change from "Disabled" to "Automatic".
Using XAML:
If you know the other assembly
structure and want the resources
in c# code, then use below code:
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
foreach (var item in dictionary.Values)
{
//operations
}
Output: If we want to use ResourceDictionary
RD1.xaml
of Project WpfControlLibrary1
into StackOverflowApp
project.
Structure of Projects:
Code Output:
PS: All ResourceDictionary
Files should have Build Action
as 'Resource
' or 'Page
'.
Using C#:
If anyone wants the solution in purely c# code then see my this solution.
Remove the project from the server from the Server View. Then run the project under the same server.
The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
Please see Why does the property I want to mock need to be virtual?
You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x)
call.
Use mysql_fetch_assoc instead of mysql_fetch_array
You should add a .gitignore file to your project and add /.idea
to it. You should add each directory / file in one line.
If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea
to the new line.
After that run git rm -r --cached .idea
command.
If you faced an error you can run git rm -r -f --cached .idea
command. After all run git add .
and then git commit -m "Removed .idea directory and added a .gitignore file"
and finally push the changes by running git push
command.
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
Arrays.asList(array);
Example:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
See Arrays.asList
class documentation.
Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse:
from flask import request
@app.route('/')
@app.route('/data')
def data():
query_string = request.query_string ## There is it
return render_template("data.html")
The full documentation for the request and response objects is in Werkzeug: http://werkzeug.pocoo.org/docs/wrappers/
Also beware that "setup" (i.e. localhost/phpmyadmin/setup) has an error in the way it handles the "no password" option. While it creates a line that says:
$cfg['Servers'][$i]['nopassword'] = true;
the actual name of the parameter should be as shown here:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
This "setup" error exists as of today, Oct 20, 2015.
Edit
This answer is now deprecated. See the answer by apsillers.
Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified
. See the support for this event across browsers. It has been supported in Chrome since 1.0.
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
See a working example here.
Just for additional context and intuition, here's an explicit and concrete example of the differences.
Assume you have the following function seen below. ( This label function, will arbitrarily split the values into 'High' and 'Low', based upon the threshold you provide as the parameter (x). )
def label(element, x):
if element > x:
return 'High'
else:
return 'Low'
In this example, lets assume our dataframe has one column with random numbers.
If you tried mapping the label function with map:
df['ColumnName'].map(label, x = 0.8)
You will result with the following error:
TypeError: map() got an unexpected keyword argument 'x'
Now take the same function and use apply, and you'll see that it works:
df['ColumnName'].apply(label, x=0.8)
Series.apply() can take additional arguments element-wise, while the Series.map() method will return an error.
Now, if you're trying to apply the same function to several columns in your dataframe simultaneously, DataFrame.applymap() is used.
df[['ColumnName','ColumnName2','ColumnName3','ColumnName4']].applymap(label)
Lastly, you can also use the apply() method on a dataframe, but the DataFrame.apply() method has different capabilities. Instead of applying functions element-wise, the df.apply() method applies functions along an axis, either column-wise or row-wise. When we create a function to use with df.apply(), we set it up to accept a series, most commonly a column.
Here is an example:
df.apply(pd.value_counts)
When we applied the pd.value_counts function to the dataframe, it calculated the value counts for all the columns.
Notice, and this is very important, when we used the df.apply() method to transform multiple columns. This is only possible because the pd.value_counts function operates on a series. If we tried to use the df.apply() method to apply a function that works element-wise to multiple columns, we'd get an error:
For example:
def label(element):
if element > 1:
return 'High'
else:
return 'Low'
df[['ColumnName','ColumnName2','ColumnName3','ColumnName4']].apply(label)
This will result with the following error:
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index Economy')
In general, we should only use the apply() method when a vectorized function does not exist. Recall that pandas uses vectorization, the process of applying operations to whole series at once, to optimize performance. When we use the apply() method, we're actually looping through rows, so a vectorized method can perform an equivalent task faster than the apply() method.
Here are some examples of vectorized functions that already exist that you do NOT want to recreate using any type of apply/map methods:
What solved it for me was using :
regasm.exe 'xx.dll' /tlb /codebase /register
It is however, important to understand the difference between regasm.exe and regsvr.exe:
What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?
Bower is a package manager primarily for (but not limited to) front-end web development. In Ubuntu 16.04 and later Bower package manager can be quickly and easily installed from the Ubuntu Software app. Open Ubuntu Software, search for "bower" and click the Install button to install it. In all currently supported versions of Ubuntu open the terminal and type:
sudo snap install bower --classic
From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):
child::*
selects all element children of the context node
child::text()
selects all text node children of the context node
child::node()
selects all the children of the context node, whatever their node type
So I guess your answer is:
$doc/PRESENTEDIN/X/child::node()
And if you want a flatten array of all nested nodes:
$doc/PRESENTEDIN/X/descendant::node()
JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.
I have developed a double Splitter (Takes two split characters) as requested Here. Could be of some value in this thread seeing its the most referenced for queries relating to string splitting.
CREATE FUNCTION uft_DoubleSplitter
(
-- Add the parameters for the function here
@String VARCHAR(4000),
@Splitter1 CHAR,
@Splitter2 CHAR
)
RETURNS @Result TABLE (Id INT,MId INT,SValue VARCHAR(4000))
AS
BEGIN
DECLARE @FResult TABLE(Id INT IDENTITY(1, 1),
SValue VARCHAR(4000))
DECLARE @SResult TABLE(Id INT IDENTITY(1, 1),
MId INT,
SValue VARCHAR(4000))
SET @String = @String+@Splitter1
WHILE CHARINDEX(@Splitter1, @String) > 0
BEGIN
DECLARE @WorkingString VARCHAR(4000) = NULL
SET @WorkingString = SUBSTRING(@String, 1, CHARINDEX(@Splitter1, @String) - 1)
--Print @workingString
INSERT INTO @FResult
SELECT CASE
WHEN @WorkingString = '' THEN NULL
ELSE @WorkingString
END
SET @String = SUBSTRING(@String, LEN(@WorkingString) + 2, LEN(@String))
END
IF ISNULL(@Splitter2, '') != ''
BEGIN
DECLARE @OStartLoop INT
DECLARE @OEndLoop INT
SELECT @OStartLoop = MIN(Id),
@OEndLoop = MAX(Id)
FROM @FResult
WHILE @OStartLoop <= @OEndLoop
BEGIN
DECLARE @iString VARCHAR(4000)
DECLARE @iMId INT
SELECT @iString = SValue+@Splitter2,
@iMId = Id
FROM @FResult
WHERE Id = @OStartLoop
WHILE CHARINDEX(@Splitter2, @iString) > 0
BEGIN
DECLARE @iWorkingString VARCHAR(4000) = NULL
SET @IWorkingString = SUBSTRING(@iString, 1, CHARINDEX(@Splitter2, @iString) - 1)
INSERT INTO @SResult
SELECT @iMId,
CASE
WHEN @iWorkingString = '' THEN NULL
ELSE @iWorkingString
END
SET @iString = SUBSTRING(@iString, LEN(@iWorkingString) + 2, LEN(@iString))
END
SET @OStartLoop = @OStartLoop + 1
END
INSERT INTO @Result
SELECT MId AS PrimarySplitID,
ROW_NUMBER() OVER (PARTITION BY MId ORDER BY Mid, Id) AS SecondarySplitID ,
SValue
FROM @SResult
END
ELSE
BEGIN
INSERT INTO @Result
SELECT Id AS PrimarySplitID,
NULL AS SecondarySplitID,
SValue
FROM @FResult
END
RETURN
Usage:
--FirstSplit
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&',NULL)
--Second Split
SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&','=')
Possible Usage (Get second value of each split):
SELECT fn.SValue
FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===', '&', '=')AS fn
WHERE fn.mid = 2
The length of the text that you are providing in each line is different, this is the problem, so if the second word is too long (see2.txt
is long 8 char which corresponds to a single tab lenght) it prints out a tab which goes to the next tabulation point.
One way to solve it is to programmatically add a pad to the f.getName()
text so each text generated: see.txt
or see2.txt
has the same lenght (for example see.txt_
and see2.txt
) so each tab automatically goes to the same tabulation point.
If you are developing with JDK 1.5 you can solve this using java.util.Formatter:
String format = "%-20s %5d\n";
System.out.format(format, "test", 1);
System.out.format(format, "test2", 20);
System.out.format(format, "test3", 5000);
this example will give you this print:
test 1
test2 20
test3 5000
Install setuptools
and try again.
try command:
sudo apt-get install -y python-setuptools
Simplest to me is:
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
merged_list = list(set(first_list+second_list))
print(merged_list)
#prints [1, 2, 5, 7, 9]
The indexes capable of placing a unique key constraint on a table are PRIMARY
and UNIQUE
indexes.
To remove the unique key constraint on a column but keep the index, you could remove and recreate the index with type INDEX
.
Note that it is a good idea for all tables to have an index marked PRIMARY
.
You can use np.where
to match the boolean conditions corresponding to Nan
values of the array and map
each outcome to generate a list of tuples
.
>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
To lock the screen:
adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26
To lock the screen and turn it off
adb shell input keyevent 82 && adb shell input keyevent 26
To unlock the screen without pass
adb shell input keyevent 82 && adb shell input keyevent 66
To unlock the screen that has pass 1234
adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66
You can leave out the newline which gives you:
case 1: case 2: case 3:
break;
but I consider that bad style.
To view the differences going from the remote file to the local file:
git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt
To view the differences in the other direction:
git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt
Basically you can diff any two files anywhere using this notation:
git diff ref1:path/to/file1 ref2:path/to/file2
As usual, ref1
and ref2
could be branch names, remotename/branchname, commit SHAs, etc.
I was getting the same error. In my case there was a leading space-symbol in the fxml file name:
" fxml_example.fxml" instead of "fxml_example.fxml"
I don't know where it came from. It was very difficult to notice it. When I removed the leading space, everything went ok. I didn't even knew that file name could start with the space-symbol.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
Years after everyone's answer, I too want to present how I did it for my project
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java
I just realize something for Mozilla Firefox 19+ that the browser gives an opacity value for the placeholder, so the color will not be what you really want.
input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
color: #eee; opacity:1;
}
input:-moz-placeholder, textarea:-moz-placeholder {
color: #eee; opacity:1;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #eee; opacity:1;
}
input:-ms-input-placeholder, textarea:-ms-input-placeholder {
color: #eee; opacity:1;
}
I overwrite the opacity
for 1, so it will be good to go.
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
Just to modify scott's answer to make it a function:
Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant
Dim LookAtWhat As Integer
If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart
With RngIn
Set FindFirstInRange = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=LookAtWhat, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=UseCase)
If FindFirstInRange Is Nothing Then FindFirstInRange = False
End With
End Function
This returns FALSE if the value isn't found, and if it's found, it returns the range.
You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.
I took out the TRIM because you can add that beforehand if you want to.
An example:
MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address
That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:
MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address
You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.
Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.
In Microservices world (having a common shared codebase), each Microservice would have a Dockerfile
whereas at the root level (generally outside of all Microservices and where your parent POM resides) you would define a docker-compose.yml
to group all Microservices into a full-blown app.
In your case "Docker Compose" is preferred over "Dockerfile". Think "App" Think "Compose".
I realize this has already been marked as answered, but we used to do it like this:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND OBJECT_ID = OBJECT_ID('dbo.MyProc'))
exec('CREATE PROCEDURE [dbo].[MyProc] AS BEGIN SET NOCOUNT ON; END')
GO
ALTER PROCEDURE [dbo].[MyProc]
AS
....
Just to avoid dropping the procedure.
perl -lne '$x += $_; END { print $x; }' < infile.txt
I wrote a powershell script to do it.
The advantage is that it prints out a summary of deleted folders, and ignored ones if you specified any subfolder hierarchy to be ignored.
I had the same problem and I did it this way
//note that I added jquery separately above this
<!--ENJOY HINT PACKAGES --START -->
<link href="path/enjoyhint/jquery.enjoyhint.css" rel="stylesheet">
<script src="path/enjoyhint/jquery.enjoyhint.js"></script>
<script src="path/enjoyhint/kinetic.min.js"></script>
<script src="path/enjoyhint/enjoyhint.js"></script>
<!--ENJOY HINT PACKAGES --END -->
and it works
you should change the type from submit
to button
:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me hope it helps.
It works for me with
logging.level.org.hibernate.SQL= DEBUG
logging.level.org.hibernate.type=TRACE
Suppose we have a dictionary like this
Dictionary<int,string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
We can initialize it as follow.
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Mohan" },
{ 2, "Kishor" },
{ 3, "Pankaj" },
{ 4, "Jeetu" }
};
Use this
WebView myWebView = (WebView) findViewById(R.id.my_web);
myWebView.setBackgroundColor(0);
I like lambda :)
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
Good luck!
Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure
This class is really simple to use and is bundled into the laravel framework for the queue manager.
From the github documentation :
$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
echo "{$greeting}, {$name}!\n";
});
$serialized = serialize($helloWorld);
I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:
npm install std-pour
Then it's simple enough to execute a command and see the output in realtime:
const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));
It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn
so it should be a drop in replacement anywhere you're using it.
There is a solution using $element in the controller if you don't want to create another directive for this problem:
appControllers.controller('YourCtrl', ['$scope', '$timeout', '$element',
function($scope, $timeout, $element) {
$scope.updateTypeahead = function() {
// ... some logic here
$timeout(function() {
$element[0].getElementsByClassName('search-query')[0].focus();
// if you have unique id you can use $window instead of $element:
// $window.document.getElementById('searchText').focus();
});
}
}]);
And this will work with ng-change:
<input id="searchText" type="text" class="search-query" ng-change="updateTypeahead()" ng-model="searchText" />
you can also use a meta tag to redirect to another url.
<meta http-equiv="refresh" content="2;url=http://webdesign.about.com/">
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
The answers here are very good, but still insufficient for me.
I wrote a small loop that compares Uri.EscapeUriString
with Uri.EscapeDataString
for all characters from 0 to 255.
NOTE: Both functions have the built-in intelligence that characters above 0x80 are first UTF-8 encoded and then percent encoded.
Here is the result:
******* Different *******
'#' -> Uri "#" Data "%23"
'$' -> Uri "$" Data "%24"
'&' -> Uri "&" Data "%26"
'+' -> Uri "+" Data "%2B"
',' -> Uri "," Data "%2C"
'/' -> Uri "/" Data "%2F"
':' -> Uri ":" Data "%3A"
';' -> Uri ";" Data "%3B"
'=' -> Uri "=" Data "%3D"
'?' -> Uri "?" Data "%3F"
'@' -> Uri "@" Data "%40"
******* Not escaped *******
'!' -> Uri "!" Data "!"
''' -> Uri "'" Data "'"
'(' -> Uri "(" Data "("
')' -> Uri ")" Data ")"
'*' -> Uri "*" Data "*"
'-' -> Uri "-" Data "-"
'.' -> Uri "." Data "."
'_' -> Uri "_" Data "_"
'~' -> Uri "~" Data "~"
'0' -> Uri "0" Data "0"
.....
'9' -> Uri "9" Data "9"
'A' -> Uri "A" Data "A"
......
'Z' -> Uri "Z" Data "Z"
'a' -> Uri "a" Data "a"
.....
'z' -> Uri "z" Data "z"
******* UTF 8 *******
.....
'Ò' -> Uri "%C3%92" Data "%C3%92"
'Ó' -> Uri "%C3%93" Data "%C3%93"
'Ô' -> Uri "%C3%94" Data "%C3%94"
'Õ' -> Uri "%C3%95" Data "%C3%95"
'Ö' -> Uri "%C3%96" Data "%C3%96"
.....
EscapeUriString
is to be used to encode URLs, while EscapeDataString
is to be used to encode for example the content of a Cookie, because Cookie data must not contain the reserved characters '='
and ';'
.
In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.
Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.
This will allocate in the BSS segment, which is a part of the heap:
static int c[1000000];
int main()
{
cout << "done\n";
return 0;
}
This will allocate in the DATA segment, which is a part of the heap too:
int c[1000000] = {};
int main()
{
cout << "done\n";
return 0;
}
This will allocate at some unspecified location in the heap:
int main()
{
int* c = new int[1000000];
cout << "done\n";
return 0;
}
ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules
flag, and it will likely work.
To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:
const fs = require('fs');
Beware of an undo-tree quirk for redo!
Many popular “starter kits” (prelude, purcell, spacemacs) come bundled with undo-tree. Most (all?) even auto-enable it. As mentioned, undo-tree is a handy way to visualize and traverse the undo/redo tree. Prelude even gives it a key-chord (uu
), and also C-x u
.
The problem is: undo-tree seems to wreck Emacs’ default and well-known binding for redo: C-g C-/
.
Instead, you can use these symmetrical keys for undo/redo:
C-/ undo
C-S-/ redo
These are useful since sometimes you want to quickly redo without opening up the visualizer.
Declarative Programming is programming with declarations, i.e. declarative sentences. Declarative sentences have a number of properties that distinguish them from imperative sentences. In particular, declarations are:
A relevant point is that these are all structural properties and are orthogonal to subject matter. Declarative is not about "What vs. How". We can declare (represent and constrain) a "how" just as easily as we declare a "what". Declarative is about structure, not content. Declarative programming has a significant impact on how we abstract and refactor our code, and how we modularize it into subprograms, but not so much on the domain model.
Often, we can convert from imperative to declarative by adding context. E.g. from "Turn left. (... wait for it ...) Turn Right." to "Bob will turn left at intersection of Foo and Bar at 11:01. Bob will turn right at the intersection of Bar and Baz at 11:06." Note that in the latter case the sentences are idempotent and commutative, whereas in the former case rearranging or repeating the sentences would severely change the meaning of the program.
Regarding monotonic, declarations can add constraints which subtract possibilities. But constraints still add information (more precisely, constraints are information). If we need time-varying declarations, it is typical to model this with explicit temporal semantics - e.g. from "the ball is flat" to "the ball is flat at time T". If we have two contradictory declarations, we have an inconsistent declarative system, though this might be resolved by introducing soft constraints (priorities, probabilities, etc.) or leveraging a paraconsistent logic.
I suffered this problem while developing an application for a client. Working on my machine the code/forms etc worked perfectly but when loaded on to the client's system this error occurred at some point within my application.
My workaround for this error was to strip apart the workbook from the forms and code by removing the VBA modules and forms. After doing this my client copied the 'bare' workbook and the modules and forms. Importing the forms and code into the macro-enabled workbook enabled the application to work again.
IP addresses are quite commonly used for geo-targeting i.e. customizing the content of a website by the visitor's location / country but they are not permanently associated with a country and often get re-assigned.
To accomplish what you want, you need to keep an up to date lookup to map an IP address to a country either with a database or a geolocation API. Here's an example :
> https://ipapi.co/8.8.8.8/country
US
> https://ipapi.co/8.8.8.8/country_name
United States
Or you can use the full API to get complete location for IP address e.g.
https://ipapi.co/8.8.8.8/json
{
"ip": "8.8.8.8",
"city": "Mountain View",
"region": "California",
"region_code": "CA",
"country": "US",
"country_name": "United States",
"continent_code": "NA",
"postal": "94035",
"latitude": 37.386,
"longitude": -122.0838,
"timezone": "America/Los_Angeles",
"utc_offset": "-0800",
"country_calling_code": "+1",
"currency": "USD",
"languages": "en-US,es-US,haw,fr",
"asn": "AS15169",
"org": "Google Inc."
}
We had this same issue. We solved it adding 'length' to entity attribute definition:
@Column(columnDefinition="text", length=10485760)
private String configFileXml = "";
I think the easiest thing for you to do would be to install the git plugin for eclipse, works more or less the same as eclipse CVS and SVN plugins:
GL!
Not an answer to OP's question but it's worth mentioning that there is the viridis
package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.
To get the palette, simply install the package and use the function viridis_pal()
. There are four options "A", "B", "C" and "D" to choose
install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n) # n = number of colors seeked
There is also an excellent talk explaining the complexity of good colormaps on YouTube:
A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt
This link: Creating the Sample Database in Oracle 11g Release 2 is a good example of creating a sample database.
This link: Newbie Guide to Oracle 11g Database Common Problems should help you if you come across some common problems creating your database.
Best of luck!
EDIT: As you are using XE, you should have a DB already created, to connect using SQL*Plus and SQL Developer etc. the info is here: Connecting to Oracle Database Express Edition and Exploring It.
Extract:
Connecting to Oracle Database XE from SQL Developer SQL Developer is a client program with which you can access Oracle Database XE. With Oracle Database XE 11g Release 2 (11.2), you must use SQL Developer version 3.0. This section assumes that SQL Developer is installed on your system, and shows how to start it and connect to Oracle Database XE. If SQL Developer is not installed on your system, see Oracle Database SQL Developer User's Guide for installation instructions.
Note:
For the following procedure: The first time you start SQL Developer on your system, you must provide the full path to java.exe in step 1.
For step 4, you need a user name and password.
For step 6, you need a host name and port.
To connect to Oracle Database XE from SQL Developer:
Start SQL Developer.
For instructions, see Oracle Database SQL Developer User's Guide.
If this is the first time you have started SQL Developer on your system, you are prompted to enter the full path to java.exe (for example, C:\jdk1.5.0\bin\java.exe). Either type the full path after the prompt or browse to it, and then press the key Enter.
The Oracle SQL Developer window opens.
In the navigation frame of the window, click Connections.
The Connections pane appears.
In the Connections pane, click the icon New Connection.
The New/Select Database Connection window opens.
In the New/Select Database Connection window, type the appropriate values in the fields Connection Name, Username, and Password.
For security, the password characters that you type appear as asterisks.
Near the Password field is the check box Save Password. By default, it is deselected. Oracle recommends accepting the default.
In the New/Select Database Connection window, click the tab Oracle.
The Oracle pane appears.
In the Oracle pane:
For Connection Type, accept the default (Basic).
For Role, accept the default.
In the fields Hostname and Port, either accept the defaults or type the appropriate values.
Select the option SID.
In the SID field, type accept the default (xe).
In the New/Select Database Connection window, click the button Test.
The connection is tested. If the connection succeeds, the Status indicator changes from blank to Success.
Description of the illustration success.gif
If the test succeeded, click the button Connect.
The New/Select Database Connection window closes. The Connections pane shows the connection whose name you entered in the Connection Name field in step 4.
You are in the SQL Developer environment.
To exit SQL Developer, select Exit from the File menu.
I figured it out. The below works in converting it to a 24 hr date format.
select date_parse('7/22/2016 6:05:04 PM','%m/%d/%Y %h:%i:%s %p')
First, install QEMU. On Debian-based distributions like Ubuntu, run:
$ apt-get install qemu
Then run the following command:
$ qemu-img convert -O vmdk imagefile.dd vmdkname.vmdk
I’m assuming a flat disk image is a dd
-style image. The convert operation also handles numerous other formats.
For more information about the qemu-img
command, see the output of
$ qemu-img -h
You can use the RedirectView
. Copied from the JavaDoc:
View that redirects to an absolute, context relative, or current request relative URL
Example:
@RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.yahoo.com");
return redirectView;
}
You can also use a ResponseEntity
, e.g.
@RequestMapping("/to-be-redirected")
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
URI yahoo = new URI("http://www.yahoo.com");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(yahoo);
return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}
And of course, return redirect:http://www.yahoo.com
as mentioned by others.
You should call the bash script using source.
Here is an example:
#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"
On your shell just call it like that:
> source venv.sh
Or as @outmind suggested: (Note that this does not work with zsh)
> . venv.sh
There you go, the shell indication will be placed on your prompt.
I find exporting the packages in string format only is more portable than exporting the whole conda
environment. As the previous answer already suggested:
$ conda list -e > requirements.txt
However, this requirements.txt
contains build numbers which are not portable between operating systems, e.g. between Mac
and Ubuntu
. In conda env export
we have the option --no-builds
but not with conda list -e
, so we can remove the build number by issuing the following command:
$ sed -i -E "s/^(.*\=.*)(\=.*)/\1/" requirements.txt
And recreate the environment on another computer:
conda create -n recreated_env --file requirements.txt
Swift 5+
First of all you have to define 2 variables globally inside your view controller.
var player: AVPlayer!
var playerViewController: AVPlayerViewController!
Here I'm adding player to a desired view.
@IBOutlet weak var playerView: UIView!
Then add following code to the viewDidLoad method.
let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)
If you are not defining player and playerViewController globally, you won't be able to embed player.
Try this if other methods do not work:
I was getting the same error when I used this code to update the record:
@mysqli_query($dbc,$query or die()))
After removing or die
, it started working properly.
Delete package.json
and package-lock.json
file
Then type npm init
after that type npm install socket.io --save
finally type npm install
It works for me
This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.
However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :
:not(.myclass1) + .myclass1
Full working code example:
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
<div>This text should appear as normal</div>_x000D_
<p>This text should be blue.</p>_x000D_
<p class="myclass1">This text should appear red.</p>_x000D_
<p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
"react-router-dom": "^5.0.0",
you do not need to add any additional module, just in your component that has a url address like this:
http://localhost:3000/#/?authority'
you can try the following simple code:
const search =this.props.location.search;
const params = new URLSearchParams(search);
const authority = params.get('authority'); //
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
from http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html
The Mockito javadoc seems to tell why use doReturn()
instead of when()
Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).
Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
1. When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
2. Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.
By deleting all emulator, sometime memory will not be reduce to our expectation. So open below mention path in you c drive
C:\Users{Username}.android\avd
In this avd folder, you can able to see all the avd's which you created earlier. So you need to delete all avd's that will remove all the unused spaces grab by your emulator's. Than create the fresh emulator for you works.
You could use for (String key : keys) { Object o = get(key);
to return an Object, call getClass().getName()
on it to get the type, and then do a set of if name.equals("String") type things to work out which method you should actually be calling, in order to get the value?
If you're using OS X, and it continues to hang indefinitely, I'd recommend shutting down Android Studio (may have to force kill), then going to your ~/.gradle directory on the console. You'll see a wrapper/dists directory there and whatever version of gradle AS is trying to download. Check the timestamp of the download underneath the randomly named subdirectory. If you see that it is never changing, most likely your download was interrupted and AS wasn't able to restart it properly and will not unless you delete everything below the dists directory and start over.
So, with AS shutdown delete everything below ~/.gradle/wrapper/dists and then try again with a new project in AS. You can check the progress of the gradle download file (it will end in .part) to make sure that it's growing. Give it plenty of time as it IS a large file.
That's what finally worked for me.
Just use this: ExtractFilePath(your_path_file_name)
2018 Update
Font Awesome 5 now features light, regular and solid variants. The icon featured in this question has the following style under the different variants:
A modern answer to this question would be that different variants of the icon can be used to make the icon appear bolder or lighter. The only downside is that if you're already using solid you will have to fall back to the original answers here to make those bolder, and likewise if you're using light you'd have to do the same to make those lighter.
Font Awesome's How To Use documentation walks through how to use these variants.
Original Answer
Font Awesome makes use of the Private Use region of Unicode. For example, this .icon-remove
you're using is added in using the ::before
pseudo-selector, setting its content to \f00d (
):
.icon-remove:before {
content: "\f00d";
}
Font Awesome does only come with one font-weight variant, however browsers will render this as they would render any font with only one variant. If you look closely, the normal
font-weight isn't as bold as the bold
font-weight. Unfortunately a normal font weight isn't what you're after.
What you can do however is change its colour to something less dark and reduce its font size to make it stand out a bit less. From your image, the "tags" text appears much lighter than the icon, so I'd suggest using something like:
.tag .icon-remove {
color:#888;
font-size:14px;
}
Here's a JSFiddle example, and here is further proof that this is definitely a font.
Use position: relative on the parent element.
Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.
You can call another action inside a action as follows:
redirect_to action: 'action_name'
class MyController < ApplicationController
def action1
redirect_to action: 'action2'
end
def action2
end
end
Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.
In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )
There are lot of options available , one of them is :
CREATE TEMPORARY TABLE temp_tb SELECT * FROM orig_tb;
ALTER TABLE temp_tb DROP col_x;
SELECT * FROM temp_tb;
Here the col_x is the column which u dont want to include in select statement.
Take a look at this question : Select all columns except one in MySQL?
Your client application and server application must be under same domain, for example :
client - localhost
server - localhost
and not :
client - localhost:21234
server - localhost
Two ways:
Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.
Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.
This is what the difference i found. Please let me know if any .
This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:
/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
for (var l = 0; l < ph[i].length; l++) {
/* create a function which swaps an image, and calls the next function in the queue */
theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
/* set the animation speed */
theQueue.delay(200,'anim');
}
}
/* start the animation */
theQueue.dequeue('anim');
This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.
git apply --reject --whitespace=fix mychanges.patch
worked for me.
The --reject
option will instruct git to not fail if it cannot determine how to apply a patch, but instead to apply indivdual hunks it can apply and create reject files (.rej
) for hunks it cannot apply. Wiggle can "apply [these] rejected patches and perform word-wise diffs".
Additionally, --whitespace=fix
will warn about whitespace errors and try to fix them, rather than refusing to apply an otherwise applicable hunk.
Both options together make the application of a patch more robust against failure, but they require additional attention with respect to the result.
For the whole documentation, see https://git-scm.com/docs/git-apply.
There is no correct answer, since it depends on what the definition of "syntax" is for your request. The most important thing is that you:
Before everyone jumps all over me for saying that there is no right or wrong answer here, let me explain a bit about how I came to the conclusion.
In this specific example, the OP's question is about a JSON request that contains a different key than expected. Now, the key name received is very similar, from a natural language standpoint, to the expected key, but it is, strictly, different, and hence not (usually) recognized by a machine as being equivalent.
As I said above, the deciding factor is what is meant by syntax. If the request was sent with a Content Type of application/json
, then yes, the request is syntactically valid because it's valid JSON syntax, but not semantically valid, since it doesn't match what's expected. (assuming a strict definition of what makes the request in question semantically valid or not).
If, on the other hand, the request was sent with a more specific custom Content Type like application/vnd.mycorp.mydatatype+json
that, perhaps, specifies exactly what fields are expected, then I would say that the request could easily be syntactically invalid, hence the 400 response.
In the case in question, since the key was wrong, not the value, there was a syntax error if there was a specification for what valid keys are. If there was no specification for valid keys, or the error was with a value, then it would be a semantic error.
WhatsApp does not have a API available for public use. As you put it, it's a closed system.
However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.
Here is a slight improvement to the given thread-based solution.
The code below supports exceptions:
def runFunctionCatchExceptions(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
except Exception, message:
return ["exception", message]
return ["RESULT", result]
def runFunctionWithTimeout(func, args=(), kwargs={}, timeout_duration=10, default=None):
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
self.result = runFunctionCatchExceptions(func, *args, **kwargs)
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
if it.result[0] == "exception":
raise it.result[1]
return it.result[1]
Invoking it with a 5 second timeout:
result = timeout(remote_calculate, (myarg,), timeout_duration=5)
You can also do this without using JQuery, like so:
<div id="myModal">
var modal = document.getElementById('myModal');
modal.backdrop = "static";
modal.keyboard = false;
Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:
.col {
padding-right:7px;
padding-left:7px;
}
Demo: http://bootply.com/93473
EDIT If you only want the spacing between columns you can select all cols except first and last like this..
.col:not(:first-child,:last-child) {
padding-right:7px;
padding-left:7px;
}
For Bootstrap 4 see: Remove gutter space for a specific div only
if you need to validate decimal with dots, commas, positives and negatives try this:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.
Don't put a name for target window when you use window.open("","NAME",....)
If you do it you can only open it once. Use _blank, etc instead of.
Please use @CrossOrigin
on the backendside
in Spring boot controller (either class level or method level) as the solution for Chrome error 'No 'Access-Control-Allow-Origin'
header is present on the requested resource.'
This solution is working for me 100% ...
Example : Class level
@CrossOrigin
@Controller
public class UploadController {
----- OR -------
Example : Method level
@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RequestMapping(value = "/loadAllCars")
@ResponseBody
public List<Car> loadAllCars() {
Ref: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
Try ISDATE()
function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy
format, while the second query tries to filter in dd/mm/yyyy
format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy
or with dd/mm/yyyy
format, whichever works in your db.
Illustrating what StaxMan has stated, this works for me
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
The correct API to use is UIView systemLayoutSizeFittingSize:
, passing either UILayoutFittingCompressedSize
or UILayoutFittingExpandedSize
.
For a normal UIView
using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell
(to determine row height for example) then you should call it against your cell contentView
and grab the height.
Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth
property be set correctly such that the label provides a correct intrinsicContentSize
, which will be used in systemLayoutSizeFittingSize's
calculation.
EDIT: by request, adding example of height calculation for a table view cell
Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.
As I said above, if you're using a multiline UILabel
it's imperative to sync the preferredMaxLayoutWidth
to the label width. I use a custom UILabel
subclass to do this:
@implementation TSLabel
- (void) layoutSubviews
{
[super layoutSubviews];
if ( self.numberOfLines == 0 )
{
if ( self.preferredMaxLayoutWidth != self.frame.size.width )
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
if ( self.numberOfLines == 0 )
{
// found out that sometimes intrinsicContentSize is 1pt too short!
s.height += 1;
}
return s;
}
@end
Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:
#import "TSTableViewController.h"
#import "TSTableViewCell.h"
@implementation TSTableViewController
- (NSString*) cellText
{
return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return 1;
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
return 1;
}
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
static TSTableViewCell *sizingCell;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
});
// configure the cell
sizingCell.text = self.cellText;
// force layout
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
// get the fitting size
CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));
return s.height;
}
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];
cell.text = self.cellText;
return cell;
}
@end
A simple custom cell:
#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize
:
It can be done using classes from the official bootstrap 3.x version, without any custom css.
Use input-group-addon
before the input tag, inside of input-group
then use any of the glyphicons, here is the code
<form>
<div class="form-group">
<div class="col-xs-5">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon glyphicon-user"></span></span>
<input class="form-control left-border-none" placeholder="User Name" type="text" name="username">
</div>
</div>
</div>
</form>
Here is the output
To customise it further add a couple of lines of custom css to your own custom.css file (adjust padding if needed)
.transparent {
background-color: transparent !important;
box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
}
.left-border-none {
border-left:none !important;
box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
}
By making the background of the input-group-addon
transparent and making the left gradient of the input tag to zero the input will have a seamless appearance. Here is the customised output
Here is a jsbin example
This will solve the custom css problems of overlapping with labels, alignment while using input-lg
and focus on tab issue.
Here is a quick example:
public class One {
/**
* @param args
*/
public static void main(String[] args) {
double a = 4.56777;
System.out.println( new Float( Math.round(a)) );
}
}
the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double
values and provides whole long
values
Regards
// innerWidth_x000D_
const screen_viewport_inner = () => {_x000D_
let w = window,_x000D_
i = `inner`;_x000D_
if (!(`innerWidth` in window)) {_x000D_
i = `client`;_x000D_
w = document.documentElement || document.body;_x000D_
}_x000D_
return {_x000D_
width: w[`${i}Width`],_x000D_
height: w[`${i}Height`]_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
// outerWidth_x000D_
const screen_viewport_outer = () => {_x000D_
let w = window,_x000D_
o = `outer`;_x000D_
if (!(`outerWidth` in window)) {_x000D_
o = `client`;_x000D_
w = document.documentElement || document.body;_x000D_
}_x000D_
return {_x000D_
width: w[`${o}Width`],_x000D_
height: w[`${o}Height`]_x000D_
}_x000D_
};_x000D_
_x000D_
// style_x000D_
const console_color = `_x000D_
color: rgba(0,255,0,0.7);_x000D_
font-size: 1.5rem;_x000D_
border: 1px solid red;_x000D_
`;_x000D_
_x000D_
_x000D_
_x000D_
// testing_x000D_
const test = () => {_x000D_
let i_obj = screen_viewport_inner();_x000D_
console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4));_x000D_
let o_obj = screen_viewport_outer();_x000D_
console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));_x000D_
};_x000D_
_x000D_
// IIFE_x000D_
(() => {_x000D_
test();_x000D_
})();
_x000D_
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.
@Entity(tableName = "employments")
data class Employment(
@PrimaryKey(autoGenerate = true) val id: Long,
@ColumnInfo(name = "code") val code: String,
@ColumnInfo(name = "title") val name: String
){
constructor(code: String, name: String) : this(0, code, name)
}
The dict
constructor accepts input exactly as you have it (key/value tuples).
>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}
From the documentation:
For example, these all return a dictionary equal to {"one": 1, "two": 2}:
dict(one=1, two=2) dict({'one': 1, 'two': 2}) dict(zip(('one', 'two'), (1, 2))) dict([['two', 2], ['one', 1]])
Encapsulation: binding the data members and member functions together is called encapsulation. encapsulation is done through class. abstraction: hiding the implementation details form usage or from view is called abstraction. ex: int x; we don't know how int will internally work. but we know int will work. that is abstraction.
I know its late replying to this question, but I have recently found a better solution to this problem without installing any plugin. We can create a formatted version number and can then use the variable created to display the build date/time. Steps to create: Build Environment --> Create a formatted version number:
Environment Variable Name: BUILD_DATE
Version Number Format String: ${BUILD_DATE_FORMATTED}
thats it. Just use the variable created above in the email subject line as ${ENV, var="BUILD_DATE"} and you will get the date/time of the current build.
If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon.
Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:
scrollBottom
is not a method in jQuery.
UPDATED DEMO - http://jsfiddle.net/xEFq5/10/
Try this:
$("#upClick").on("click" ,function(){
scrolled=scrolled-300;
$(".cover").animate({
scrollTop: scrolled
});
});
Try this:
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);
OR
you can also used following solution:
SELECT * FROM tablename ORDER BY column DESC LIMIT 1;
In case the XML store in the CLOB field in the database table. E.g for this XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Awmds>
<General_segment>
<General_segment_id>
<Customs_office_code>000</Customs_office_code>
</General_segment_id>
</General_segment>
</Awmds>
This is the Extract Query:
SELECT EXTRACTVALUE (
xmltype (T.CLOB_COLUMN_NAME),
'/Awmds/General_segment/General_segment_id/Customs_office_code')
AS Customs_office_code
FROM TABLE_NAME t;