It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.
After some googling I found this link:
The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged
So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.
you can use this in terminal or shell
adb shell install -g MyApp.apk
see more in develope google
You just need to remove the LocationListener
from LocationManager
manager.removeUpdates(listener);
Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.
.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.
In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:
public interface ITwo : IOne
The technical answer is that ITwo
does inherit IOne
for a few reasons:
ITwo
implements IOne
is flat wrongITwo
inherits IOne
methods, if MethodOne()
exists on IOne
then it is also accesible from ITwo
. i.e: ((ITwo)someObject).MethodOne())
is valid, even though ITwo
does not explicitly contain a definition for MethodOne()
typeof(IOne).IsAssignableFrom(typeof(ITwo))
returns true
We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)
Unity is an IoC. The point of IoC is to abstract the wiring of dependencies between types outside of the types themselves. This has a couple of advantages. First of all, it is done centrally which means you don't have to change a lot of code when dependencies change (which may be the case for unit tests).
Furthermore, if the wiring is done using configuration data instead of code, you can actually rewire the dependencies after deployment and thus change the behavior of the application without changing the code.
I was having the same problem using <a>
acting as button and I discovered I was missing a workaround by adding attr type="button"
makes it behave normally for me at least.
<a type="button" class="btn btn-primary">Release Me!</a>
This means the port is used somewhere else. so, you need to try another one or stop using the old port.
With rlang 0.4.0
we have curly-curly operators ({{}}
) which makes this very easy.
library(dplyr)
library(rlang)
iris1 <- tbl_df(iris)
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
mutate(df, {{varname}} := Petal.Width * n)
}
multipetal(iris1, 4)
# A tibble: 150 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.4
# <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
# 1 5.1 3.5 1.4 0.2 setosa 0.8
# 2 4.9 3 1.4 0.2 setosa 0.8
# 3 4.7 3.2 1.3 0.2 setosa 0.8
# 4 4.6 3.1 1.5 0.2 setosa 0.8
# 5 5 3.6 1.4 0.2 setosa 0.8
# 6 5.4 3.9 1.7 0.4 setosa 1.6
# 7 4.6 3.4 1.4 0.3 setosa 1.2
# 8 5 3.4 1.5 0.2 setosa 0.8
# 9 4.4 2.9 1.4 0.2 setosa 0.8
#10 4.9 3.1 1.5 0.1 setosa 0.4
# … with 140 more rows
We can also pass quoted/unquoted variable names to be assigned as column names.
multipetal <- function(df, name, n) {
mutate(df, {{name}} := Petal.Width * n)
}
multipetal(iris1, temp, 3)
# A tibble: 150 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species temp
# <dbl> <dbl> <dbl> <dbl> <fct> <dbl>
# 1 5.1 3.5 1.4 0.2 setosa 0.6
# 2 4.9 3 1.4 0.2 setosa 0.6
# 3 4.7 3.2 1.3 0.2 setosa 0.6
# 4 4.6 3.1 1.5 0.2 setosa 0.6
# 5 5 3.6 1.4 0.2 setosa 0.6
# 6 5.4 3.9 1.7 0.4 setosa 1.2
# 7 4.6 3.4 1.4 0.3 setosa 0.900
# 8 5 3.4 1.5 0.2 setosa 0.6
# 9 4.4 2.9 1.4 0.2 setosa 0.6
#10 4.9 3.1 1.5 0.1 setosa 0.3
# … with 140 more rows
It works the same with
multipetal(iris1, "temp", 3)
With java-8, you can do it this way.
double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value
What it does is :
Stream<Double>
from the listDoubleStream
toArray()
to get the array.You can also do this,
<?php
if ( ($cart->count_product) > 0) {
$print .= "<div class='my_class'>"
$print .= $cart->count_product;
$print .= "</div>"
} else {
$print = '';
}
echo $print;
?>
Fix:
I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".
After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.
C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
Volume in drive C is Windows
Volume Serial Number is 8EE6-5DD0
Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319
03/18/2010 08:23 PM 19,296 aspnet_regbrowsers.exe
03/18/2010 08:23 PM 36,696 aspnet_regiis.exe
03/18/2010 08:23 PM 102,232 aspnet_regsql.exe
3 File(s) 158,224 bytes
0 Dir(s) 34,836,508,672 bytes free
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.
HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.
Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:
DataFrame.shift(periods=1, freq=None, axis=0) Shift index by desired number of periods with an optional time freq
Notes
If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data.
Hope to help future questions in this matter.
Table with rounded corners and with bordered cells. Using @Ramon Tayag solution.
The key is to use border-spacing: 0
as he points out.
Solution using SCSS.
$line: 1px solid #979797;
$radius: 5px;
table {
border: $line;
border-radius: $radius;
border-spacing: 0;
th,
tr:not(:last-child) td {
border-bottom: $line;
}
th:not(:last-child),
td:not(:last-child) {
border-right: $line;
}
}
Probably use jenkins command line is another option, see https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI
So you can do
java -jar jenkins-cli.jar -s http://server get-job myjob > myjob.xml
java -jar jenkins-cli.jar -s http://server create-job newmyjob < myjob.xml
It works fine for me and I am used to store in inside my version control system
if you are already using jQuery in your build just do this:
$(yourObject).length
It works nicely for me on objects, and I already had jQuery as a dependancy.
I think the equivalent is Int64
A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...
[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]
The simple way:
The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):
sudo nano /etc/rc.local
Add the following and save:
#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &
The better way to do this would be to create a Daemon via Upstart:
sudo nano /etc/init/TheNameOfYourDaemon.conf
add the following:
description "My Daemon Job"
author "Your Name"
start on runlevel [2345]
pre-start script
echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script
exec /bin/sh TheNameOfYourScript.sh > /dev/null &
Save this.
Confirm that it looks ok:
init-checkconf /etc/init/TheNameOfYourDaemon.conf
Now reboot the machine:
sudo reboot
Now when you boot up your system, you can see the log file stating that your Daemon is running:
cat /var/log/TheNameOfYourDaemonJobLog.log
• Now you may start/stop/restart/get the status of your Daemon via:
restart: this will stop, then start a service
sudo service TheNameOfYourDaemonrestart restart
start: this will start a service, if it's not running
sudo service TheNameOfYourDaemonstart start
stop: this will stop a service, if it's running
sudo service TheNameOfYourDaemonstop stop
status: this will display the status of a service
sudo service TheNameOfYourDaemonstatus status
Following @armod's update about exceptions being added right on client
objects. I'll show how you can see all exceptions defined for your client class.
Exceptions are generated dynamically when you create your client with session.create_client()
or boto3.client()
. Internally it calls method botocore.errorfactory.ClientExceptionsFactory._create_client_exceptions()
and fills client.exceptions
field with constructed exception classes.
All class names are available in client.exceptions._code_to_exception
dictionary, so you can list all types with following snippet:
client = boto3.client('s3')
for ex_code in client.exceptions._code_to_exception:
print(ex_code)
Hope it helps.
If you don't want to change your markup, this function does the trick:
jQuery('button').click( function(e) {
jQuery('.collapse').collapse('hide');
});
Whenever a BUTTON is clicked, all sections become collapsed. Then bootstrap opens the one you selected.
From Framework Design Guidelines and FxCop rules.:
1. Custom Exception should have a name that ends with Exception
class MyException : Exception
2. Exception should be public
public class MyException : Exception
3. CA1032: Exception should implements standard constructors.
A serialization constructor protected if the type is not sealed and private if the type is sealed. Based on MSDN:
[Serializable()]
public class MyException : Exception
{
public MyException()
{
// Add any type-specific logic, and supply the default message.
}
public MyException(string message): base(message)
{
// Add any type-specific logic.
}
public MyException(string message, Exception innerException):
base (message, innerException)
{
// Add any type-specific logic for inner exceptions.
}
protected MyException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
// Implement type-specific serialization constructor logic.
}
}
or
[Serializable()]
public sealed class MyException : Exception
{
public MyException()
{
// Add any type-specific logic, and supply the default message.
}
public MyException(string message): base(message)
{
// Add any type-specific logic.
}
public MyException(string message, Exception innerException):
base (message, innerException)
{
// Add any type-specific logic for inner exceptions.
}
private MyException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
// Implement type-specific serialization constructor logic.
}
}
It seems to me, that the easiest method by far would be this:
$required = array('a','b','c','d');
$values = array(
'a' => '1',
'b' => '2'
);
$missing = array_diff_key(array_flip($required), $values);
Prints:
Array(
[c] => 2
[d] => 3
)
This also allows to check which keys are missing exactly. This might be useful for error handling.
If you just need read-only access, then c_str()
will do it:
char const *c = myString.c_str();
If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:
std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];
Close/dispose your WebResponse object.
When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.
You've got basically 2 options for "global" variables:
$rootScope
http://docs.angularjs.org/api/ng.$rootScope$rootScope
is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope
is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
and then in a controller:
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/
Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently
Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10
string[] files =
Directory.GetFiles(txtPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);
That last parameter effects exactly what you're referring to. Set it to AllDirectories for every file including in subfolders, and set it to TopDirectoryOnly if you only want to search in the directory given and not subfolders.
Refer to MDSN for details: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx
i'am working with hibernate 5 and postgres, and this worked form me.
@Column(name = "ACCOUNT_TYPE", ***nullable***=false, columnDefinition="varchar2 default 'END_USER'")
@Enumerated(EnumType.STRING)
private AccountType accountType;
$ php artisan route:list
+--------+--------------------------------+----------------------------+-- -----------------+----------------------------------------------------+--------- ---+
| Domain | Method | URI | Name | Action | Middleware |
+--------+--------------------------------+----------------------------+-------------------+----------------------------------------------------+------------+
| | GET|HEAD | / |
| | GET | campaign/showtakeup/{id} | showtakeup | App\Http\Controllers\campaignController@showtakeup | auth | |
routes.php
Route::get('campaign/showtakeup/{id}', ['uses' =>'campaignController@showtakeup'])->name('showtakeup');
campaign.showtakeup.blade.php
@foreach($campaign as $campaigns)
//route parameters; you may pass them as the second argument to the method:
<a href="{{route('showtakeup', ['id' => $campaigns->id])}}">{{ $campaigns->name }}</a>
@endforeach
Hope this solves your problem. Thanks
Unlike what I see in every single other answer, you don't need to use pseudo elements in order to replace the content of a tag with an image
<div class="pvw-title">Facts</div>
div.pvw-title { /* No :after or :before required */
content: url("your URL here");
}
I would have thought this would be the most bootstrap-esque way of doing things:
<button type='button' class='btn btn-success col-xs-12'> First buttton baby </button>
All I'm doing is adding the class col-xs-12
to the button.
There's always a better way for doing things.
var number = 51.93999999999761;
I would like to get four digits precision: 51.94
just do:
number.toPrecision(4);
the result will be: 51.94
It's simpler to use, the -a option :
cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]
If you want to measure CPU time, can use time.process_time()
for Python 3.3 and above:
import time
start = time.process_time()
# your code here
print(time.process_time() - start)
First call turns the timer on, and second call tells you how many seconds have elapsed.
There is also a function time.clock()
, but it is deprecated since Python 3.3 and will be removed in Python 3.8.
There are better profiling tools like timeit
and profile
, however time.process_time() will measure the CPU time and this is what you're are asking about.
If you want to measure wall clock time instead, use time.time()
.
In my case I showed DialogFragment
in Activity
. In this dialog fragment I wrote as in DialogFragment remove black border:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_FRAME, 0)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
super.onCreateDialog(savedInstanceState)
val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
dialog.setTitle(null)
dialog.setCancelable(true)
dialog.setContentView(view)
return dialog
}
Either remove setStyle(STYLE_NO_FRAME, 0)
in onCreate()
or chande/remove onCreateDialog
. Because dialog settings have changed after the dialog has been created.
There's a built-in interface that you can use directly for all gestures:
Here is an explanation for a basic level user:
There is 2 imports be careful in choosing that both are diferent
add compile 'org.jsoup:jsoup:1.10.2'
to dependencies in APP LEVEL build.gradle
&
Just add below code and you are good to go.
private class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (!currentVersion.equalsIgnoreCase(onlineVersion)) {
//show dialog
new AlertDialog.Builder(context)
.setTitle("Updated app available!")
.setMessage("Want to update app?")
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
Toast.makeText(getApplicationContext(), "App is in BETA version cannot update", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
})
.setNegativeButton("Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
new MyAsyncTask().execute();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
You need to use return value of replaceAll()
method. replaceAll()
does not replace the characters in the current string, it returns a new string with replacement.
- String objects are immutable, their values cannot be changed after they are created.
- You may use replace() instead of replaceAll() if you don't need regex.
String str = "abcd=0; efgh=1";
String replacedStr = str.replaceAll("abcd", "dddd");
System.out.println(str);
System.out.println(replacedStr);
outputs
abcd=0; efgh=1
dddd=0; efgh=1
In this case, you can do ajax call inside componentDidMount
, and then update state
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
this.UserList();
}
UserList() {
$.getJSON('https://randomuser.me/api/')
.then(({ results }) => this.setState({ person: results }));
}
render() {
const persons = this.state.person.map((item, i) => (
<div>
<h1>{ item.name.first }</h1>
<span>{ item.cell }, { item.email }</span>
</div>
));
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{ persons }</div>
</div>
);
}
}
public changeAttr(int id)
{
list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
With:
IdItem is the id of the element you want to modify
FieldToModify is the Field of the item that you want to update.
NewValueForTheField is exactly that, the new value.
(It works perfect for me, tested and implemented)
In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0
$ pip uninstall scipy
$ pip install scipy==1.1.0
in Bitbucket go to branches in left hand side menu.
In my scenario I only wanted to remove a specific username/password from the list which had many other saved connections I didn't want to forget. It turns out the SqlStudio.bin
file others are discussing here is a .NET binary serialization of the Microsoft.SqlServer.Management.UserSettings.SqlStudio
class, which can be deserialized, modified and reserialized to modify specific settings.
To accomplish removal of the specific login, I created a new C# .Net 4.6.1 console application and added a reference to the namespace which is located in the following dll: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Microsoft.SqlServer.Management.UserSettings.dll
(your path may differ slightly depending on SSMS version)
From there I could easily create and modify the settings as desired:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Management.UserSettings;
class Program
{
static void Main(string[] args)
{
var settingsFile = new FileInfo(@"C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin");
// Backup our original file just in case...
File.Copy(settingsFile.FullName, settingsFile.FullName + ".backup");
BinaryFormatter fmt = new BinaryFormatter();
SqlStudio settings = null;
using(var fs = settingsFile.Open(FileMode.Open))
{
settings = (SqlStudio)fmt.Deserialize(fs);
}
// The structure of server types / servers / connections requires us to loop
// through multiple nested collections to find the connection to be removed.
// We start here with the server types
var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;
foreach (var serverType in serverTypes)
{
foreach (var server in serverType.Value.Servers)
{
// Will store the connection for the provided server which should be removed
ServerConnectionSettings removeConn = null;
foreach (var conn in server.Connections)
{
if (conn.UserName == "adminUserThatShouldBeRemoved")
{
removeConn = conn;
break;
}
}
if (removeConn != null)
{
server.Connections.RemoveItem(removeConn);
}
}
}
using (var fs = settingsFile.Open(FileMode.Create))
{
fmt.Serialize(fs, settings);
}
}
}
Solution as proposed by Aziz would be:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children,
)
It would not be in the exact center because of padding:
padding: new EdgeInsets.all(25.0),
To make exactly center Column - at least in this case - you would need to remove padding.
In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.
No need to delete any files or add the idea plugin to build.gradle.
There are a few. I was looking into MBTrading for a friend. I didn't get too far, as my friend lost interest. Seemed relatively straigt forward with a C# and VB.Net SDK. They had some docs and everything. This was ~6 months ago, so it may be better (or worse) by now.
IIRC, you can create a demo account for free. I don't remember all the details, but it let you connect to their test server and pull quotes and make fake trades and such to get your software fine tuned.
Don't know much about cost for an actual account or anything.
If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:
Switch to branch "foo" and update it:
$ git checkout foo
$ git pull
You can see the branches you've got by issuing command:
$ git branch
I know this is an old post, but I ran into this same issue with my VMs. Log into the VM and go to Control Panel > System and Security > Windows Firewall > Allowed Apps. Then check all of the boxes next to "File and Printer Sharing" to enable file sharing. This should allow you to ping the VM. The screenshot below is from a 2016 Windows Server but the same method will work on older ones.
Yes but what happens if you start using mixins for example, you cant be having ObjectMapper as a singleton because you will be applying the configuration globally. So you will be adding or setting the mixin classes on the same ObjectMapper instance?
Extending upon Mustafa's answer.
A) Install http://phantomjs.org/ and then
B) install the phantom node module https://github.com/amir20/phantomjs-node
C) Here is an example of rendering a pdf
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open("http://www.google.com").then(function(status) {
page.render('google.pdf').then(function() {
console.log('Page Rendered');
ph.exit();
});
});
});
});
Output of the PDF:
EDIT: Silent printing that PDF
java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf
Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.
Your code will still be compiled and run by the JDK you've selected.
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
on arch linux. (im not sure on other distros) you can view the operstate. which shows up if connected or down if not the operstate lives on
/sys/class/net/(interface name here)/operstate
#you can also put watch
watch -d -n -1 /sys/class/net/(interface name here)/operstate
For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:
<div class="wrap">
<div>
<span>One</span>
<span>Two</span>
</div>
<div>Three</div>
</div>
and use space-between
:
.wrap {
display: flex;
background: #ccc;
justify-content: space-between;
}
This way you can group multiple items to the right(or just one).
To retrieve text of an auto generated span value just do this :
var al = $("#id-span-name").text();
alert(al);
Please check this answer: https://stackoverflow.com/a/38598174/1275924
The idea is to use Cryptolens as the license server. Here's a step-by-step example (in C# and VB.NET). I've also attached a code snippet for key verification below (in C#):
var licenseKey = "GEBNC-WZZJD-VJIHG-GCMVD";
var RSAPubKey = "{enter the RSA Public key here}";
var auth = "{access token with permission to access the activate method}";
var result = Key.Activate(token: auth, parameters: new ActivateModel()
{
Key = licenseKey,
ProductId = 3349,
Sign = true,
MachineCode = Helpers.GetMachineCode()
});
if (result == null || result.Result == ResultType.Error ||
!result.LicenseKey.HasValidSignature(RSAPubKey).IsValid())
{
// an error occurred or the key is invalid or it cannot be activated
// (eg. the limit of activated devices was achieved)
Console.WriteLine("The license does not work.");
}
else
{
// everything went fine if we are here!
Console.WriteLine("The license is valid!");
}
Console.ReadLine();
CSS
div.horizontalgap {
float: left;
overflow: hidden;
height: 1px;
width: 0px;
}
Usage in HTML (for a 10px horizontal gap)
<div class="horizontalgap" style="width:10px"></div>
In case of using NUnit, try this:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
Generic functional form
def select_columns(data_frame, column_names):
new_frame = data_frame.loc[:, column_names]
return new_frame
Specific for your problem above
selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)
Go to
C:\Program Files\MySQL\MySQL Server 5.2\bin
then Open MySQLInstanceConfig file
then complete the wizard.
Click finish
Solve the problem
I think this is the best way to change the port number also.
It works for me
A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed
In another word change the entire value of that variable (name)
or leave it alone.
Example:
my_string = "Hello world"
my_string[0] = "h"
print my_string
you expected this to work and print hello world but this will throw the following error:
Traceback (most recent call last):
File "test.py", line 4, in <module>
my_string[0] = "h"
TypeError: 'str' object does not support item assignment
The interpreter is saying : i can't change the first character of this string
you will have to change the whole string
in order to make it works:
my_string = "Hello World"
my_string = "hello world"
print my_string #hello world
check this table:
I made some modification to @jvd10's solution. The '!important' seems too strong that the container doesn't adapt well when TOC sidebar is displayed. I removed it and added 'min-width' to limit the minimal width.
Here is my .juyputer/custom/custom.css:
/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
width: 99%;
min-width: 1110px;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px;
}
if you are opening page on JavaScript popup then
Response.Write("<script>javascript:window.close();</script>");
will do the job
The better way of sending GET
or POST
requests with PHP
is as below:
<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>
The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
https://github.com/isaacs/npm/issues/2119
I had to execute the command below:
npm config set registry http://registry.npmjs.org/
However, that will make npm
install packages over an insecure HTTP connection. If you can, you should stick with
npm config set registry https://registry.npmjs.org/
instead to install over HTTPS.
I am sure you would've already found your answer... here is the solution I derived at.
That's my CSS.
.field, .actions {
margin-bottom: 15px;
}
.field label {
float: left;
width: 30%;
text-align: right;
padding-right: 10px;
margin: 5px 0px 5px 0px;
}
.field input {
width: 70%;
margin: 0px;
}
And my HTML...
<h1>New customer</h1>
<div class="container form-center">
<form accept-charset="UTF-8" action="/customers" class="new_customer" id="new_customer" method="post">
<div style="margin:0;padding:0;display:inline"></div>
<div class="field">
<label for="customer_first_name">First name</label>
<input class="form-control" id="customer_first_name" name="customer[first_name]" type="text" />
</div>
<div class="field">
<label for="customer_last_name">Last name</label>
<input class="form-control" id="customer_last_name" name="customer[last_name]" type="text" />
</div>
<div class="field">
<label for="customer_addr1">Addr1</label>
<input class="form-control" id="customer_addr1" name="customer[addr1]" type="text" />
</div>
<div class="field">
<label for="customer_addr2">Addr2</label>
<input class="form-control" id="customer_addr2" name="customer[addr2]" type="text" />
</div>
<div class="field">
<label for="customer_city">City</label>
<input class="form-control" id="customer_city" name="customer[city]" type="text" />
</div>
<div class="field">
<label for="customer_pincode">Pincode</label>
<input class="form-control" id="customer_pincode" name="customer[pincode]" type="text" />
</div>
<div class="field">
<label for="customer_homephone">Homephone</label>
<input class="form-control" id="customer_homephone" name="customer[homephone]" type="text" />
</div>
<div class="field">
<label for="customer_mobile">Mobile</label>
<input class="form-control" id="customer_mobile" name="customer[mobile]" type="text" />
</div>
<div class="actions">
<input class="btn btn-primary btn-large btn-block" name="commit" type="submit" value="Create Customer" />
</div>
</form>
</div>
You can see the working example here... http://jsfiddle.net/s6Ujm/
PS: I am a beginner too, pro designers... feel free share your reviews.
use
sudo pip install virtualenv
You have a permission denied error. This states your current user does not have the root permissions.So run the command as a super user.
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
For each document, the update operator $set
can set multiple values, so rather than replacing the entire object in the items
array, you can set the name
and value
fields of the object individually.
{'$set': {'items.$.name': update.name , 'items.$.value': update.value}}
Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):
https://stackoverflow.com/a/42000085
<span class="something" datacustomattribute="">
Hello
</span>
.something::before {
content: attr(datascustomattribute);
position: absolute;
}
Note that the datacustomattribute
must start with data
and be all lowercase to satisfy React.
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
As pprakash mentions above, copying the table.frm files AND the ibdata1 file was what worked for me.
In short:
After that, all was well. (Don't forget to backup if you have success!)
Percentage values are not applicable to border-width
in CSS. This is listed in the spec.
You will need to use JavaScript to calculate the percentage of the element's width or whatever length quantity you need, and apply the result in px
or similar to the element's borders.
I believe the reason there's no straightforward property to access the selected row of a WPF DataGrid is because a DataGrid's selection mode can be set to either the row-level or the cell-level. Therefore, the selection-related properties and events are all written against cell-level selection - you'll always have selected cells regardless of the grid's selection mode, but you aren't guaranteed to have a selected row.
I don't know precisely what you're trying to achieve by handling the CellEditEnding event, but to get the values of all selected cells when you select a row, take a look at handling the SelectedCellsChanged event, instead. Especially note the remarks in that article:
You can handle the SelectedCellsChanged event to be notified when the collection of selected cells is changed. If the selection includes full rows, the Selector.SelectionChanged event is also raised.
You can retrieve the AddedCells and RemovedCells from the SelectedCellsChangedEventArgs in the event handler.
Hope that helps put you on the right track. :)
` Please include either of these:
`#include<sstream>`
using std::istringstream;
You need to use the overflow option, but with the following parameters:
.nav {
max-height:300px;
overflow-y:auto;
}
Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.
If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.
Presumably you want something that adapts itself to the content rather then the the opposite.
Hope it may helpful
If you are ok with manually selecting the column, you could be very fast using pick:
svn st | pick | xargs rm
Just go to any cell of the 2nd column, press c
and then hit enter
global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = new WC_product($cart_item['product_id']);
var_dump($product);
}
I added META-INF folder with context.xml contain
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/SpringGradleDemo"/>
SpringGradleDemo is my project name and it work. My servlet-mapping is "/" I read it here https://tomcat.apache.org/tomcat-5.5-doc/config/context.html
A lot of these answers were outdated, and I spent many hours in frustration (I'm fairly new to Django & web dev in general). However, I found this excellent gist by @iambibhas: https://gist.github.com/iambibhas/5051911
import requests
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
def save_image_from_url(model, url):
r = requests.get(url)
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(r.content)
img_temp.flush()
model.image.save("image.jpg", File(img_temp), save=True)
You have to use querySelectorAll
as you need to select all elements with the said class, again since querySelectorAll
is an array you need to iterate it and add the event handlers
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function (event) {
event.preventDefault();
var choice = confirm("sure u want to delete?");
if (choice) {
return true;
}
});
}
In a nutshell, this is the code which works for me :)
WebDriver driver;
WebElement element;
String value;
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
Your JDK version: Java 8
Your JRE version: Java 9
Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java
into <yourclassname>.java
javac -source 1.8 -target 1.8 *.java
source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.
Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).
I used a few options mentioned above :
del self.left
or setting value to None using
self.left = None
It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,
print("The value of the variable is {}".format(self.left))
you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :
if self.left:
#Then only print stuff
The above command will only print values if self.left is not None
A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if
I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)
I have a performance problem in the first place
I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)
In your example, the performance will anyway be driven by the synchronized access to System.out.println()
, and making this process parallel will have no effect, or even a negative one.
Moreover, remember that parallel streams don't magically solve all the synchronization problems. If a shared resource is used by the predicates and functions used in the process, you'll have to make sure that everything is thread-safe. In particular, side effects are things you really have to worry about if you go parallel.
In any case, measure, don't guess! Only a measurement will tell you if the parallelism is worth it or not.
Unless you want the canvas to upscale your image data automatically (that's what James Black's answer talks about, but it won't look pretty), you have to resize it yourself and redraw the image. Centering a canvas
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
REQUIREMENTS files.
Seriously, I use this in conjunction with virtualenv every day.
QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS
Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.
From Heroku's documentation https://devcenter.heroku.com/articles/python
You create a virtual environment, and set your shell to use it. (bash/*nix instructions)
virtualenv env
source env/bin/activate
Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.
pip install flask
Now you can dump the info about which packages are installed with
pip freeze > requirements.txt
If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:
pip install -r requirements.txt
Any time you can automate tedium like this is awesome.
The following answer is probably the most efficient but has the caveat of only being suitable for 1 to 1 mappings of arguments. This uses the fastest way of concatenating strings (similar to a stringbuilder: array of strings, joined). This is my own code. Probably needs a better separator though.
String.format = function(str, args)
{
var t = str.split('~');
var sb = [t[0]];
for(var i = 0; i < args.length; i++){
sb.push(args[i]);
sb.push(t[i+1]);
}
return sb.join("");
}
Use it like:
alert(String.format("<a href='~'>~</a>", ["one", "two"]));
This worked for me -
HTML -
<div id="sideNote" class="col-sm-3" style="float:right;">
</div>
<div class="footer-wrap">
<div id="footer-div">
</div>
</div>
CSS -
#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}
#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}
JQuery -
function isVisible(elment) {
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elment).offset().top;
return y <= (vpH + st);
}
function setSideNotePos(){
$(window).scroll(function() {
if (isVisible($('.footer-wrap'))) {
$('#sideNote').css('position','absolute');
$('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
} else {
$('#sideNote').css('position','fixed');
$('#sideNote').css('top','auto');
}
});
}
Now call this function like this -
$(document).ready(function() {
setSideNotePos();
});
PS - The Jquery functions are copied from an answer to another similar question on stackoverflow, but it wasn't working for me fully. So I modified it to these functions, as they are shown here. I think the position etc attributes to your divs will depend on how the divs are structured, who their parents and siblings are.
The above function works when both sideNote and footer-wraps are direct siblings.
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(window).load was deprecated in 1.8, and removed in jquery 3.0
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
I'd answer this question with another question: Do you use singeltons/ Are singeltons bad?
Because (almost all) singelton usage is a glorified global variable.
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
Use getRGB(), it helps ( no complicated programs )
Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.
Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers
01001000. 01001001.
The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit
import numpy as np
import threading
def threaded_process(items_chunk):
""" Your main process which runs in thread for each chunk"""
for item in items_chunk:
try:
api.my_operation(item)
except Exception:
print('error with item')
n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
thread_list.append(thread)
thread_list[thr].start()
for thread in thread_list:
thread.join()
go to your project folder via cmd. run the following command
composer update
it will install the missing vendor folder and files in your project.
but in some cases, it gives an error like "Your configuration does not allow connection to ....." in cmd.
for that go to your composer.json file,
change "secure-http": true
to "secure-http": false
but in some cases (as was in my case) you may not find such line in your file. for that do the following action:
change "config": {
"preferred-install": "dist"
}
to
"config": {
"preferred-install": "dist",
"secure-http": false
}
and run again composer update
command.
hope this will solve problem.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
In your example, the variable a
is just a reference to an instance of a string object. When you say a = "ty"
, you are not actually changing the string object, but rather pointing the reference at an entirely different instance of the string class.
Surround the string with <html></html>
and break the lines with <br/>
.
JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Another option is to go to Window->Preferences->Java->Editor->SaveActions and check the Format source code option. Then your source code will be formatted truly automatically each time you save it.
I am surprised why everyone recommends to pass a comparator function to sort()
, that makes sorting really slow!
To sort numbers, just create any TypedArray:
var numArray = new Float64Array([140000, 104, 99]);
numArray = numArray.sort();
console.log(numArray)
_x000D_
You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes:
SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan'
You then have to copy and run the statements in query analyzer.
Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though.
DECLARE @old sysname, @new sysname, @sql varchar(1000)
SELECT
@old = 'jonathan'
, @new = 'dbo'
, @sql = '
IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
WHERE
QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
AND TABLE_SCHEMA = ''' + @old + '''
)
EXECUTE sp_changeobjectowner ''?'', ''' + @new + ''''
EXECUTE sp_MSforeachtable @sql
Got it from this site.
It also talks about doing the same for stored procs if you need to.
I would generally prefer something a bit simpler, like activate
/deactivate
sub-resource (linked by a Link
header with rel=service
).
POST /groups/api/v1/groups/{group id}/activate
or
POST /groups/api/v1/groups/{group id}/deactivate
For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.
What about a wrapper around your existing code:
public Collection<File> getMatchingFiles( String directory, String extension ) {
return new ArrayList<File>()(
getAllFilesThatMatchFilenameExtension( directory, extension ) );
}
I will throw a warning though. If you can live with that warning, then you're done.
Fortunately, I found my lost password along with the keystore path and alias name from my Android studio logs.
if you are running linux / Unix based machines.
Navigate to Library Logs directory
cd ~/Library/Logs/
in there if you remember your android studio version which you used to build the last release APK. Navigate to that Directory
ex : cd AndroidStudio1.5/
In there you will find the log files. in any of the log files (idea.log) you will find your keystore credentials
example
-Pandroid.injected.signing.store.file=/Users/myuserid/AndroidStudioProjects/keystore/keystore.jks,
-Pandroid.injected.signing.store.password=mystorepassword,
-Pandroid.injected.signing.key.alias=myandroidkey,
-Pandroid.injected.signing.key.password=mykeypassword,
I hope this helps for Android Studio users
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
To just get the simple list of folders without full path, you can use:
Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d)
I have a feeling you might need SQL Server's PATINDEX() function. Check this out:
So maybe:
SELECT SUBSTRING(@TEXT, PATINDEX('%the dog%', @TEXT), PATINDEX('%immediately%',@TEXT))
From http://pyyaml.org/wiki/PyYAMLDocumentation:
add_path_resolver(tag, path, kind)
adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.
#!/usr/bin/env python
import yaml
class Person(yaml.YAMLObject):
yaml_tag = '!person'
def __init__(self, name):
self.name = name
yaml.add_path_resolver('!person', ['Person'], dict)
data = yaml.load("""
Person:
name: XYZ
""")
print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}
print data['Person'].name
# XYZ
Just as a normal js object:
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //get
There are two things you're doing with [indexer: string] : string
You can make a general dictionary with explicitly typed fields by using [key: string]: any;
e.g. age
must be number
, while name
must be a string - both are required. Any implicit field can be any type of value.
As an alternative, there is a Map
class:
let map = new Map<object, string>();
let key = new Object();
map.set(key, "value");
map.get(key); // return "value"
This allows you have any Object instance (not just number/string) as the key.
Although its relatively new so you may have to polyfill it if you target old systems.
The string created by calling Hash#inspect
can be turned back into a hash by calling eval
on it. However, this requires the same to be true of all of the objects in the hash.
If I start with the hash {:a => Object.new}
, then its string representation is "{:a=>#<Object:0x7f66b65cf4d0>}"
, and I can't use eval
to turn it back into a hash because #<Object:0x7f66b65cf4d0>
isn't valid Ruby syntax.
However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.
function setMarkers(map,locations){
for (var i = 0; i < locations.length; i++)
{
var loan = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var add = locations[i][3];
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset
});
map.setCenter(marker.getPosition());
marker.content = "<h3>Loan Number: " + loan + '</h3>' + "Address: " + add;
google.maps.events.addListener(marker,'click', function(map,marker){
map.infowindow.setContent(marker.content);
map.infowindow.open(map,marker);
});
}
}
Then move var infowindow = new google.maps.InfoWindow()
to the initialize()
function:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(33.890542, 151.274856),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
map.infowindow = new google.maps.InfoWindow();
setMarkers(map,locations)
}
I would advise reading Java puzzlers. It explains inheritance, generics, abstractions, and wildcards in declarations quite well. http://www.javapuzzlers.com/
The accepted answer is awesome. However, you can still use %
width and attain text-overflow: ellipsis
. The solution is simple:
display: inline-block; /* for em, a, span, etc (inline by default) */
text-overflow: ellipsis;
width: calc (80%); /* The trick is here! */
It seems whenever you use calc
, the final value is rendered in absolute pixels, which consequentially converts 80%
to something like 800px
for a 1000px
-width container. Therefore, instead of using width: [YOUR PERCENT]%
, use width: calc([YOUR PERCENT]%)
.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
If you have dynamic classes or don't know what classes could be already applied then this method I believe is the best approach:
// addClass
$('path').attr('class', function(index, classNames) {
return classNames + ' class-name';
});
// removeClass
$('path').attr('class', function(index, classNames) {
return classNames.replace('class-name', '');
});
Make sure Anonymous access is enabled on IIS -> Authentication.
But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
I would use SharedSizeGroup
<Grid>
<Grid.ColumnDefinition>
<ColumnDefinition SharedSizeGroup="col1"></ColumnDefinition>
<ColumnDefinition SharedSizeGroup="col2"></ColumnDefinition>
</Grid.ColumnDefinition>
<TextBox Background="Azure" Text="Hello" Grid.Column="1" MaxWidth="200" />
</Grid>
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
After doing what everyone else said above, i.e.:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... my navigation bar was still white. So I added this line:
navigationController?.navigationBar.backgroundColor = .clear
... et voila! That seemed to do the trick.
I removed
super.service(req, res);
Then it worked fine for me
You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.
The general form for this would be an UPDATE
statement:
UPDATE <table name>
SET
ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
ColumnA = <bad value> /* or any other search conditions */
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);
A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...
You can use CFArray instead of NSArray. Here is an article explaining how.
CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */
The same applies for the CoreFoundation version of the other containers too.
button.titleLabel.font = <whatever font you want>
For the people wondering why their text isn't showing up, if you do
button.titleLabel.text = @"something";
It won't show up, you need to do:
[button setTitle:@"My title" forState:UIControlStateNormal]; //or whatever you want the control state to be
Maybe this is the answer you are looking for. It finds the last instance of <tr />
and appends the new row after it:
<script type="text/javascript">
$('a').click(function() {
$('#myTable tr:last').after('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>
It sounds like more of an architectual issue, and any timeout/disconnect you can do would be more or less a band-aid. This has to be solved on SQL server side, by the way of read-only replica, transaction log shipping (to give you a read-only server to connect to), replication and such. Basically you give the DMZ sql server that heavy read can go to without killing stuff. This is very common. A well-designed SQL system won't be taken down by DDoS - that'd be like a car that dies if you step on the gas.
That said, if you are at the liberty to change the code, you could guesstimate if the query is too heavy and you could either reject or return only X rows in your stored procedure. If you are mated to some reporting tool and such and can't control the SELECT it generates, you could point it to a view and then do the safety valve in the view.
Also, if up-to-the-minute freshness isn't critical and you could compromise on that, like monthly sales data, then compiling a physical table of complex joins by job to avoid complex joins might do the trick - that way everything would be sub-second per query.
It entirely depends on what you are doing, but there is always a solution. Sometimes it takes extra coding to optimize it, sometimes it takes extra money to get you the secondary read-only DB, sometimes it needs time and attention in index tuning.
So it entirely depends, but I'd start with "what can I compromise? what can I change?" and go from there.
You can also use meta-annotations to externalize the configuration. For example:
@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests {
...
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }
I've encountered an issue calling trying some of the methods on an empty tableView
. Here's another option for Swift 4 that handles empty tableviews.
extension UITableView {
func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
}
func scrollToTop(animated: Bool) {
let indexPath = IndexPath(row: 0, section: 0)
if self.hasRowAtIndexPath(indexPath: indexPath) {
self.scrollToRow(at: indexPath, at: .top, animated: animated)
}
}
}
Usage:
// from yourViewController or yourTableViewController
tableView.scrollToTop(animated: true)//or false
A more modern version of kaiido's answer using fetch would be:
function toObjectUrl(url) {
return fetch(url)
.then((response)=> {
return response.blob();
})
.then(blob=> {
return URL.createObjectURL(blob);
});
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.
You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602
There is another code that's works for me (jQuery).
$(".datepicker").datepicker({_x000D_
format: "dd/mm/yyyy",_x000D_
autoHide: true_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
The .join()
method has a parameter for the separator string. If you want it to be empty instead of the default comma, use
arr.join("");
If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017
Agent queue.
Yes you can, for example:
[textField setKeyboardType:UIKeyboardTypeNumberPad];
Android hasn't provided a native method. Nor the AppCompat.
Try this library: https://github.com/rengwuxian/MaterialEditText
This might be what you want.
I have made a query for you. This will give you Recursive Category with a Single Query:
SELECT id,NAME,'' AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 WHERE prent is NULL
UNION
SELECT b.id,a.name,b.name AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id WHERE a.prent is NULL AND b.name IS NOT NULL
UNION
SELECT c.id,a.name,b.name AS subName,c.name AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id WHERE a.prent is NULL AND c.name IS NOT NULL
UNION
SELECT d.id,a.name,b.name AS subName,c.name AS subsubName,d.name AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id LEFT JOIN Table1 AS d ON d.prent=c.id WHERE a.prent is NULL AND d.name IS NOT NULL
ORDER BY NAME,subName,subsubName,subsubsubName
Here is a fiddle.
The following function returns an object version of your queryString.
You can simply write obj.key1
and obj.key2
to access values of key1
and key2
in parameter.
function getQueryStringObject()
{
var querystring = document.location.search.replace('?','').split( '&' );
var objQueryString={};
var key="",val="";
if(typeof querystring == 'undefined')
{
return (typeof querystring);
}
for(i=0;i<querystring.length;i++)
{
key=querystring[i].split("=")[0];
val=querystring[i].split("=")[1];
objQueryString[key] = val;
}
return objQueryString;
}
And to use this function you can write
var obj= getQueryStringObject();
alert(obj.key1);
As @Heinzi mentioned the character set of the response should be used.
var encoding = response.CharacterSet == ""
? Encoding.UTF8
: Encoding.GetEncoding(response.CharacterSet);
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream, encoding);
var responseString = reader.ReadToEnd();
}
FragmentManager fm = getFragmentManager();
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment);
frag.<specific_function_name>();
GoTo DeviceManager, then right click on the android device and click uninstall driver. Unplug and plug the device back...then a pop will come on your device while your pc installs the required drivers. Click "allow" on the popup. You can see your device when you type "adb devices" in command prompt.
You have applied class "btn-pTool" to span which is an inline element... give display:block
to it and also add some text inside the<a>
tag and the see the result.
Also give a background color and background position as well to the image though default background position is there.. but try doing it this way
If one of the tables M
, S
, D
, or H
has more than one row for a given Id
(if just the Id
column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id
in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).
References:
In Spring boot, Spring Web dependency provides an embedded Apache Tomcat web server. If you remove spring-boot-starter-web dependency in the pom.xml then it doesn't provide an embedded web server.
remove the following dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).
But seriously, there are many:
\n
is the code for end-of-line, \r
means nothing special\n
is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)\r
was the code for end-of-line instead\r\n
, in this order\r\n
is the standard line-termination for text formats on the Internet\r
commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation), \n
commands the roller to roll up one line (a much faster operation) -- that's the reason you always have \r
before \n
, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation.\r
and \n
act similarly (except both in terms of the cursor, as there is no carriage or roller;-)In practice, in the modern context of writing to a text file, you should always use \n
(the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use \r
is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-).
I process a lot of credit card transaction at work, and I can tell you that the expiry date is inclusive.
Also, I agree with Gorgapor. Don't write your own processing code. They are some good tools out there for credit card processing. Here we have been using Monetra for 3 years and it does a pretty decent job at it.
I would go with something like:
public void list(File file) {
System.out.println(file.getName());
File[] children = file.listFiles();
for (File child : children) {
list(child);
}
}
The System.out.println is just there to indicate to do something with the file. there is no need to differentiate between files and directories, since a normal file will simply have zero children.
I solved this exception by changing the target sdk
version from 19 onwards kitkat version AndroidManifest.xml.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
I assume that you have some sort of List
component and some sort of Item
component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
return <Item key={item.id} item={item}
active={item.id === this.props.activeId}
scrollIntoView={this.scrollElementIntoViewIfNeeded} />
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
class Item extends React.Component {
render() {
return <div>something...</div>;
}
componentDidMount() {
this.ensureVisible();
}
componentDidUpdate() {
this.ensureVisible();
}
ensureVisible() {
if (this.props.active) {
this.props.scrollIntoView(React.findDOMNode(this));
}
}
}
A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref
attribute to a certain item and find it with that:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
var active = item.id === this.props.activeId;
var props = {
key: item.id,
item: item,
active: active
};
if (active) {
props.ref = "activeItem";
}
return <Item {...props} />
}
componentDidUpdate(prevProps) {
// only scroll into view if the active item changed last render
if (this.props.activeId !== prevProps.activeId) {
this.ensureActiveItemVisible();
}
}
ensureActiveItemVisible() {
var itemComponent = this.refs.activeItem;
if (itemComponent) {
var domNode = React.findDOMNode(itemComponent);
this.scrollElementIntoViewIfNeeded(domNode);
}
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView()
or the Webkit-specific scrollIntoViewIfNeeded
, which has a polyfill available so you can use it in non-Webkit browsers.
Saving a password for a Git repository HTTPS URL is possible with a ~/.netrc
(Unix) or %HOME%/_netrc
(note the _
) on Windows.
But: That file would store your password in plain text.
Solution: Encrypt that file with GPG (GNU Privacy Guard), and make Git decrypt it each time it needs a password (for push
/pull
/fetch
/clone
operation).
Note: with Git 2.18 (Q2 2018), you now can customize the GPG used to decrypt the encrypted .netrc
file.
See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster
-- in commit 017b7c5, 30 May 2018)
git-credential-netrc
: acceptgpg
option
git-credential-netrc
was hardcoded to decrypt with 'gpg
' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2
'
With Windows:
(Git has a gpg.exe
in its distribution, but using a full GPG installation includes a gpg-agent.exe
, which will memorize your passphrase associated to your GPG key.)
Install gpg4Win Lite
, the minimum gnupg command-line interface (take the most recent gpg4win-vanilla-2.X.Y-betaZZ.exe
), and complete your PATH with the GPG installation directory:
set PATH=%PATH%:C:\path\to\gpg
copy C:\path\to\gpg\gpg2.exe C:\path\to\gpg\gpg.exe
(Note the 'copy
' command: Git will need a Bash script to execute the command 'gpg
'. Since gpg4win-vanilla-2
comes with gpg2.exe
, you need to duplicate it.)
Create or import a GPG key, and trust it:
gpgp --import aKey
# or
gpg --gen-key
(Make sure to put a passphrase to that key.)
Install the credential helper script in a directory within your %PATH%
:
cd c:\a\fodler\in\your\path
curl -o c:\prgs\bin\git-credential-netrc https://raw.githubusercontent.com/git/git/master/contrib/credential/netrc/git-credential-netrc.perl
(Beware: the script is renamed in Git 2.25.x/2.26, see below)
(Yes, this is a Bash script, but it will work on Windows since it will be called by Git.)
Make a _netrc file in clear text
machine a_server.corp.com
login a_login
password a_password
protocol https
machine a_server2.corp.com
login a_login2
password a_password2
protocol https
(Don't forget the 'protocol
' part: 'http
' or 'https
' depending on the URL you will use.)
Encrypt that file:
gpg -e -r a_recipient _netrc
(You now can delete the _netrc
file, keeping only the _netrc.gpg
encrypted one.)
Use that encrypted file:
git config --local credential.helper "netrc -f C:/path/to/_netrc.gpg -v"
(Note the '/
': C:\path\to...
wouldn't work at all.) (You can use at first -v -d
to see what is going on.)
From now on, any Git command using an HTTP(S) URL which requires authentication will decrypt that _netrc.gpg
file and use the login/password associated to the server you are contacting.
The first time, GPG will ask you for the passphrase of your GPG key, to decrypt the file.
The other times, the gpg-agent launched automatically by the first GPG call will provide that passphrase for you.
That way, you can memorize several URLs/logins/passwords in one file, and have it stored on your disk encrypted.
I find it more convenient than a "cache" helper", where you need to remember and type (once per session) a different password for each of your remote services, for said password to be cached in memory.
With Git 2.26 (Q1 2020), the sample credential helper for using .netrc
has been updated to work out of the box. See patch/discussion.
See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 1fd27f8, 25 Dec 2019)
contrib/credential/netrc
: makePERL_PATH
configurableSigned-off-by: Denton Liu
The shebang path for the Perl interpreter in
git-credential-netrc
was hardcoded.
However, some users may have it located at a different location and thus, would have had to manually edit the script.Add a
.perl
prefix to the script to denote it as a template and ignore the generated version.
Augment theMakefile
so that it generatesgit-credential-netrc
fromgit-credential-netrc.perl
, just like other Perl scripts.The Makefile recipes were shamelessly stolen from
contrib/mw-to-git/Makefile
.
And:
With 2.26 (Q1 2020), Sample credential helper for using .netrc has been updated to work out of the box.
See commit 6579d93, commit 1c78c78 (20 Dec 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 1fd27f8, 25 Dec 2019)
contrib/credential/netrc
: work outside a repoSigned-off-by: Denton Liu
Currently,
git-credential-netrc
does not work outside of a git repository. It fails with the following error:fatal: Not a git repository: . at /usr/share/perl5/Git.pm line 214.
There is no real reason why need to be within a repository, though. Credential helpers should be able to work just fine outside the repository as well.
Call the non-self version of
config()
so thatgit-credential-netrc
no longer needs to be run within a repository.
Jeff King (peff
) adds:
I assume you're using a gpg-encrypted
netrc
(if not, you should probably just usecredential-store
).
For "read-only" password access, I find the combination ofpass
with config like this is a bit nicer:[credential "https://github.com"] username = peff helper = "!f() { test $1 = get && echo password=`pass github/oauth`; }; f"
Try using:
SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK
This should make the lock exclusive and hold it for the duration of the transaction.
Maybe you find this simpler
select * from (
select ssn, sum(time) from downloads
group by ssn
order by sum(time) desc
) where rownum <= 10 --top 10 downloaders
Regards
K
Metaclass is a kind of class which defines how the class will behave like or we can say that A class is itself an instance of a metaclass.
There is not really a straightforward way of getting the HTML source code of a webelement
. You will have to use JavaScript. I am not too sure about python bindings, but you can easily do like this in Java. I am sure there must be something similar to JavascriptExecutor
class in Python.
WebElement element = driver.findElement(By.id("foo"));
String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
You can use OutputDebugString
. OutputDebugString
is a macro that depending on your build options either maps to OutputDebugStringA(char const*)
or OutputDebugStringW(wchar_t const*)
. In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L
prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T
macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
Without any further information, which Database etc the best we can do is something like
Sql Server
SELECT TOP 1 * FROM Table ORDER BY ID DESC
MySql
SELECT * FROM Table ORDER BY ID DESC LIMIT 1
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:
Quote:
JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.
Another quote: for the code
var a
a
=
3 console.log(a)
JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;
and:
two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements
... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.
... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:
x
++
y
It is parsed as
x; ++y;
, not asx++; y
So I think to simplify it, that means:
In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return
, break
, continue
, and (2) if it sees ++
or --
on a new line, then it will add the ;
at the end of the previous line.
The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.
With the above said, that means for return
with a line break, the JavaScript interpreter will insert a ;
(quoted again: If a line break appears after any of these words [such as return
] ... JavaScript will always interpret that line break as a semicolon)
and due to this reason, the classic example of
return
{
foo: 1
}
will not work as expected, because the JavaScript interpreter will treat it as:
return; // returning nothing
{
foo: 1
}
There has to be no line-break immediately after the return
:
return {
foo: 1
}
for it to work properly. And you may insert a ;
yourself if you were to follow the rule of using a ;
after any statement:
return {
foo: 1
};
you can use Series.idxmax()
>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>>
All given answers work fine, but I remember learning that using setAlpha can be a bad idea performance wise (more info here). So creating a StateListDrawable is a better idea to manage disabled state of buttons. Here's how:
Create a XML btn_blue.xml in res/drawable folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Disable background -->
<item android:state_enabled="false"
android:color="@color/md_blue_200"/>
<!-- Enabled background -->
<item android:color="@color/md_blue_500"/>
</selector>
Create a button style in res/values/styles.xml
<style name="BlueButton" parent="ThemeOverlay.AppCompat">
<item name="colorButtonNormal">@drawable/btn_blue</item>
<item name="android:textColor">@color/md_white_1000</item>
</style>
Then apply this style to your button:
<Button
android:id="@+id/my_disabled_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/BlueButton"/>
Now when you call btnBlue.setEnabled(true)
OR btnBlue.setEnabled(false)
the state colors will automatically switch.
The suggested for loop is quite fine but you have to check the properties with hasOwnProperty
. I'd rather suggest using Object.keys()
that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
var data = {_x000D_
"messages": [{_x000D_
"msgFrom": "13223821242",_x000D_
"msgBody": "Hi there"_x000D_
}, {_x000D_
"msgFrom": "Bill",_x000D_
"msgBody": "Hello!"_x000D_
}]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
console.log('message index '+ index);_x000D_
Object.keys(message).forEach(function(prop) { _x000D_
console.log(prop + " = " + message[prop]);_x000D_
});_x000D_
});
_x000D_
As of Ruby 2.5 you can use delete_suffix
or delete_suffix!
to achieve this in a fast and readable manner.
The docs on the methods are here.
If you know what the suffix is, this is idiomatic (and I'd argue, even more readable than other answers here):
'abc123'.delete_suffix('123') # => "abc"
'abc123'.delete_suffix!('123') # => "abc"
It's even significantly faster (almost 40% with the bang method) than the top answer. Here's the result of the same benchmark:
user system total real
chomp 0.949823 0.001025 0.950848 ( 0.951941)
range 1.874237 0.001472 1.875709 ( 1.876820)
delete_suffix 0.721699 0.000945 0.722644 ( 0.723410)
delete_suffix! 0.650042 0.000714 0.650756 ( 0.651332)
I hope this is useful - note the method doesn't currently accept a regex so if you don't know the suffix it's not viable for the time being. However, as the accepted answer (update: at the time of writing) dictates the same, I thought this might be useful to some people.
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id
annotation to specify the primary key of an entity.
The @GeneratedValue
annotation is used to specify how the primary key should be generated. In your example you are using an Identity
strategy which
Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
There are other strategies, you can see more here.
If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.
private File createFile(String path, String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(".").getFile() + path + fileName);
// Lets create the directory
try {
file.getParentFile().mkdir();
} catch (Exception err){
System.out.println("ERROR (Directory Create)" + err.getMessage());
}
// Lets create the file if we have credential
try {
file.createNewFile();
} catch (Exception err){
System.out.println("ERROR (File Create)" + err.getMessage());
}
return file;
}
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...
var firstname = $('#firstname').val();
$('ol').append( '<li>' + firstname + '</li>' );
Store the firstname value and then use append
to add that value as an li
to the ol
. I hope this helps :)
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
#!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
" | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"
Here is how to to that:
The header and footer are 30px height.
The footer is stuck to the bottom of the page.
HTML:
<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>
CSS:
#header {
height: 30px;
}
#footer {
height: 30px;
position: absolute;
bottom: 0;
}
body {
height: 100%;
margin-bottom: 30px;
}
Try it on jsfiddle: http://jsfiddle.net/Usbuw/
Cookie is just another HTTP header.
import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")
See urllib2 examples for other ways how to add HTTP headers to your request.
There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.
I had these settings in 'gradle.properties'
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
It is better to use androidx library. So I changed all imports to androidx library and project compiled. visit http://developer.android.com/jetpack/androidx
for information.
Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.
Example: Suppose we had this class:
class ScopeMonitor
{
static string urlFragment = "foo/bar";
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
}
When you access fullUr
, it will be "http://www.example.com/foo/bar".
Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
static string urlFragment = "foo/bar";
}
Your fullUrl
value is now just "http://www.example.com/" since urlFragment
hadn't been initialized at the time fullUrl
was being set. Not good. So, you add a static constructor to take care of the initialization:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl;
static string urlFragment = "foo/bar";
static ScopeMonitor()
{
fullUrl= firstPart + urlFragment;
}
}
Now, no matter what order you have the fields, the initialization will always be correct.
----Ctrl + c then choose Y from the Y/N option provided.
So, you want to treat your .properties
file on the same folder as the main/runnable jar as a file rather than as a resource of the main/runnable jar. In that case, my own solution is as follows:
First thing first: your program file architecture shall be like this (assuming your main program is main.jar and its main properties file is main.properties):
./ - the root of your program
|__ main.jar
|__ main.properties
With this architecture, you can modify any property in the main.properties file using any text editor before or while your main.jar is running (depending on the current state of the program) since it is just a text-based file. For example, your main.properties file may contain:
app.version=1.0.0.0
app.name=Hello
So, when you run your main program from its root/base folder, normally you will run it like this:
java -jar ./main.jar
or, straight away:
java -jar main.jar
In your main.jar, you need to create a few utility methods for every property found in your main.properties file; let say the app.version
property will have getAppVersion()
method as follows:
/**
* Gets the app.version property value from
* the ./main.properties file of the base folder
*
* @return app.version string
* @throws IOException
*/
import java.util.Properties;
public static String getAppVersion() throws IOException{
String versionString = null;
//to load application's properties, we use this class
Properties mainProperties = new Properties();
FileInputStream file;
//the base folder is ./, the root of the main.properties file
String path = "./main.properties";
//load the file handle for main.properties
file = new FileInputStream(path);
//load all the properties from this file
mainProperties.load(file);
//we have loaded the properties, so close the file handle
file.close();
//retrieve the property we are intrested, the app.version
versionString = mainProperties.getProperty("app.version");
return versionString;
}
In any part of the main program that needs the app.version
value, we call its method as follows:
String version = null;
try{
version = getAppVersion();
}
catch (IOException ioe){
ioe.printStackTrace();
}
I just found a free zip database that includes time offset and participation in DST. I do like Erik J's answer, as it would help me choose the actual time zone as opposed to just the offset (because you never can be completely sure on the rules), but I think I might start with this, and have it try to find the best time zone match based on offset/dst configuration. I think I may try to set up a simple version of Development 4.0's answer to check against what I get from the zip info as a sanity test. It's definitely not as simple as I'd hope, but a combination should get me at least 90% sure of a user's time zone.
This code for those who are experiencing the same problem trying to accessing the camera could be written with a safety check.
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
continue
OR in case you want to close the camera/ discontinue if there will be some problem with the frame itself
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break
For reference https://github.com/HackerShackOfficial/AI-Smart-Mirror/issues/36
In Xcode4 go to the Organizer. Choose at library the Provisioning Profiles. Select your provisioning profile and click on the "Refresh" button at the bottom. It will ask you to enter your login and password. After that, the profile is renewed.
Try this, it worked for me.
div{_x000D_
border-radius: 20px;_x000D_
height: 70vh;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
div::before{_x000D_
content: '';_x000D_
display: block;_x000D_
box-sizing: border-box;_x000D_
height: 100%;_x000D_
_x000D_
border: 1em solid transparent;_x000D_
border-image: linear-gradient(to top, red 0%, blue 100%);_x000D_
border-image-slice: 1;_x000D_
}
_x000D_
<div></div>
_x000D_
The link is to the fiddle https://jsfiddle.net/yash009/kayjqve3/1/ hope this helps
I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..
1. onBindViewHolder() methods never got called. --> Problem 1.
2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.
Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.
Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it.
To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager
and paste the code below into it. NO CHANGES REQUIRED
public class CustomLinearLayoutManager extends LinearLayoutManager {
private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();
public CustomLinearLayoutManager(Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
try {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected)
{
foreach (DataGridViewCell cell in row.Cells)
{
int index = cell.ColumnIndex;
if (index == 0)
{
value = cell.Value.ToString();
//do what you want with the value
}
}
}
}
The best i could think of a variable is a int Is a combination with MySQL's functions CAST()
and LENGTH()
.
This method will work on strings, integers, doubles/floats datatypes.
SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int
see demo http://sqlfiddle.com/#!9/ff40cd/44
it will fail if the column has a single character value. if column has a value 'A' then Cast('A' as UNSIGNED) will evaluate to 0 and LENGTH(0) will be 1. so LENGTH(Cast('A' as UNSIGNED))=LENGTH(0) will evaluate to 1=1 => 1
True Waqas Malik totally fogotten to test that case. the patch is.
SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;
Results
**Query #1**
SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;
| 1 | is_int |
| --- | ------ |
| 1 | 1 |
---
**Query #2**
SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;
| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0 |
---
**Query #3**
SELECT "1", (LENGTH(CAST("1" AS UNSIGNED))) = CASE WHEN CAST("1" AS UNSIGNED) = 0 THEN CAST("1" AS UNSIGNED) ELSE (LENGTH("1")) END AS is_int;
| 1 | is_int |
| --- | ------ |
| 1 | 1 |
---
**Query #4**
SELECT "1.1", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1.1" AS UNSIGNED) = 0 THEN CAST("1.1" AS UNSIGNED) ELSE (LENGTH("1.1")) END AS is_int;
| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0 |
---
**Query #5**
SELECT "1a", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1a" AS UNSIGNED) = 0 THEN CAST("1a" AS UNSIGNED) ELSE (LENGTH("1a")) END AS is_int;
| 1a | is_int |
| --- | ------ |
| 1a | 0 |
---
**Query #6**
SELECT "1.1a", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("1.1a" AS UNSIGNED) = 0 THEN CAST("1.1a" AS UNSIGNED) ELSE (LENGTH("1.1a")) END AS is_int;
| 1.1a | is_int |
| ---- | ------ |
| 1.1a | 0 |
---
**Query #7**
SELECT "a1", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("a1" AS UNSIGNED) = 0 THEN CAST("a1" AS UNSIGNED) ELSE (LENGTH("a1")) END AS is_int;
| a1 | is_int |
| --- | ------ |
| a1 | 0 |
---
**Query #8**
SELECT "a1.1", (LENGTH(CAST("a1.1" AS UNSIGNED))) = CASE WHEN CAST("a1.1" AS UNSIGNED) = 0 THEN CAST("a1.1" AS UNSIGNED) ELSE (LENGTH("a1.1")) END AS is_int;
| a1.1 | is_int |
| ---- | ------ |
| a1.1 | 0 |
---
**Query #9**
SELECT "a", (LENGTH(CAST("a" AS UNSIGNED))) = CASE WHEN CAST("a" AS UNSIGNED) = 0 THEN CAST("a" AS UNSIGNED) ELSE (LENGTH("a")) END AS is_int;
| a | is_int |
| --- | ------ |
| a | 0 |
see demo
Start up R in a fresh session and paste this in:
library(ggplot2)
df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c("1999", "2002", "2005", "2008")))), .Names = c("year",
"pollution"), row.names = c(NA, -4L), class = "data.frame")
df[] <- lapply(df, as.numeric) # make all columns numeric
ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year",
y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
Let's try to understand view by the following examples:
a=torch.range(1,16)
print(a)
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.,
15., 16.])
print(a.view(-1,2))
tensor([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 10.],
[11., 12.],
[13., 14.],
[15., 16.]])
print(a.view(2,-1,4)) #3d tensor
tensor([[[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.]],
[[ 9., 10., 11., 12.],
[13., 14., 15., 16.]]])
print(a.view(2,-1,2))
tensor([[[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.]],
[[ 9., 10.],
[11., 12.],
[13., 14.],
[15., 16.]]])
print(a.view(4,-1,2))
tensor([[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]],
[[ 9., 10.],
[11., 12.]],
[[13., 14.],
[15., 16.]]])
-1 as an argument value is an easy way to compute the value of say x provided we know values of y, z or the other way round in case of 3d and for 2d again an easy way to compute the value of say x provided we know values of y or vice versa..
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;
U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake
file, which will help you with generating Makefile
.
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Exception object also contains original response e.response
, that could be useful if need to see error body in response from the server. For example:
try:
r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());