Try
rows = tabDelimitedTable.split("[" + newLine + "]");
This should solve the regex problem.
Also not that important but return type of
System.getProperty("line.separator")
is String so no need to call toString().
If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html
But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:
a) only support windows clients by using "\r\n" as line end.
b) provide two attachment files, one with linux format and one with windows format.
c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.
(\r?\n)|(\r\n?)
to
\n
This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)
To operate on multiple files, either:
The commons-lang library has a constant field available called SystemUtils.LINE_SEPARATOR
I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.
Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.
Try setting the core.autocrlf
configuration option to true
. Also have a look at the core.safecrlf
option.
Actually it sounds like core.safecrlf
might already be set in your repository, because (emphasis mine):
If this is not the case for the current setting of core.autocrlf, git will reject the file.
If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.
Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.
Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.
.gitattributes
file in the root of your git repository:
* text=auto eol=lf
Add and commit it.
Afterwards, you can do following to steps and all files are normalized now:
git rm --cached -r . # Remove every file from git's index.
git reset --hard # Rewrite git's index to pick up all the new line endings.
Source: Answer by kenorb.
Windows' MORE is not reliable, it destroys TABs inevitably and adds lines.
unix2dos is part also of MinGW/MSYS, Cygutils, GnuWin32 and other unix binary port collections - and may already be installed.
When python is there, this one-liner converts any line endings to current platform - on any platform:
TYPE UNIXFILE.EXT | python -c "import sys; sys.stdout.write(sys.stdin.read())" > MYPLATFILE.EXT
or
python -c "import sys; sys.stdout.write(open(sys.argv[1]).read())" UNIXFILE.EXT > MYPLATFILE.EXT
Or put the one-liner into a .bat / shell script and on the PATH according to your platform:
@REM This is any2here.bat
python -c "import sys; sys.stdout.write(open(sys.argv[1]).read())" %1
and use that tool like
any2here UNIXFILE.EXT > MYPLATFILE.EXT
Adding another version based on example above by @ricky89 and @mklement0 with few improvements:
Script to process:
LF-to-CRLF.ps1:
# get current dir
$currentDirectory = Split-Path $MyInvocation.MyCommand.Path -Parent
# create subdir CR-to-CRLF for new files
$outDir = $(Join-Path $currentDirectory "CR-to-CRLF")
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# get all .txt files
Get-ChildItem $currentDirectory -Force | Where-Object {$_.extension -eq ".txt"} | ForEach-Object {
$file = New-Object System.IO.StreamReader -Arg $_.FullName
# Resulting file will be in CR-to-CRLF subdir
$outstream = [System.IO.StreamWriter] $(Join-Path $outDir $($_.BaseName + $_.Extension))
$count = 0
# read line by line, replace CR with CRLF in each by saving it with $outstream.WriteLine
while ($line = $file.ReadLine()) {
$count += 1
$outstream.WriteLine($line)
}
$file.close()
$outstream.close()
Write-Host ("$_`: " + $count + ' lines processed.')
}
I seem to be a bit late to the party and much more of a beginner than any expertise; BUT this worked for me:
window.onbeforeunload = function() {
return false;
};
I placed this as an inline script immediately after my Head and Meta elements, like this:
<script>
window.onbeforeunload = function() {
return false;
}
</script>
This page seems to me to be highly relevant to the originator's requirement (especially the sections headed window.onunload
and window.onbeforeunload
):
https://javascript.info/onload-ondomcontentloaded
Hoping this helps.
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
VS 2017 Git Local Commit DB.lock error on every commit
This issue must have been caused by a corrupt .ignore file.
If your IDE is Visual Studio please follow these steps to resolve this issue:
NB: Bear in mind that your version of visual studio might place these options differently. I am using Visual Studio 2019 Community Edition.
The same problem happened with me but my problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
:)
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
First of all, you need to ensure the port number on which the server is running. Then you can run
mysql -u username -p --port portNumber
on the command line
Try the following expression: ^\d+\.\d{0,2}$
If you want the decimal places to be optional, you can use the following: ^\d+(\.\d{1,2})?$
EDIT: To test a string match in Javascript use the following snippet:
var regexp = /^\d+\.\d{0,2}$/;
// returns true
regexp.test('10.5')
You can also try dropping the index column if it is not needed to compare:
print(df1.reset_index(drop=True) == df2.reset_index(drop=True))
I have used this same technique in a unit test like so:
from pandas.util.testing import assert_frame_equal
assert_frame_equal(actual.reset_index(drop=True), expected.reset_index(drop=True))
You should check for !test
, here is a fiddle showing that.
<span ng-if="!test">null</span>
The problem is that you are trying to access resources (in this case, strings) using getResources().getString(), which will try to get the resources from the Activity. See this source code of the Fragment class:
/**
* Return <code>getActivity().getResources()</code>.
*/
final public Resources getResources() {
if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return mHost.getContext().getResources();
}
mHost
is the object that holds your Activity.
Because the Activity might not be attached, your getResources() call will throw an Exception.
The accepted solution IMHO is not the way to go as you are just hiding the problem. The correct way is just to get the resources from somewhere else that is always guaranteed to exist, like the application context:
youApplicationObject.getResources().getString(...)
The steps below are for Eclipse Indigo Classic Version.
Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser
and use $.support
instead).
To detect mobile you can check for touch events:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}
Taken from What's the best way to detect a 'touch screen' device using JavaScript?
Also check for any long running processes executed from your .NET app against the DB. For example you may be calling a stored procedure or query which does not have enough time to finish which can show in your logs as:
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Check the command timeout settings Try to run a trace (profiler) and see what is happening on the DB side...
Doable, yes. But you'd missing out on a lot of theory behind programming so even though you may know the language well enough to code in it, you won't know how to program well. I'd suggest picking up a few beginner's books on object oriented design while you're at it. The best (for me at least) teaching and helping tools for a new language are tutorials and forums like this (don't forget to google first though, there are a lot of beginner questions answered with a simple search).
Good luck!
cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION"))); // HERE IS NO ERROR
style="padding-top: 8px"
Use this to shift your div up or down in your row. Works wonders for me.
You can use:
newinv=inventory+[add]
but using append is better since it doesn't create a new list:
inventory.append(add)
The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'
That statement is false. That's just how Enterprise Manager or SQL Server chooses to show the date. Internally it's a 8-byte binary value, which is why some of the functions posted by Andrew will work so well.
Kibbee makes a valid point as well, and in a perfect world I would agree with him. However, sometimes you want to bind query results directly to display control or widgets and there's really not a chance to do any formatting. And sometimes the presentation layer lives on a web server that's even busier than the database. With those in mind, it's not necessarily a bad thing to know how to do this in SQL.
This isn't exactly what you are looking for but here is how I've approached this problem in the past;
You can enter a formula like;
=COUNTIF(A1:A10,"Green")
...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
ValidateForm
returns boolean
,not a string
.
When you do this if(ValidateForm() == 'false')
, is the same of if(false == 'false')
, which is not true.
function post(url, formId) {
if(!ValidateForm()) {
// False
} else {
// True
}
}
A bit late but this is what I'm doing with journald
. It's pretty powerful.
You need to be running your docker containers on an OS with systemd-journald
.
docker run -d --log-driver=journald myapp
This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:
journalctl CONTAINER_NAME=myapp -f
which will feed it to your console as it is logged,
journalctl CONTAINER_NAME=myapp > output.log
which gives you the whole lot in a file to take away, or
journalctl CONTAINER_NAME=myapp --since=17:45
Plus you can still see the logs via docker logs ....
if that's your preference.
No more > my.log
or -v "/apps/myapp/logs:/logs"
etc
A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-
, i.e. data-my-attribute="true"
.
Check this UniversalVideoView library its simple and straight forward with controller as well.
Here is the code to play the video
Add this dependancyy in build.gradle
implementation 'com.linsea:universalvideoview:1.1.0@aar'
Java Code
UniversalVideoView mVideoView = findViewById(R.id.videoView);
Uri uri=Uri.parse("https://firebasestorage.googleapis.com/v0/b/contactform-d9534.appspot.com/o/Vexento%20-%20Masked%20Heroes.mp4?alt=media&token=74c2e448-5b1b-47b7-b761-66409bcfbf56");
mVideoView.setVideoURI(uri);
UniversalMediaController mMediaController = findViewById(R.id.media_controller);
mVideoView.setMediaController(mMediaController);
mVideoView.start();
Xml Code
<FrameLayout
android:id="@+id/video_layout"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@android:color/black">
<com.universalvideoview.UniversalVideoView
android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
app:uvv_autoRotation="true"
app:uvv_fitXY="false" />
<com.universalvideoview.UniversalMediaController
android:id="@+id/media_controller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:uvv_scalable="true" />
</FrameLayout>
In Java just use the instanceof operator. This will also take care of subclasses.
ArrayList<Object> listOfObjects = new ArrayList<Object>();
for(Object obj: listOfObjects){
if(obj instanceof String){
}else if(obj instanceof Integer){
}etc...
}
No, you never call the base class destructor, it is always called automatically like others have pointed out but here is proof of concept with results:
class base {
public:
base() { cout << __FUNCTION__ << endl; }
~base() { cout << __FUNCTION__ << endl; }
};
class derived : public base {
public:
derived() { cout << __FUNCTION__ << endl; }
~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};
int main()
{
cout << "case 1, declared as local variable on stack" << endl << endl;
{
derived d1;
}
cout << endl << endl;
cout << "case 2, created using new, assigned to derive class" << endl << endl;
derived * d2 = new derived;
delete d2;
cout << endl << endl;
cout << "case 3, created with new, assigned to base class" << endl << endl;
base * d3 = new derived;
delete d3;
cout << endl;
return 0;
}
The output is:
case 1, declared as local variable on stack
base::base
derived::derived
derived::~derived
base::~base
case 2, created using new, assigned to derive class
base::base
derived::derived
derived::~derived
base::~base
case 3, created with new, assigned to base class
base::base
derived::derived
base::~base
Press any key to continue . . .
If you set the base class destructor as virtual which one should, then case 3 results would be same as case 1 & 2.
UPDATE: For Bootstrap 5
The class name is now "float-end" instead of "pull-right"
<div class="alert alert-info clearfix">
<a href="#" class="alert-link">
Summary:Its some description.......testtesttest
</a>
<button type="button" class="btn btn-primary btn-lg float-end">
Large button
</button>
</div>
For Bootstrap 4 and under
Just add a simple pull-right class to the button, and make sure the container div is clearfixed:
<div class="alert alert-info clearfix">
<a href="#" class="alert-link">
Summary:Its some description.......testtesttest
</a>
<button type="button" class="btn btn-primary btn-lg pull-right">
Large button
</button>
</div>
No, no, no! Please do not try to make your own 'abstract' classes and methods when the language does not support that feature; the same goes for any language feature you wish a given language supported. There is no correct way to implement abstract methods in TypeScript. Just structure your code with naming conventions such that certain classes are never directly instantiated, but without explicitly enforcing this prohibition.
Also, the example above is only going to provide this enforcement at run time, NOT at compile time, as you would expect in Java/C#.
For Windows:
Cross-validation set is used for model selection, for example, select the polynomial model with the least amount of errors for a given parameter set. The test set is then used to report the generalization error on the selected model. From here: https://www.coursera.org/learn/machine-learning/lecture/QGKbr/model-selection-and-train-validation-test-sets
jQuery should be the first:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
You can easily use this function to get the result:
function objetToArray($adminBar){
$reflector = new ReflectionObject($adminBar);
$nodes = $reflector->getProperties();
$out = [];
foreach ($nodes as $node) {
$nod = $reflector->getProperty($node->getName());
$nod->setAccessible(true);
$out[$node->getName()] = $nod->getValue($adminBar);
}
return $out;
}
Use PHP 5 or later.
I dont think youre returning json object from server. just a string.
you need the dataType of the return object to be json
As all said above, you can easily install xampp first from https://www.apachefriends.org/download.html Then follow the instructions as:
http://localhost:80
and database at port 3306
, and PhpMyadmin at http://localhost/phpmyadmin/
Edit your settings.py
file like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '',
}}
Install the following packages in the virtualenv (if you're using django on virtualenv, which is more preferred):
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
That's it!! you have configured Django with MySQL in a very easy way.
Now run your Django project:
python manage.py migrate
python manage.py runserver
As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).
My resulting code is as follow:
Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);
smtpConnectionPool = new SmtpConnectionPool(
SmtpConnectionFactories.newSmtpFactory(session));
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
You can use something like this
[HttpPost]
public async Task<HttpResponseMessage> AddFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key == "companyName")
{
var companyName = val;
}
}
}
// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string path = result.FileData.First().LocalFileName;
//Do whatever you want to do with your file here
return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
}
private string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
public string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.
Use:
return [n]
From help return
return: return [n]
Return from a shell function. Causes a function or sourced script to exit with the return value specified by N. If N is omitted, the return status is that of the last command executed within the function or script. Exit Status: Returns N, or failure if the shell is not executing a function or script.
I guess all other options would be more cryptic. For those who like readable and non-cryptic code:
IF "%ID%"=="0" (
REM do something
) ELSE IF "%ID%"=="1" (
REM do something else
) ELSE IF "%ID%"=="2" (
REM do another thing
) ELSE (
REM default case...
)
It's like an anecdote:
Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...
The IF
ELSE
solution isn't that bad. It's almost as good as python's if
elif
else
. More cryptic 'eggs' can be found here.
I find it useful, because when I didn't know about env, before I started to write script I was doing this:
type nodejs > scriptname.js #or any other environment
and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env
is very useful. Maybe there are details with this, but this is my reason
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
this code works on my proyect and i can select the listview item and checkbox
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true" >
<TextView
android:id="@+id/label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4" />
<CheckBox
android:id="@+id/check"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:focusable="false"
android:text="" >
</CheckBox>
</LinearLayout>
How about (works also for 0 and negatives):
int digits( int x ) {
return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
var src = "data:image/jpeg;base64,";
src += item_image;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "80";
document.querySelector('#imageContainer').innerHTML = newImage.outerHTML;//where to insert your image
When you zip()
together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.
See for yourself:
In [1]: a = b = c = range(20)
In [2]: zip(a, b, c)
Out[2]:
[(0, 0, 0),
(1, 1, 1),
...
(17, 17, 17),
(18, 18, 18),
(19, 19, 19)]
To find out how many elements each tuple contains, you could examine the length of the first element:
In [3]: result = zip(a, b, c)
In [4]: len(result[0])
Out[4]: 3
Of course, this won't work if the lists were empty to start with.
try this,use preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
I see a lot of answers that repeat the old idiom:
If it looks like a duck and quacks like a duck, it's a duck
and then dive into an explanation of what you can do with duck typing, or an example which seems to obfuscate the concept further.
I don't find that much help.
This is the best attempt at a plain english answer about duck typing that I have found:
Duck Typing means that an object is defined by what it can do, not by what it is.
This means that we are less concerned with the class/type of an object and more concerned with what methods can be called on it and what operations can be performed on it. We don't care about it's type, we care about what it can do.
You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-
INSERT specifying values
INSERT INTO Users(weight, desiredWeight)
VALUES (160,145)
INSERT using a SELECT statement
INSERT INTO Users(weight, desiredWeight)
SELECT weight, desiredWeight
FROM AnotherTable
WHERE id = 1
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
Regarding the question of Nothing
Visual Studio's Error List pane only shows you the first line of the error. Invoke View
>Output
and I bet you'll see something like:
c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
due to following members:
'ULONG MysteryUnimplementedMethod(void)' : is abstract
c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'
The JAVA_HOME you have above only points to the JRE, which does not contain the compiler. Set your JAVA_HOME to
/usr/lib/jvm/java-6-openjdk
...and try again.
This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict
built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.
In this way it's possible to avoid key errors.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
... def __missing__(self, key):
... return ''
...
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
The same thing can be done more simply in the following way. The use of the 'default' argument for the get
method of a dict object makes it unnecessary to subclass a dict.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
There's also the PHP UML tool available from pear.
PHP_UML:
Install it on the command line via:
$ pear install pear/php_uml
(This used to be $ pear install pear/php_uml-alpha
but the package has since gone stable.)
Generate your xmi:
$ phpuml -o project.xmi
This will echo standard input to standard output:
import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
In general I would consider setting up of an environment variable (like PYTHONPATH)
to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.
Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the
test environment as well, leading to situations like the tests running fine for a
particular developer but probably failing when some one launches the tests.
Why not so?:
set host=%COMPUTERNAME%
echo %host%
The following expands the excellent answer here by allowing native lower case option as well, and also handles null or empty input and makes this an extension method.
/// <summary>
/// Converts the byte array to a hex string very fast. Excellent job
/// with code lightly adapted from 'community wiki' here: https://stackoverflow.com/a/14333437/264031
/// (the function was originally named: ByteToHexBitFiddle). Now allows a native lowerCase option
/// to be input and allows null or empty inputs (null returns null, empty returns empty).
/// </summary>
public static string ToHexString(this byte[] bytes, bool lowerCase = false)
{
if (bytes == null)
return null;
else if (bytes.Length == 0)
return "";
char[] c = new char[bytes.Length * 2];
int b;
int xAddToAlpha = lowerCase ? 87 : 55;
int xAddToDigit = lowerCase ? -39 : -7;
for (int i = 0; i < bytes.Length; i++) {
b = bytes[i] >> 4;
c[i * 2] = (char)(xAddToAlpha + b + (((b - 10) >> 31) & xAddToDigit));
b = bytes[i] & 0xF;
c[i * 2 + 1] = (char)(xAddToAlpha + b + (((b - 10) >> 31) & xAddToDigit));
}
string val = new string(c);
return val;
}
public static string ToHexString(this IEnumerable<byte> bytes, bool lowerCase = false)
{
if (bytes == null)
return null;
byte[] arr = bytes.ToArray();
return arr.ToHexString(lowerCase);
}
Here is a totally out of the box solution.
In the ahk script, a) Ftp the commands (.ksh) file to the linux machine
b) Use plink like below. Plink should be installed if you have putty.
plink sessionname -l username -pw password test.ksh
or
plink -ssh example.com -l username -pw password test.ksh
All the steps will be performed in sequence whenever you press F9 in windows.
Firstly for technical accuracy, border-radius
is not a HTML5 feature, it's a CSS3 feature.
The best script I've found to render box shadows & rounded corners in older IE versions is IE-CSS3. It translates CSS3 syntax into VML (an IE-specific Vector language like SVG) and renders them on screen.
It works a lot better on IE7-8 than on IE6, but does support IE6 as well. I didn't think much to PIE when I used it and found that (like HTC) it wasn't really built to be functional.
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if "blabla" in line:
found = True
break
return found
if check():
print "found"
else:
print "not found"
Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:
(1) I created the global variable: boolean end1 = false;
The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.
(2) My thread contains:
void myThread() {
end1 = false;
new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
public void onFinish()
{
// do stuff here once at end of time.
end1 = true; // signal that the thread has ended.
}
public void onTick(long millisUntilFinished)
{
// do stuff here repeatedly.
}
}.start();
}
(3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.
Handler h1 = new Handler();
private void checkThread() {
h1.postDelayed(new Runnable() {
public void run() {
if (end1)
// resond to the second thread ending here.
else
h1.postDelayed(this, 1000);
}
}, 1000);
}
(4) Finally, start the whole thing running somewhere in your code by calling:
void startThread()
{
myThread();
checkThread();
}
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
Generally, you could create a channel and receive a stop signal in the goroutine.
There two way to create channel in this example.
channel
context. In the example I will demo context.WithCancel
The first demo, use channel
:
package main
import "fmt"
import "time"
func do_stuff() int {
return 1
}
func main() {
ch := make(chan int, 100)
done := make(chan struct{})
go func() {
for {
select {
case ch <- do_stuff():
case <-done:
close(ch)
return
}
time.Sleep(100 * time.Millisecond)
}
}()
go func() {
time.Sleep(3 * time.Second)
done <- struct{}{}
}()
for i := range ch {
fmt.Println("receive value: ", i)
}
fmt.Println("finish")
}
The second demo, use context
:
package main
import (
"context"
"fmt"
"time"
)
func main() {
forever := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done(): // if cancel() execute
forever <- struct{}{}
return
default:
fmt.Println("for loop")
}
time.Sleep(500 * time.Millisecond)
}
}(ctx)
go func() {
time.Sleep(3 * time.Second)
cancel()
}()
<-forever
fmt.Println("finish")
}
Date.parse()
is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split()
-- might be faster) paired with some parseInt()
will allow you to quickly make a date.
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
In short:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the real property values.
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.
A variation when using xpath in Java using count():
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}
The Event type input
did not work for me on <select>
but changing it to change
works
useEffect(() => {
var event = new Event('change', { bubbles: true });
selectRef.current.dispatchEvent(event); // ref to the select control
}, [props.items]);
For those like me who come to this page with this problem after updating Xcode but don't have an issue with the location setting, restarting my computer did the trick.
It happened to me because of Eclipse memory leak. I had to restart my computer.
After install nvm as @nelsonic describes, this is the easiest way to keep it upgraded:
"node" is a shortcut to the last version, so you can install the last version with:
nvm install node
And to always use the "node" version:
nvm alias default node
Finally to upgrade your node version and keep the installed packages:
nvm install node --reinstall-packages-from=node
According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage
with a CGImage
(explicitly or implicitly), it will return NULL
if the UIImage
is backed by a CIImage
and vice-versa.
Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.
As stated your options are
Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.
While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling
- render:toBitmap:rowBytes:bounds:format:colorSpace:
As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.
Copy all file and replace to /var/lib/mysql ,
after that you must change owner of files to mysql
this is so important if mariadb.service restart has been faild
chown -R mysql:mysql /var/lib/mysql/*
and
chmod -R 700 /var/lib/mysql/*
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
My solution is put those imports in __init__.py
of lib:
in file: __init__.py
import mod1
Then,
import lib
lib.mod1
would work fine.
Right here: http://jt400.sourceforge.net/
This is what I use for that exact purpose.
EDIT: Usage Examples (minus exceptions):
// Driver initialization
AS400JDBCDriver driver = new com.ibm.as400.access.AS400JDBCDriver();
DriverManager.registerDriver(driver);
// JDBC Connection URL
String url = "jdbc:as400://10.10.10.10" + ";promt=false" // disable GUI prompting by jt400 library
// Get a Connection object (this is used to create statements, etc)
Connection conn = DriverManager.getConnection(url, UserString, PassString);
Hope that helps!
/*
korzhao
*/
package rand
import (
crand "crypto/rand"
"math/rand"
"sync"
"time"
"unsafe"
)
// Doesn't share the rand library globally, reducing lock contention
type Rand struct {
Seed int64
Pool *sync.Pool
}
var (
MRand = NewRand()
randlist = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
)
// init random number generator
func NewRand() *Rand {
p := &sync.Pool{New: func() interface{} {
return rand.New(rand.NewSource(getSeed()))
},
}
mrand := &Rand{
Pool: p,
}
return mrand
}
// get the seed
func getSeed() int64 {
return time.Now().UnixNano()
}
func (s *Rand) getrand() *rand.Rand {
return s.Pool.Get().(*rand.Rand)
}
func (s *Rand) putrand(r *rand.Rand) {
s.Pool.Put(r)
}
// get a random number
func (s *Rand) Intn(n int) int {
r := s.getrand()
defer s.putrand(r)
return r.Intn(n)
}
// bulk get random numbers
func (s *Rand) Read(p []byte) (int, error) {
r := s.getrand()
defer s.putrand(r)
return r.Read(p)
}
func CreateRandomString(len int) string {
b := make([]byte, len)
_, err := MRand.Read(b)
if err != nil {
return ""
}
for i := 0; i < len; i++ {
b[i] = randlist[b[i]%(62)]
}
return *(*string)(unsafe.Pointer(&b))
}
24.0 ns/op 16 B/op 1 allocs/
You should never use gets
(or scanf
with an unbounded string size) since that opens you up to buffer overflows. Use the fgets
with a stdin
handle since it allows you to limit the data that will be placed in your buffer.
Here's a little snippet I use for line input from the user:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.
You can test it with something like:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
With Jackson (com.fasterxml.jackson.databind
):
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))
From: How to enable pretty print JSON output (Jackson)
I know this is already in the answers, but I want to write it separately here because chances are, you already have Jackson as a dependency and so all you will need would be an extra line of code
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
From the Intel's manual - Instruction Set Reference, the JE
and JZ
have the same opcode (74
for rel8 / 0F 84
for rel 16/32) also JNE
and JNZ
(75
for rel8 / 0F 85
for rel 16/32) share opcodes.
JE
and JZ
they both check for the ZF
(or zero flag), although the manual differs slightly in the descriptions of the first JE
rel8 and JZ
rel8 ZF
usage, but basically they are the same.
Here is an extract from the manual's pages 464, 465 and 467.
Op Code | mnemonic | Description
-----------|-----------|-----------------------------------------------
74 cb | JE rel8 | Jump short if equal (ZF=1).
74 cb | JZ rel8 | Jump short if zero (ZF ? 1).
0F 84 cw | JE rel16 | Jump near if equal (ZF=1). Not supported in 64-bit mode.
0F 84 cw | JZ rel16 | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
0F 84 cd | JE rel32 | Jump near if equal (ZF=1).
0F 84 cd | JZ rel32 | Jump near if 0 (ZF=1).
75 cb | JNE rel8 | Jump short if not equal (ZF=0).
75 cb | JNZ rel8 | Jump short if not zero (ZF=0).
0F 85 cd | JNE rel32 | Jump near if not equal (ZF=0).
0F 85 cd | JNZ rel32 | Jump near if not zero (ZF=0).
I believe the most performant way is:
$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;
If you want to implement localisation, you may do something like this:
$translationText = "the color is %s";
$translationRed = "red";
$result = sprintf($translationText, $translationRed);
It's a bit slower, but it does not assume grammar rules.
In Windows® systems you can simply try
pip3 list | findstr scikit
scikit-learn 0.22.1
If you are on Anaconda try
conda list scikit
scikit-learn 0.22.1 py37h6288b17_0
And this can be used to find out the version of any package you have installed. For example
pip3 list | findstr numpy
numpy 1.17.4
numpydoc 0.9.2
Or if you want to look for more than one package at a time
pip3 list | findstr "scikit numpy"
numpy 1.17.4
numpydoc 0.9.2
scikit-learn 0.22.1
Note the quote characters are required when searching for more than one word.
Take care.
You should look at the with
binding, as well as controlsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html
I have done with below single git command:
git clone [url] -b [branch-name] --single-branch
I like Maxim's observation that DOS attacks can exhaust server resources. It also happens without an actually malicious adversary.
Some servers have to deal with the 'unintentional DOS attack' which occurs when the client app has a bug with connection leak, where they keep creating a new connection for every new command they send to your server. And then perhaps eventually closing their connections if they hit GC pressure, or perhaps the connections eventually time out.
Another scenario is when 'all clients have the same TCP address' scenario. Then client connections are distinguishable only by port numbers (if they connect to a single server). And if clients start rapidly cycling opening/closing connections for any reason they can exhaust the (client addr+port, server IP+port) tuple-space.
So I think servers may be best advised to switch to the Linger-Zero strategy when they see a high number of sockets in the TIME_WAIT state - although it doesn't fix the client behavior, it might reduce the impact.
you can find the opencv_core248 and other dlls in opencv\build\x86\vc12\bin folder. Just copy the dlls you require into system32 folder. And your app should start working in a flash ! Hope it helps.
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:
Integer.valueOf(x).compareTo(y);
Try this regular expression:
\b(\w+)\s+\1\b
Here \b
is a word boundary and \1
references the captured match of the first group.
ctypes can be used to access dlls, here's a tutorial:
EDIT:
Create a class that extends AsyncTask
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
And call this like new ImageLoadTask(url, imageView).execute();
Direct method:
Use this method and pass your url as string. It returns a bitmap. Set the bitmap to your ImageView.
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
And then this to ImageView like so:
imageView.setImageBitmap(getBitmapFromURL(url));
And dont forget about this permission in maifest.
<uses-permission android:name="android.permission.INTERNET" />
NOTE:
Try to call this method from another thread or AsyncTask because we are performing networking operations.
Use DatatypeConverter.printHexBinary()
:
public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
byte[] myBytes = text.getBytes("UTF-8");
return DatatypeConverter.printHexBinary(myBytes);
}
Example usage:
System.out.println(toHexadecimal("Hello StackOverflow"));
Prints:
48656C6C6F20537461636B4F766572666C6F77
Note: This causes a little extra trouble with Java 9
and newer since the API is not included by default. For reference e.g. see this GitHub
issue.
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
If using google play services, depending on just the libraries you need instead of the whole blob can make things faster.
If your only need is maps, use:
compile 'com.google.android.gms:play-services-maps:6.5.+'
instead of:
compile 'com.google.android.gms:play-services:6.5.+'
The latter brings 20k methods (see blog) into the classpath, which might tip the total method count over 64k.
That would force the use of proguard or multidex even for debug builds. For one of my projects i had the following build times
If developing on sdk 21+, it would possible to optimize multidex builds as stated in the android documentation
android {
productFlavors {
// Define separate dev and prod product flavors.
dev {
// dev utilizes minSDKVersion = 21 to allow the Android gradle plugin
// to pre-dex each module and produce an APK that can be tested on
// Android Lollipop without time consuming dex merging processes.
minSdkVersion 21
}
prod {
// The actual minSdkVersion for the application.
minSdkVersion 14
}
}
...
}
go to: /vendor/laravel/framework/src.Illuminate/Foundation
:
Open application.php file
Search for "version". The below indicates the version.
You can use:
Process proc = Process.GetCurrentProcess();
To get the current process and use:
proc.PrivateMemorySize64;
To get the private memory usage. For more information look at this link.
Use Control.BringToFront
:
myForm.BringToFront();
SQL Developer 4.1, released in May of 2015, added a Model tab which shows table foreign keys which refer to your table in an Entity Relationship Diagram format.
You can use the jQuery ajax method link if you want to pass data from client to server.
In this case you can use $_SERVER['HTTP_USER_AGENT']
variable to found browser user agent.
The problem you encounter comes from the lack of call to super.prepareForReuse()
.
Some other solutions above, suggesting to update the UI of the cell from the delegate's functions, are leading to a flawed design where the logic of the cell's behaviour is outside of its class. Furthermore, it's extra code that can be simply fixed by calling super.prepareForReuse()
. For example :
class myCell: UICollectionViewCell {
// defined in interface builder
@IBOutlet weak var viewSelection : UIView!
override var isSelected: Bool {
didSet {
self.viewSelection.alpha = isSelected ? 1 : 0
}
}
override func prepareForReuse() {
// Do whatever you want here, but don't forget this :
super.prepareForReuse()
// You don't need to do `self.viewSelection.alpha = 0` here
// because `super.prepareForReuse()` will update the property `isSelected`
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.viewSelection.alpha = 0
}
}
With such design, you can even leave the delegate's functions collectionView:didSelectItemAt:
/collectionView:didDeselectItemAt:
all empty, and the selection process will be totally handled, and behave properly with the cells recycling.
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
The (as yet unreleased) change https://github.com/junit-team/junit/pull/386 introduces a @SortMethodsWith
. https://github.com/junit-team/junit/pull/293 at least made the order predictable without that (in Java 7 it can be quite random).
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;
I used System.nanoTime()
for measurements.
I got the same time on both cases - around 1.564 seconds.
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println
command), demonstrated by this code:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
And so on..
And for completeness, Mac OS X
import AppKit
[(screen.frame().size.width, screen.frame().size.height)
for screen in AppKit.NSScreen.screens()]
will give you a list of tuples containing all screen sizes (if multiple monitors present)
If you need a custom title for each option, ng-options
is not applicable. Instead use ng-repeat
with options:
<select ng-model="myVariable">
<option ng-repeat="item in items"
value="{{item.ID}}"
title="Custom title: {{item.Title}} [{{item.ID}}]">
{{item.Title}}
</option>
</select>
I guess I am still unclear about what it is you are trying to do, but JScript.NET might be worth looking into, though Managed JScript seems like it may be more appropriate for your needs (it is more like JavaScript than JScript.NET).
Personally, I thought it would be cool to integrate V8 somehow, but I didn't get past downloading the source code; wish I had the time to actually do something with it.
Another trick is to use
.class {
position: absolute;
visibility:hidden;
display:none;
}
This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none
works later on it will be working. Keep in mind that visibility:hidden
may not remove it from screen readers.
You want something like:
<button class="btn btn-primary btn-block" onclick="this.blur();">...
The .blur() method correctly removes the focus highlighting and doesn't mess up Bootstraps's styles.
First, you need to understand the rules for upgrading the versioning number. You can read more about the semantic version here.
Each version will have x.y.z version where it defines for different purpose as shown below.
To run the scripts, you can define it in your package.json.
"script": {
"buildmajor": "npm version major && ng build --prod",
"buildminor": "npm version minor && ng build --prod",
"buildpatch": "npm version patch && ng build --prod"
}
In your terminal, you just need to npm run accordingly to your needs like
npm run buildpatch
If run it in git repo, the default git-tag-version is true and if you do not wish to do so, you can add below command into your scripts:
--no-git-tag-version
for eg: "npm --no-git-tag-version version major && ng build --prod"
There are cases when they are necessary:
In code I work on I use explicit destructor call in allocators, I have implementation of simple allocator that uses placement new to return memory blocks to stl containers. In destroy I have:
void destroy (pointer p) {
// destroy objects by calling their destructor
p->~T();
}
while in construct:
void construct (pointer p, const T& value) {
// initialize memory with placement new
#undef new
::new((PVOID)p) T(value);
}
there is also allocation being done in allocate() and memory deallocation in deallocate(), using platform specific alloc and dealloc mechanisms. This allocator was used to bypass doug lea malloc and use directly for example LocalAlloc on windows.
Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.
At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ
Using Moment, Underscore and jQuery, to iterate an array of dates.
Sample JSON:
"workerList": [{
"shift_start_dttm": "13/06/2017 20:21",
"shift_end_dttm": "13/06/2017 23:59"
}, {
"shift_start_dttm": "03/04/2018 00:00",
"shift_end_dttm": "03/05/2018 00:00"
}]
Javascript:
function getMinStartDttm(workerList) {
if(!_.isEmpty(workerList)) {
var startDtArr = [];
$.each(d.workerList, function(index,value) {
startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm'));
});
var startDt = _.min(startDtArr);
return start.format('DD/MM/YYYY HH:mm');
} else {
return '';
}
}
Hope it helps.
You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.
EDIT: Adding the actual code:
Solution:
HTML snippet:
<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
<li>Tag 1</li>
<li>Tag 2</li>
<li>Tag 3</li>
<li>Tag 4</li>
<li>Tag 5</li>
</ul>
Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
$(function() {
$('#showAll').click(function(){ //Adds click event listener
$('#tags').toggle('slow'); // Toggles visibility. Use the 'slow' parameter to add a nice effect.
});
});
You can test directly from this link: http://jsfiddle.net/vssJr/5/
Additional Comments on JQuery:
Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.
JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.
Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.
If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.
double value = 3.4555;
String value1 = String.format("% .3f", value) ;
String value2 = value1.substring(0, value1.length() - 1);
System.out.println(value2);
double doublevalue= Double.valueOf(value2);
System.out.println(doublevalue);
You can parameterise it and pass gradle clean build -Pprokey=goodbye
task choiceMyMainClass(type: JavaExec) {
group = "Execution"
description = "Run Option main class with JavaExecTask"
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('prokey')){
if (prokey == 'hello'){
main = 'com.sam.home.HelloWorld'
}
else if (prokey == 'goodbye'){
main = 'com.sam.home.GoodBye'
}
} else {
println 'Invalid value is enterrd';
// println 'Invalid value is enterrd'+ project.prokey;
}
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
getInitialState() {_x000D_
return {email: ''}_x000D_
},_x000D_
handleChange(e) {_x000D_
this.setState({email: e.target.value})_x000D_
},_x000D_
render() {_x000D_
return <div>_x000D_
<input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
<button type="button" disabled={!this.state.email}>Button</button>_x000D_
</div>_x000D_
}_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
We can do this sort of thing with the advent of the format
method since python2.6:
>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'
Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:
>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'
And as of python3.6, this can be expressed as an inline formatted string:
Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'
You can also use
SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...
to initialise the counter variable.
Compile is the process of creating an executable program from code written in a compiled programming language. Compiling allows the computer to run and understand the program without the need of the programming software used to create it. When a program is compiled it is often compiled for a specific platform (e.g. IBM platform) that works with IBM compatible computers, but not other platforms (e.g. Apple platform). The first compiler was developed by Grace Hopper while working on the Harvard Mark I computer. Today, most high-level languages will include their own compiler or have toolkits available that can be used to compile the program. A good example of a compiler used with Java is Eclipse and an example of a compiler used with C and C++ is the gcc command. Depending on how big the program is it should take a few seconds or minutes to compile and if no errors are encountered while being compiled an executable file is created.check this information
Example:
use: android:textStyle="bold"
<TextView
android:id="@+id/txtVelocidade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/txtlatitude"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp"
android:textStyle="bold"
android:text="Aguardando GPS"
android:textAppearance="?android:attr/textAppearanceLarge" />
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
I put this right after the onClick(View v)
event.
You need to import android.view.inputmethod.InputMethodManager
;
The keyboard hides when you click the button.
Based on the accepted answer by delnan.
What if one of your wanted keys aren't in the old_dict? The delnan solution will throw a KeyError exception that you can catch. If that's not what you need maybe you want to:
only include keys that excists both in the old_dict and your set of wanted_keys.
old_dict = {'name':"Foobar", 'baz':42}
wanted_keys = ['name', 'age']
new_dict = {k: old_dict[k] for k in set(wanted_keys) & set(old_dict.keys())}
>>> new_dict
{'name': 'Foobar'}
have a default value for keys that's not set in old_dict.
default = None
new_dict = {k: old_dict[k] if k in old_dict else default for k in wanted_keys}
>>> new_dict
{'age': None, 'name': 'Foobar'}
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
BindingSource
is the only way without going for a 3rd party ORM, it may seem long winded at first but the benefits of one update method on the BindingSource
are so helpful.
If your source is say for example a list of user strings
List<string> users = GetUsers();
BindingSource source = new BindingSource();
source.DataSource = users;
dataGridView1.DataSource = source;
then when your done editing just update your data object whether that be a DataTable
or List of user strings like here and ResetBindings
on the BindingSource
;
users = GetUsers(); //Update your data object
source.ResetBindings(false);
Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid
:
import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)
There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes
object instead of a Facet Grid
. These are different things, and the Axes.set_xticklabels()
method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes
. The lesson is that it's important to pay attention to what kind of objects you are working with.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
there is a JDK tools executed via command line as following :
native2ascii -encoding utf8 src.txt output.txt
Example :
src.txt
??? ???? ?????? ??????
output.txt
\u0628\u0633\u0645 \u0627\u0644\u0644\u0647 \u0627\u0644\u0631\u062d\u0645\u0646 \u0627\u0644\u0631\u062d\u064a\u0645
If you want to use it in your Java application, you can wrap this command line by :
String pathSrc = "./tmp/src.txt";
String pathOut = "./tmp/output.txt";
String cmdLine = "native2ascii -encoding utf8 " + new File(pathSrc).getAbsolutePath() + " " + new File(pathOut).getAbsolutePath();
Runtime.getRuntime().exec(cmdLine);
System.out.println("THE END");
Then read content of the new file.
To create a valid DSA format private key supported by Paramiko in Puttygen.
Click on Conversions then Export OpenSSH Key
Your bat file could be like:
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj
PAUSE
EXIT
;with C as
(
select Rel.t2ID,
Rel.t1ID,
t1.Price,
row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
from @t1 as T1
inner join @relation as Rel
on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
T2.Name as T2Name,
T2.Orders,
T1.ID as T1ID,
T1.Name as T1Name,
T1Sum.Price
from @t2 as T2
inner join (
select C1.t2ID,
sum(C1.Price) as Price,
C2.t1ID
from C as C1
inner join C as C2
on C1.t2ID = C2.t2ID and
C2.rn = 1
group by C1.t2ID, C2.t1ID
) as T1Sum
on T2.ID = T1Sum.t2ID
inner join @t1 as T1
on T1.ID = T1Sum.t1ID
Remove 'javascript:' from your code and it should work.
Do you happen to use FireFox? I have learned from someone else that FireFox no longer accepts the 'javascript:' string. However, for the life of me, I cannot find the original source (though I believe it was somewhere in FF update notes).
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
This is how I made it without extra css or jquery:
<div class="form-group">
<div class="input-group">
<label class="sr-only" for="extra3">Extra name 3</label>
<input type="text" id="extra3" class="form-control" placeholder="Extra name">
<span class="input-group-addon">
<label class="checkbox-inline">
Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
</label>
</span>
<span class="input-group-addon">
<label class="checkbox-inline">
Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
</label>
</span>
<span class="input-group-addon">
To be paid?
<select>
<option value="online">Online</option>
<option value="on spot">On Spot</option>
</select>
</span>
</div>
</div>
In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.
This is how I managed to make it work:
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew<Task<T>>(delegate
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap<T>().GetAwaiter().GetResult();
}
Then I called it like this:
Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));
Try doing this :
awk '{print substr($0, 1, length($0)-1)}' file.txt
This is more generic than just removing the final comma but any last character
If you'd want to only remove the last comma with awk :
awk '{gsub(/,$/,""); print}' file.txt
Try: Console.WriteLine
(type out
for a Visual Studio snippet)
Console.WriteLine(stuff);
Another way is to use System.Diagnostics.Debug.WriteLine
:
System.Diagnostics.Debug.WriteLine(stuff);
Debug.WriteLine
may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine
won't be rendered in Output window but only in the Console itself in case of Console Application type.
Another difference is that Debug.WriteLine
will not print anything in Release configuration.
The problem of converting from any non-unicode source to a unicode SQL Server table can be solved by:
try this which is working for me in my test demo
<script>
$(document).ready(function(){
$('#dropdown').change(function()
{
// var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
//Depend on Value i.e. 0 or 1 respective function gets called.
switch(text){
case 'Reporting':
// alert("hello1");
$("#td1").hide();
break;
case 'Buyer':
//alert("hello");
$("#td1").show();
break;
//etc...
default:
alert("catch default");
break;
}
});
});
</script>
there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables
then add new path enter this in your variable path and values
If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.
_
has 3 main conventional uses in Python:
To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the gettext documentation for example), as in code like
raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name:
To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
label, has_label, _ = text.partition(':')
As part of a function definition (using either def
or lambda
), where
the signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like:
def callback(_):
return True
[For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]
This use case can conflict with the translation lookup use case, so it is necessary to avoid using _
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __
, as their throwaway variable for exactly this reason).
Linters often recognize this use case. For example year, month, day = date()
will raise a lint warning if day
is not used later in the code. The fix, if day
is truly not needed, is to write year, month, _ = date()
. Same with lambda functions, lambda arg: 1.0
creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0
. An unused variable is often hiding a bug/typo (e.g. set day
but use dya
in the next line).
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
Mine says:
Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5
Use of pseudo-element as suggested by Terry has one PRO and one CON:
Anyway is a great solution.
OTHER SOLUTIONS:
If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:
outline
property combined with border
and a single inset box-shadow
box-shadow
combined with border
.Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border
class):
.left
{
outline: 4px solid #fff;
box-shadow:inset 0 0 0 4px #fff;
}
.right
{
box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}
LESS code:
You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.
Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):
@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;
.double-border
{
background-color: @content-color;
border: @double-border-size solid @content-color;
padding: 2em;
width: 16em;
height: 16em;
float:left;
margin-right:20px;
text-align:center;
}
.left
{
outline: @double-border-size solid @inset-border-color;
box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}
.right
{
box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}
The purpose is that you can give a default value if the key is not found, which is very useful
dictionary.get("Name",'harry')
If you are using cocos2d, you may see an issue with [parentView bringSubviewToFront:view], at least it was not working for me. Instead of bringing the view I wanted to the front, I send the other views back and that did the trick.
[[[CCDirector sharedDirector] view] sendSubviewToBack:((UIButton *) button)];
I am using DBLINK to connect internal database for cross database queries.
Reference taken from this article.
Install DbLink extension.
CREATE EXTENSION dblink;
Verify DbLink:
SELECT pg_namespace.nspname, pg_proc.proname
FROM pg_proc, pg_namespace
WHERE pg_proc.pronamespace=pg_namespace.oid
AND pg_proc.proname LIKE '%dblink%';
Test connection of database:
SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');
Do you really need to do that programmatically?
Just considering the title: You could use a ShapeDrawable as android:background…
For example, let's define res/drawable/my_custom_background.xml
as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
I've not tested but it should work.
Update:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file
>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0))
>>> print(columnNames)
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart
which always gives the full date and time the process started:
# ps -p 1 -wo pid,lstart,cmd
PID STARTED CMD
1 Mon Dec 23 00:31:43 2013 /sbin/init
# ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd
USER PID %CPU %MEM VSZ RSS TT STAT STARTED CMD
root 1 0.0 0.1 2800 1152 ? Ss Mon Dec 23 00:31:44 2013 /sbin/init
root 5151 0.3 0.1 4732 1980 pts/2 S Sat Mar 8 16:50:47 2014 bash
For a discussion of how the information is published in the /proc filesystem, see https://unix.stackexchange.com/questions/7870/how-to-check-how-long-a-process-has-been-running
(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:
# date; ls -ld /proc/1 /proc/$$
Sat Mar 8 17:14:21 EST 2014
dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1
dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151
Note that in this case I ran a "ps -p 1" command at about 16:50, then spawned a new bash shell, then ran the "ps -p 1 -p $$" command within that shell shortly afterward....)
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
Alternatively to hasProperty
you can try hamcrest-more-matchers where
matcher with extracting function. In your case it will look like:
import static com.github.seregamorph.hamcrest.MoreMatchers.where;
assertThat(myClass.getMyItems(), contains(
where(MyItem::getName, is("foo")),
where(MyItem::getName, is("bar"))
));
The advantages of this approach are:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
but: item 0: was "wrong-name"
I believe that the assumption that the graph is connected can be handful. thus, you can use the proof shown above, that the running time is O(|V|). if not, then |E|>|V|. reminder: the running time of DFS is O(|V|+|E|).
A simple way to do it would be to just annotate the Quartz Jobs with @Component
annotation, and then Spring will do all the DI magic for you, as it is now recognized as a Spring bean. I had to do something similar for an AspectJ
aspect - it was not a Spring bean until I annotated it with the Spring @Component
stereotype.
The extension method worked great for me with one exception that if the user logs out there old claim sets still existed so with a tiny modification as in passing usermanager through everything works great and you dont need to logout and login. I cant answer directly as my reputation has been dissed :(
public static class ClaimExtensions
{
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
{
RemoveClaim(currentPrincipal, key, userManager);
}
// add new claim
var claim = new Claim(key, value);
identity.AddClaim(claim);
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
//Persist to store
userManager.AddClaim(identity.GetUserId(),claim);
}
public static void RemoveClaim(this IPrincipal currentPrincipal, string key, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return ;
// check for existing claim and remove it
var existingClaims = identity.FindAll(key);
existingClaims.ForEach(c=> identity.RemoveClaim(c));
//remove old claims from store
var user = userManager.FindById(identity.GetUserId());
var claims = userManager.GetClaims(user.Id);
claims.Where(x => x.Type == key).ToList().ForEach(c => userManager.RemoveClaim(user.Id, c));
}
public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.First(c => c.Type == key);
return claim.Value;
}
public static string GetAllClaims(this IPrincipal currentPrincipal, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claims = userManager.GetClaims(identity.GetUserId());
var userClaims = new StringBuilder();
claims.ForEach(c => userClaims.AppendLine($"<li>{c.Type}, {c.Value}</li>"));
return userClaims.ToString();
}
}
Use DecimalFormat
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(myDouble);
System.out.println(fString);
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
I know this is an old question, but I came across a main thread one-liner that I use in both Kotlin and Java. This may not be the best solution for a service, but for calling something that will change the UI inside of a fragment this is extremely simple and obvious.
Java (8):
getActivity().runOnUiThread(()->{
//your main thread code
});
Kotlin:
this.runOnUiThread {
//your main thread code
}
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en',
includedLanguages: 'es',
layout: google.translate.TranslateElement.InlineLayout.SIMPLE
}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function MyApp() {
const location = useLocation();
useEffect(() => {
console.log('route has been changed');
...your code
},[location.pathname]);
}
with hooks
Use this function:
$(".price").each(function(){
total_price += parseInt($(this).val());
});
Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:
storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getAlbumName()
);
The picture doesn't go to the album. To do this, you need to call a scan:
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery
My Windows 10 machine was automagically updated today. Looks like the "Windows 10 Anniversary update" When I restarted Virtualbox my server with a bridged adapter showed same as OP. I tried rerunning the VirtualBox installer (it did a Repair) - that did not fix the issue. I tried running the installer again as Admin (it did a Repair) - that did not fix. I ran the installer and selected UnInstall, then ran it again to Install. And the Network adapter settings looked good. Server started and connected to my network as usual. Whew. Hope this helps someone.
In php.ini
, I had to change
extension_dir = "ext"
to
extension_dir = "C:/PHP/ext"
as my PHP was installed in C:\PHP
. I had to use /
instead of \
, and then it worked.
Also uncomment mbstrings
, mysqli
and mysql
extensions.
In the jQuery source code we have jQuery.fn = jQuery.prototype = {...}
since jQuery.prototype
is an object the value of jQuery.fn
will simply be a reference to the same object that jQuery.prototype
already references.
To confirm this you can check jQuery.fn === jQuery.prototype
if that evaluates true
(which it does) then they reference the same object
Using boto3
import logging
import boto3
from botocore.exceptions import ClientError
def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name
# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True
For more:- https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html
Try something like this:
IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();
There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.
try this
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd
Nathan's answer will give you jokes from last 24, 168, and 744 hours, NOT the jokes from today, this week, this month. If that's what you want, great, but I think you might be looking for something different.
Using his code, at noon, you will get the jokes beginning yesterday at noon, and ending today at noon. If you really want today's jokes, try the following:
SELECT * FROM jokes WHERE date >= CURRENT_DATE() ORDER BY score DESC;
You would have to do something a little different from current week, month, etc., but you get the idea.
Use npm ls (there is even json output)
From the script:
test.js:
function npmls(cb) {
require('child_process').exec('npm ls --json', function(err, stdout, stderr) {
if (err) return cb(err)
cb(null, JSON.parse(stdout));
});
}
npmls(console.log);
run:
> node test.js
null { name: 'x11', version: '0.0.11' }
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
see the link also MySQL UPDATE
public static void SendMail(MailMessage Message)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.googlemail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("[email protected]", "password");
client.Send(Message);
}
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):
RouterModule.forRoot([{ path: "", component: LoginComponent}])
Just developed solution to detect when scrolling finished app-wide: https://gist.github.com/k06a/731654e3168277fb1fd0e64abc7d899e
It is based on idea of tracking changes of runloop modes. And perform blocks at least after 0.2 seconds after scrolling.
This is core idea for tracking runloop modes changes iOS10+:
- (void)tick {
[[NSRunLoop mainRunLoop] performInModes:@[ UITrackingRunLoopMode ] block:^{
[self tock];
}];
}
- (void)tock {
self.runLoopModeWasUITrackingAgain = YES;
[[NSRunLoop mainRunLoop] performInModes:@[ NSDefaultRunLoopMode ] block:^{
[self tick];
}];
}
And solution for low deployment targets like iOS2+:
- (void)tick {
[[NSRunLoop mainRunLoop] performSelector:@selector(tock) target:self argument:nil order:0 modes:@[ UITrackingRunLoopMode ]];
}
- (void)tock {
self.runLoopModeWasUITrackingAgain = YES;
[[NSRunLoop mainRunLoop] performSelector:@selector(tick) target:self argument:nil order:0 modes:@[ NSDefaultRunLoopMode ]];
}
let INT_VALUE=80
let FLOAT_VALUE:Double= 80.9999
let doubleValue=65.0
let DOUBLE_VALUE:Double= 65.56
let STRING_VALUE="Hello"
let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE);
println(str);
A key consideration that hasn't been much discussed is support and updates.
Log4Net hasn't been updated since version 1.2.10 was published April 19, 2006.
In contrast, NLog has been actively supported since 2006 will soon release NLog 2.0 supporting many platforms that didn't exist when log4net was last updated such as:
Fenwick Tree. It's a data structure to keep count of the sum of all elements in a vector, between two given subindexes i and j. The trivial solution, precalculating the sum since the begining doesn't allow to update a item (you have to do O(n) work to keep up).
Fenwick Trees allow you to update and query in O(log n), and how it works is really cool and simple. It's really well explained in Fenwick's original paper, freely available here:
http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol24/issue3/spe884.pdf
Its father, the RQM tree is also very cool: It allows you to keep info about the minimum element between two indexes of the vector, and it also works in O(log n) update and query. I like to teach first the RQM and then the Fenwick Tree.
I later found that, there is an official way to see all the routes, by going to http://localhost:3000/rails/info/routes. Official docs: https://guides.rubyonrails.org/routing.html#listing-existing-routes
Though, it may be late, But I love the error page which displays all the routes. I usually try to go at /routes
(or some bogus) path directly from the browser. Rails server automatically gives me a routing error page as well as all the routes and paths defined. That was very helpful :)
So, Just go to http://localhost:3000/routes
Maybe it's obvious for you guys but I scratched my head for a while because the folder didn't show up in the files app. I actually needed to store something in the folder. you could achieve this by
For multiple files input using lodash or underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
If your close button is going to be text, this works very well for me:
#close {
position: fixed;
width: 70%; /* the width of the parent */
text-align: right;
}
#close span {
cursor: pointer;
}
Then your HTML
can just be:
<div id="close"><span id="x">X</span></div>
In my case, I was seeing this error because I am using a popular open source CMS and the directory which was causing issues was the uploads directory which the CMS writes to.
So what it was saying is that there are files which you don't have, but which you can't get from versioning.
I'm grabbing all the files from the live site to my local, then I'll check this into the repo in the hope that this fixes the issue.
I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString()
method in your enum.
public class CustomObjectMapper extends ObjectMapper {
@PostConstruct
public void customConfiguration() {
// Uses Enum.toString() for serialization of an Enum
this.enable(WRITE_ENUMS_USING_TO_STRING);
// Uses Enum.toString() for deserialization of an Enum
this.enable(READ_ENUMS_USING_TO_STRING);
}
}
There are more enum-related features available, see here:
https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
10061 is WSAECONNREFUSED, 'connection refused', which means there was nothing listening at the IP:port you tried to connect to.
There was a firewall product around the year 2000 that issued refusals instead of ignoring incoming connections to blocked ports, but this was quickly recognised as an information leak to attackers and corrected or withdrawn.
prefix the comment with a single-quote. there is no need for an "end" tag.
'this is a comment
Extend to multiple lines using the line-continuation character, _
:
'this is a multi-line _
comment
This is an option in the toolbar to select a line(s) of code and comment/uncomment:
While the previous answers may work in a fashion, I think that using BehaviorSubject is the correct way if you want to continue using observables.
Example:
this.store.subscribe(
(data:any) => {
myService.myBehaviorSubject.next(data)
}
)
In the Service:
let myBehaviorSubject = new BehaviorSubjet(value);
In component.ts:
this.myService.myBehaviorSubject.subscribe(data => this.myData = data)
I hope this helps!
This solution only for chrome browser. I am not sure about other browser.
The solution:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
works very well.