It's not a big deal, it's pretty easy to switch between them. MSTest being integrated isn't a big deal either, just grab testdriven.net.
Like the previous person said pick a mocking framework, my favourite at the moment is Moq.
As far as I can tell, most of the other answers have a few problems.
The correct way to do this for a disk-based (as opposed to web-based), non-GACed assembly is to use the currently executing assembly's CodeBase
property.
This returns a URL (file://
). Instead of messing around with string manipulation or UnescapeDataString
, this can be converted with minimal fuss by leveraging the LocalPath
property of Uri
.
var codeBaseUrl = Assembly.GetExecutingAssembly().CodeBase;
var filePathToCodeBase = new Uri(codeBaseUrl).LocalPath;
var directoryPath = Path.GetDirectoryName(filePathToCodeBase);
I tried a lot of the suggested options and none appeared to work (I won't list the various problems). What I ended up doing, which worked, was simple and intuitive (to me) was:
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="@this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
If you're dealing with an input element, I found it useful to set the pointer focus to back itself.
$('input').on('keydown', function(e) {
if (e.keyCode == 9) {
$(this).focus();
e.preventDefault();
}
});
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
when your add permission in manifest then in eclipse go to project and clic
k on clean project
To copy a selected text ('Text To Copy') to your clipboard, create a Bookmarklet (browser bookmark that executes JavaScript) and execute it (click on it). It will create a temporary textarea.
Code from GitHub:
https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d
(function (text) {
var node = document.createElement('textarea');
var selection = document.getSelection();
node.textContent = text;
document.body.appendChild(node);
selection.removeAllRanges();
node.select();
document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(node);
})('Text To Copy');
NPM is used to manage packages and download them. However, NPX must be used as the tool to execute Node Packages
Try using NPX nodemon ...
Hope this helps!
I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.
I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.
I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.
Experiment 1
Parallel.For(0, 1000000000, x => Method1());
Experiment 2
for (int i = 0; i < 1000000000; i++)
{
Task o = new Task(Method1);
o.Start();
}
InnoDB supports RENAME TABLE statement to move table from one database to another. To use it programmatically and rename database with large number of tables, I wrote a couple of procedures to get the job done. You can check it out here - SQL script @Gist
To use it simply call the renameDatabase procedure.
CALL renameDatabase('old_name', 'new_name');
Tested on MariaDB and should work ideally on all RDBMS using InnoDB transactional engine.
u can also try from yours design
<div <%=If(True = True, "style='display: none;'", "")%> >True</div>
<div <%=If(True = False, "style='display: none;'", "")%> >False</div>
<div <%=If(Session.Item("NameExist") IsNot Nothing, "style='display: none;'", "")%> >NameExist</div>
<div <%=If(Session.Item("NameNotExist") IsNot Nothing, "style='display: none;'", "")%> >NameNotExist</div>
Output html
<div style='display: none;' > True</div>
<div >False</div>
<div style='display: none;' >NameExist</div>
<div >NameNotExist</div>
curl command:
curl -X PUT http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F taskStatus=1
python requests - More complicated POST requests:
updateTaskUrl = "http://127.0.0.1:8080/api/xxx"
updateInfoDict = {
"taskStatus": 1,
}
resp = requests.put(updateTaskUrl, data=updateInfoDict)
curl command:
curl -X POST http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F file=@/Users/xxx.txt
python requests - POST a Multipart-Encoded File:
filePath = "/Users/xxx.txt"
fileFp = open(filePath, 'rb')
fileInfoDict = {
"file": fileFp,
}
resp = requests.post(uploadResultUrl, files=fileInfoDict)
that's all.
Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.
If you want statics, use an abstract class and inherit it, otherwise, remove the static.
Hope that helps!
There is an excellent eluceo/ical package that allows you to easily create ics files.
Here is an example usage from docs:
// 1. Create new calendar
$vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com');
// 2. Create an event
$vEvent = new \Eluceo\iCal\Component\Event();
$vEvent->setDtStart(new \DateTime('2012-12-24'));
$vEvent->setDtEnd(new \DateTime('2012-12-24'));
$vEvent->setNoTime(true);
$vEvent->setSummary('Christmas');
// Adding Timezone (optional)
$vEvent->setUseTimezone(true);
// 3. Add event to calendar
$vCalendar->addComponent($vEvent);
// 4. Set headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="cal.ics"');
// 5. Output
echo $vCalendar->render();
when you bind localhost
or 127.0.0.1
, it means you can only connect to your service from local.
you cannot bind 10.0.0.1
because it not belong to you, you can only bind ip owned by your computer
you can bind 0.0.0.0
because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip
This will also work on iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
Building on Barry Wark's excellent explanation...
What is so important about the ternary operator is that it can be used in places that an if-else cannot. ie: Inside a condition or method parameter.
[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]
...which is a great use for preprocessor constants:
// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")
// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]
This saves you from having to use and release local variables in if-else patterns. FTW!
This option should be enabled in portal:
I had exact the same problem! I had been searching and searching for days because all the babble about "put the -vm c:\program files\java\jdkxxxxx\bin" in the ini ar as argument for a shortcut did not at all help!
(Do I sound frustrated? Believe me, that's an understatement! I am simply furious because I lost a week trying to make Maven reliable!)
I had very unpredictable behavior. Sometimes it compiled and sometimes not. If I did a maven clean
, it could not find the compiler and failed. If I then changed something in the build path, it suddenly worked again!!
Until I went to menu Window → Preferences → Java → Installed JRE's. I added a new JRE using the location of the JDK and then removed the JRE. Suddenly Maven ran stable!
Maybe this is worth putting in letters with font-size 30 or so in the Apache manual?
With all due respect, this is simply outrageous for the Java community! I can't imagine how many days were lost by all these people, trying to work out their problems of this kind! I cannot possibly imagine this is released as a final version. I personally would not even dare to release such a thing under the name beta software...
Kind regards either way.... After a week of tampering I can finally start developing. I hope my boss won't find out about this. It took me lots of effort to convince him not to go to .NET and I already feel sorry about it.
I encountered the same problem when I tried to install curl in my 32 bit win 7 machine. As answered by Buravchik it is indeed dependency of SSL and installing openssl fixed it. Just a point to take care is that while installing openssl you will get a prompt to ask where do you wish to put the dependent DLLS. Make sure to put it in windows system directory as other programs like curl and wget will also be needing it.
{}
represents an empty dictionary, not an array/list. For lists or arrays, you need []
.
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend
the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {}
or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update
method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
Yes this topic is a bit old but i wanted to share the solution that worked for me for those who might need it anyway
As Ali said, try to locate your program using the following from terminal :
sudo python3
import serial
print(serial.__file__)
--> Copy
CTRL+D #(to get out of python)
sudo python3
-->paste/__init__.py
Activating __init__.py
will say to your program "ok i'm going to use Serial from python3". My problem was that my python3 program was using Serial from python 2.7
Other solution: remove other python versions
Cao
Tryhard
This image gives the answer. Please read it.
I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.
An observablecollection can be a List
{
BuchungsSatz item = BuchungsListe.ToList.Find(x => x.BuchungsAuftragId == DGBuchungenAuftrag.CurrentItem.Id);
}
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
You need to use table-layout:fixed
in order for CSS ellipsis to work on the table cells.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
I dont understand the frustrations. Why not just make a broadcastreceiver that filters for this intent:
android.provider.Telephony.MMS_RECEIVED
I checked a little further and you might need system level access to get this (rooted phone).
I am no expert at this (and this page was very helpful along with http://mywiki.wooledge.org/UsingFind)
Just noticed -path
is for a path that fully matches the string/path that comes just after find
(.
in theses examples) where as -name
matches all basenames.
find . -path ./.git -prune -o -name file -print
blocks the .git directory in your current directory ( as your finding in .
)
find . -name .git -prune -o -name file -print
blocks all .git subdirectories recursively.
Note the ./
is extremely important!! -path
must match a path anchored to .
or whatever comes just after find if you get matches with out it (from the other side of the or '-o
') there probably not being pruned!
I was naively unaware of this and it put me of using -path when it is great when you don't want to prune all subdirectory with the same basename :D
There is a get method in HashMap:
for (String keys : objectSet.keySet())
{
System.out.println(keys + ":"+ objectSet.get(keys));
}
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:
Play 2.0-RC4
It is important to include quotes around the play command you want to run. In my case without the quotes play would still run on port 9000.
play "run 8080"
Alternatively you could run the following from the play console (type 'play' to get to the console)
run 8080
Unfortunately the Windows Mobile Device Center stopped working out of the box after the Creators Update for Windows 10. The application won't open and therefore it's impossible to get the sync working. In order to get it running now we need to modify the ActiveSync registry settings. Create a BAT file with the following contents and run it as administrator:
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RapiMgr /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\WcesComm /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
Restart the computer and everything should work.
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
> 1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<- 220 dur.bounceme.net ESMTP Postfix (Ubuntu)
-> EHLO dur.bounceme.net
<- 250-dur.bounceme.net
<- 250-PIPELINING
<- 250-SIZE 10240000
<- 250-VRFY
<- 250-ETRN
<- 250-STARTTLS
<- 250-ENHANCEDSTATUSCODES
<- 250-8BITMIME
<- 250 DSN
-> MAIL FROM:<[email protected]>
<- 250 2.1.0 Ok
-> RCPT TO:<[email protected]>
<- 250 2.1.5 Ok
-> DATA
<- 354 End data with <CR><LF>.<CR><LF>
-> Date: Mon, 30 Dec 2013 14:33:17 -0800
-> To: [email protected]
-> From: [email protected]
-> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
-> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
->
-> This is a test mailing
->
-> .
<- 250 2.0.0 Ok: queued as 52D162C3EFF
-> QUIT
<- 221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
>N 5 [email protected] 15/581 test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>
This is a test mailing
New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$
It's just one easy command.
My following JS solution is better than the other approaches here because it ensures that it will always say 'open' when the target is closed, and vice versa.
HTML:
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">
Open
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
JS:
$('[data-toggle-secondary]').each(function() {
var $toggle = $(this);
var originalText = $toggle.text();
var secondaryText = $toggle.data('toggle-secondary');
var $target = $($toggle.attr('href'));
$target.on('show.bs.collapse hide.bs.collapse', function() {
if ($toggle.text() == originalText) {
$toggle.text(secondaryText);
} else {
$toggle.text(originalText);
}
});
});
$('[data-toggle-secondary]').each(function() {_x000D_
var $toggle = $(this);_x000D_
var originalText = $toggle.text();_x000D_
var secondaryText = $toggle.data('toggle-secondary');_x000D_
var $target = $($toggle.attr('href'));_x000D_
_x000D_
$target.on('show.bs.collapse hide.bs.collapse', function() {_x000D_
if ($toggle.text() == originalText) {_x000D_
$toggle.text(secondaryText);_x000D_
} else {_x000D_
$toggle.text(originalText);_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">_x000D_
Open_x000D_
</a>_x000D_
<div class="collapse" id="collapseExample">_x000D_
<div class="well">_x000D_
..._x000D_
</div>_x000D_
</div>
_x000D_
data-toggle-secondary
attributeI had the similar problem in a live site. In my local site it was working fine. For fixing the same I Just have added the below code
json_decode(stripslashes($_GET['arr']));
It's 2020 - nobody should be using Net::HTTP
any more and all answers seem to be saying so, use a more high level gem such as Faraday - Github
That said, what I like to do is a wrapper around the HTTP api call,something that's called like
rv = Transporter::FaradayHttp[url, options]
because this allows me to fake HTTP calls without additional dependencies, ie:
if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
response_body = FakerForTests[url: url, options: options]
else
conn = Faraday::Connection.new url, connection_options
Where the faker looks something like this
I know there are HTTP mocking/stubbing frameworks, but at least when I researched last time they didn't allow me to validate requests efficiently and they were just for HTTP, not for example for raw TCP exchanges, this system allows me to have a unified framework for all API communication.
Assuming you just want to quick&dirty convert a hash to json, send the json to a remote host to test an API and parse response to ruby this is probably fastest way without involving additional gems:
JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`
Hopefully this goes without saying, but don't use this in production.
If you have jest
running as a script command, something like npm test
, you need to use the following command to make it work:
npm test -- -t "fix order test"
Here is my sample how I use it. For the css/less task. Can be applied for all.
var cssTask = function (options) {
var minifyCSS = require('gulp-minify-css'),
less = require('gulp-less'),
src = cssDependencies;
src.push(codePath + '**/*.less');
var run = function () {
var start = Date.now();
console.log('Start building CSS/LESS bundle');
gulp.src(src)
.pipe(gulpif(options.devBuild, plumber({
errorHandler: onError
})))
.pipe(concat('main.css'))
.pipe(less())
.pipe(gulpif(options.minify, minifyCSS()))
.pipe(gulp.dest(buildPath + 'css'))
.pipe(gulpif(options.devBuild, browserSync.reload({stream:true})))
.pipe(notify(function () {
console.log('END CSS/LESS built in ' + (Date.now() - start) + 'ms');
}));
};
run();
if (options.watch) {
gulp.watch(src, run);
}
};
gulp.task('dev', function () {
var options = {
devBuild: true,
minify: false,
watch: false
};
cssTask (options);
});
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
In The above link you will find the answer
**C or c**
Displays numeric values in currency format. You can specify the number of decimal places.
Example:
Format: {0:C}
123.456 -> $123.46
**D or d**
Displays integer values in decimal format. You can specify the number of digits. (Although the type is referred to as "decimal", the numbers are formatted as integers.)
Example:
Format: {0:D}
1234 -> 1234
Format: {0:D6}
1234 -> 001234
**E or e**
Displays numeric values in scientific (exponential) format. You can specify the number of decimal places.
Example:
Format: {0:E}
1052.0329112756 -> 1.052033E+003
Format: {0:E2}
-1052.0329112756 -> -1.05e+003
**F or f**
Displays numeric values in fixed format. You can specify the number of decimal places.
Example:
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567
**G or g**
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Example:
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120
F or f
Displays numeric values in fixed format. You can specify the number of decimal places.
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567
G or g
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120
N or n
Displays numeric values in number format (including group separators and optional negative sign). You can specify the number of decimal places.
Format: {0:N}
1234.567 -> 1,234.57
Format: {0:N4}
1234.567 -> 1,234.5670
P or p
Displays numeric values in percent format. You can specify the number of decimal places.
Format: {0:P}
1 -> 100.00%
Format: {0:P1}
.5 -> 50.0%
R or r
Displays Single, Double, or BigInteger values in round-trip format.
Format: {0:R}
123456789.12345678 -> 123456789.12345678
X or x
Displays integer values in hexadecimal format. You can specify the number of digits.
Format: {0:X}
255 -> FF
Format: {0:x4}
255 -> 00ff
You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.
function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});
It is possible to turn the string into a stream by using the std::stringstream
class (its constructor takes a string as parameter). Once it's built, you can use the >>
operator on it (like on regular file based streams), which will extract, or tokenize word from it:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}
Scikit-learn (which I recommend using anyways) has it included in the metrics
module:
>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 0, 0, 0, 1, 1, 0, 2, 2]
>>> confusion_matrix(y_true, y_pred)
array([[3, 0, 0],
[1, 1, 1],
[1, 1, 1]])
string jsonFilePath = @"C:\MyFolder\myFile.json";
string json = File.ReadAllText(jsonFilePath);
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
foreach (var item in json_Dictionary)
{
// parse here
}
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.
Public Sub example()
Dim sArray(4) As string
Dim element As variant
For Each element In sArray
do_something (element)
Next element
End Sub
Sub do_something(ByVal e As String)
End Sub
The other option is to convert the variant to a string before passing it.
do_something CStr(element)
Use this.
$('#mydiv').load(document.URL + ' #mydiv');
Note, include a space before the hastag.
Here are the steps to pull a specific or any branch,
1.clone the master(you need to provide username and password)
git clone <url>
2. the above command will clone the repository and you will be master branch now
git checkout <branch which is present in the remote repository(origin)>
3. The above command will checkout to the branch you want to pull and will be set to automatically track that branch
4.If for some reason it does not work like that, after checking out to that branch in your local system, just run the below command
git pull origin <branch>
For arbitrary levels of nestedness:
In [2]: def nested_dict():
...: return collections.defaultdict(nested_dict)
...:
In [3]: a = nested_dict()
In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})
In [5]: a['a']['b']['c'] = 1
In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
{'a': defaultdict(<function __main__.nested_dict>,
{'b': defaultdict(<function __main__.nested_dict>,
{'c': 1})})})
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
I do like below to :
var book: MutableList<Books> = mutableListOf()
/** Returns a new [MutableList] with the given elements. */
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
I was using .net core 3.1 with postgres 12.3. Building on the answer from Tadija Bagaric I ended up with:
using (var connection = new NpgsqlConnection(AppConfig.CommentFilesConnection))
{
string insertUserSql = @"INSERT INTO mytable(comment_id,filename,content)
VALUES( @commentId, @filename, @content) returning id;";
int newUserId = connection.QuerySingle<int>(
insertUserSql,
new
{
commentId = 1,
filename = "foobar!",
content = "content"
}
);
}
where AppConfig is my own class which simply gets a string set for my connection details. This is set within the Startup.cs ConfigureServices method.
Something like this?:
INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
I know its already answered, still i am just trying to make it simple. So angular.copy(data) you can use in case where you want to modify/change your received object by keeping its original values unmodified/unchanged.
For example: suppose i have made api call and got my originalObj, now i want to change the values of api originalObj for some case but i want the original values too so what i can do is, i can make a copy of my api originalObj in duplicateObj and modify duplicateObj this way my originalObj values will not change. In simple words duplicateObj modification will not reflect in originalObj unlike how js obj behave.
$scope.originalObj={
fname:'sudarshan',
country:'India'
}
$scope.duplicateObj=angular.copy($scope.originalObj);
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
$scope.duplicateObj.fname='SUD';
$scope.duplicateObj.country='USA';
console.log('---------After update-------')
console.log('----------originalObj--------------');
console.log($scope.originalObj);
console.log('-----------duplicateObj---------------');
console.log($scope.duplicateObj);
Result is like....
----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}
I found this generator based approach more satisfying:
def split_keep(string, sep):
"""Usage:
>>> list(split_keep("a.b.c.d", "."))
['a.', 'b.', 'c.', 'd']
"""
start = 0
while True:
end = string.find(sep, start) + 1
if end == 0:
break
yield string[start:end]
start = end
yield string[start:]
It avoids the need to figure out the correct regex, while in theory should be fairly cheap. It doesn't create new string objects and, delegates most of the iteration work to the efficient find method.
... and in Python 3.8 it can be as short as:
def split_keep(string, sep):
start = 0
while (end := string.find(sep, start) + 1) > 0:
yield string[start:end]
start = end
yield string[start:]
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.
So to create a empty file do:
var f = new File([""], "filename");
The third argument looks like:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.
I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:
while (i.hasNext()) {
// code goes here
}
I did one iteration at the start, and then checked for condition using:
do {
// code goes here
} while (i.hasNext());
I hope this will help some people at some stage.
2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.
Check on custom font name whether checkbox on "Target membership" is added. This should help.
I found complete working example for SFTP in java using JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
Something like this (not tested)
with match_groups as (
select product_id,
matching_product_id,
product_id as group_id
from matches
where product_id not in (select matching_product_id from matches)
union all
select m.product_id, m.matching_product_id, p.group_id
from matches m
join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;
You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.
I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.
If you are trying to debug your virtual host configuration, you may find the Apache -S command line switch useful. That is, type the following command:
httpd -S
This command will dump out a description of how Apache parsed the configuration file. Careful examination of the IP addresses and server names may help uncover configuration mistakes. (See the docs for the httpd program for other command line options).
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.
The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)
SELECT
*
FROM
[SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]
You can also look at using Linked Servers. Linked servers can be other types of data sources too such as DB2 platforms. This is one method for trying to access DB2 from a SQL Server TSQL or Sproc call...
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
if (text[0] == '\0')
{
/* Code... */
}
Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen
than checking the first byte.
The above example is the fastest and less computation is required.
In some scenarios where you update a service and redirect to a new view(page) and then your directive gets loaded before your services are updated then you can use $rootScope.$broadcast if your $watch or $timeout fails
View
<service-history log="log" data-ng-repeat="log in requiedData"></service-history>
Controller
app.controller("MyController",['$scope','$rootScope', function($scope, $rootScope) {
$scope.$on('$viewContentLoaded', function () {
SomeSerive.getHistory().then(function(data) {
$scope.requiedData = data;
$rootScope.$broadcast("history-updation");
});
});
}]);
Directive
app.directive("serviceHistory", function() {
return {
restrict: 'E',
replace: true,
scope: {
log: '='
},
link: function($scope, element, attrs) {
function updateHistory() {
if(log) {
//do something
}
}
$rootScope.$on("history-updation", updateHistory);
}
};
});
there is few things that you can do
SELECT GROUP_CONCAT(CAST(name AS CHAR))
FROM product
WHERE id IN (12345,12346,12347)
If you want to order by the query you can order by cast as well like below
SELECT GROUP_CONCAT(name ORDER BY name))
FROM product
WHERE id IN (12345,12346,12347)
as it says on this blog
SELECT MIN(Date) AS Date FROM tbl_Employee /*To get First date Of Employee*/
Have created a simple dictionary in JS here:
function JSdict() {
this.Keys = [];
this.Values = [];
}
// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
JSdict.prototype.getVal = function (key) {
if (key == null) {
return "Key cannot be null";
}
for (var i = 0; i < this.Keys.length; i++) {
if (this.Keys[i] == key) {
return this.Values[i];
}
}
return "Key not found!";
}
}
// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
JSdict.prototype.update = function (key, val) {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
// Verify dict integrity before each operation
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Values[i] = val;
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
JSdict.prototype.add = function (key, val) {
// Allow only strings or numbers as keys
if (typeof (key) == "number" || typeof (key) == "string") {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
return "Duplicate keys not allowed!";
}
}
this.Keys.push(key);
this.Values.push(val);
}
else {
return "Only number or string can be key!";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
JSdict.prototype.remove = function (key) {
if (key == null) {
return "Key cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Keys.shift(key);
this.Values.shift(this.Values[i]);
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
var dict = new JSdict();
dict.add(1, "one")
dict.add(1, "one more")
"Duplicate keys not allowed!"
dict.getVal(1)
"one"
dict.update(1, "onne")
dict.getVal(1)
"onne"
dict.remove(1)
dict.getVal(1)
"Key not found!"
This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.
Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.
Hope this helps!
EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.
However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.
Viz: dict.hasOwnProperty(key) and delete dict[key]
Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array
THanks!
You could try this:
SELECT * INTO tbl_NewTableName
FROM tbl_OldTableName
WHERE Condition1=@Condition1Value
Then run a simple delete:
DELETE FROM tbl_OldTableName
WHERE Condition1=@Condition1Value
You can use new feature Google play app signing to generate a new key file .
After May 2017 Google play store add a new feature on Play store and It’s Good News For Android Developers. From this feature, Developer can update their app or Apk who lost a KeyStore file. you need to enable google play app signing on play store console.
https://support.google.com/googleplay/android-developer/answer/7384423?hl=en
http://www.geekcodehub.com/2018/05/23/keystore-lost-in-android/
This is a pretty bulletproof solution for testing if a variable exists :
var setOrNot = typeof variable !== typeof undefined ? true : false;
Unfortunately, you cannot simply encapsulate it in a function.
You might think of doing something like this :
function isset(variable) {
return typeof variable !== typeof undefined ? true : false;
}
However, this will produce a reference error if variable variable
has not been defined, because you cannot pass along a non-existing variable to a function :
Uncaught ReferenceError: foo is not defined
On the other hand, it does allow you to test whether function parameters are undefined :
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Even though no value for y
is passed along to function test
, our isset
function works perfectly in this context, because y
is known in function test
as an undefined
value.
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN
never use number type like id as
if (id) {}
for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.
So for id type, we must use following:
if ((Id !== undefined) && (Id !== null) && (Id !== "")){
} else {
}
for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.
if (string_type_variable) { }
In addition to what people wrote years ago:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
Then your version of mingw does not default to c99. Add this compiler flag: -std=c99
.
Instead of casting to float, you can add 0.0 to the sum:
def avg(l):
return sum(l, 0.0) / len(l)
You could also use vbCrLf
which corresponds to Chr(13)
& Chr(10)
.
Does IE11 displays any message relative to the blocked execution of your ActiveX ?
You should read this and this.
Use the following JS function to detect support of ActiveX :
function IsActiveXSupported() {
var isSupported = false;
if(window.ActiveXObject) {
return true;
}
if("ActiveXObject" in window) {
return true;
}
try {
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
isSupported = true;
} catch (e) {
if (e.name === "TypeError" || e.name === "Error") {
isSupported = true;
}
}
return isSupported;
}
The most common way would be to put a simple text file (XML/JSON would be better) on your webserver with the last build version. The application will then download this file, check the version and start the updater. A typical file would look like this:
Application Update File (A unique string that will let your application recognize the file type)
version: 1.0.0 (Latest Assembly Version)
download: http://yourserver.com/... (A link to the download version)
redirect: http://yournewserver.com/... (I used this field in case of a change in the server address.)
This would let the client know that they need to be looking at a new address.
You can also add other important details.
function findByTextContent(needle, haystack, precise) {_x000D_
// needle: String, the string to be found within the elements._x000D_
// haystack: String, a selector to be passed to document.querySelectorAll(),_x000D_
// NodeList, Array - to be iterated over within the function:_x000D_
// precise: Boolean, true - searches for that precise string, surrounded by_x000D_
// word-breaks,_x000D_
// false - searches for the string occurring anywhere_x000D_
var elems;_x000D_
_x000D_
// no haystack we quit here, to avoid having to search_x000D_
// the entire document:_x000D_
if (!haystack) {_x000D_
return false;_x000D_
}_x000D_
// if haystack is a string, we pass it to document.querySelectorAll(),_x000D_
// and turn the results into an Array:_x000D_
else if ('string' == typeof haystack) {_x000D_
elems = [].slice.call(document.querySelectorAll(haystack), 0);_x000D_
}_x000D_
// if haystack has a length property, we convert it to an Array_x000D_
// (if it's already an array, this is pointless, but not harmful):_x000D_
else if (haystack.length) {_x000D_
elems = [].slice.call(haystack, 0);_x000D_
}_x000D_
_x000D_
// work out whether we're looking at innerText (IE), or textContent _x000D_
// (in most other browsers)_x000D_
var textProp = 'textContent' in document ? 'textContent' : 'innerText',_x000D_
// creating a regex depending on whether we want a precise match, or not:_x000D_
reg = precise === true ? new RegExp('\\b' + needle + '\\b') : new RegExp(needle),_x000D_
// iterating over the elems array:_x000D_
found = elems.filter(function(el) {_x000D_
// returning the elements in which the text is, or includes,_x000D_
// the needle to be found:_x000D_
return reg.test(el[textProp]);_x000D_
});_x000D_
return found.length ? found : false;;_x000D_
}_x000D_
_x000D_
_x000D_
findByTextContent('link', document.querySelectorAll('li'), false).forEach(function(elem) {_x000D_
elem.style.fontSize = '2em';_x000D_
});_x000D_
_x000D_
findByTextContent('link3', 'a').forEach(function(elem) {_x000D_
elem.style.color = '#f90';_x000D_
});
_x000D_
<ul>_x000D_
<li><a href="#">link1</a>_x000D_
</li>_x000D_
<li><a href="#">link2</a>_x000D_
</li>_x000D_
<li><a href="#">link3</a>_x000D_
</li>_x000D_
<li><a href="#">link4</a>_x000D_
</li>_x000D_
<li><a href="#">link5</a>_x000D_
</li>_x000D_
</ul>
_x000D_
Of course, a somewhat simpler way still is:
var textProp = 'textContent' in document ? 'textContent' : 'innerText';_x000D_
_x000D_
// directly converting the found 'a' elements into an Array,_x000D_
// then iterating over that array with Array.prototype.forEach():_x000D_
[].slice.call(document.querySelectorAll('a'), 0).forEach(function(aEl) {_x000D_
// if the text of the aEl Node contains the text 'link1':_x000D_
if (aEl[textProp].indexOf('link1') > -1) {_x000D_
// we update its style:_x000D_
aEl.style.fontSize = '2em';_x000D_
aEl.style.color = '#f90';_x000D_
}_x000D_
});
_x000D_
<ul>_x000D_
<li><a href="#">link1</a>_x000D_
</li>_x000D_
<li><a href="#">link2</a>_x000D_
</li>_x000D_
<li><a href="#">link3</a>_x000D_
</li>_x000D_
<li><a href="#">link4</a>_x000D_
</li>_x000D_
<li><a href="#">link5</a>_x000D_
</li>_x000D_
</ul>
_x000D_
References:
To add to Sweko's point:
The reason why the cast
var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y
is not possible is because the List<T>
is invariant in the Type T and thus it doesn't matter whether X
derives from Y
) - this is because List<T>
is defined as:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces
(Note that in this declaration, type T
here has no additional variance modifiers)
However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe
derives from Animal
:
IEnumerable<Animal> animals = giraffes;
This is because IEnumerable<T>
supports covariance in T
- this makes sense given that IEnumerable
implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out
keyword in the declaration of IEnumerable<T>
:
public interface IEnumerable<out T> : IEnumerable
(Here's further explanation for the reason why mutable collections like List
cannot support covariance
, whereas immutable iterators and collections can.)
Casting with .Cast<T>()
As others have mentioned, .Cast<T>()
can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException
if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach
loop).
Filtering and Casting with OfType<T>()
If the input list contains elements of different, incompatable types, the potential InvalidCastException
can be avoided by using .OfType<T>()
instead of .Cast<T>()
. (.OfType<>()
checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)
foreach
Also note that if the OP had written this instead: (note the explicit Y y
in the foreach
)
List<Y> ListOfY = new List<Y>();
foreach(Y y in ListOfX)
{
ListOfY.Add(y);
}
that the casting will also be attempted. However, if no cast is possible, an InvalidCastException
will result.
Examples
For example, given the simple (C#6) class hierarchy:
public abstract class Animal
{
public string Name { get; }
protected Animal(string name) { Name = name; }
}
public class Elephant : Animal
{
public Elephant(string name) : base(name){}
}
public class Zebra : Animal
{
public Zebra(string name) : base(name) { }
}
When working with a collection of mixed types:
var mixedAnimals = new Animal[]
{
new Zebra("Zed"),
new Elephant("Ellie")
};
foreach(Animal animal in mixedAnimals)
{
// Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
castedAnimals.Add((Elephant)animal);
}
var castedAnimals = mixedAnimals.Cast<Elephant>()
// Also fails for Zed with `InvalidCastException
.ToList();
Whereas:
var castedAnimals = mixedAnimals.OfType<Elephant>()
.ToList();
// Ellie
filters out only the Elephants - i.e. Zebras are eliminated.
Re: Implicit cast operators
Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.
If we add a conversion operator to convert a Zebra to an Elephant:
public class Zebra : Animal
{
public Zebra(string name) : base(name) { }
public static implicit operator Elephant(Zebra z)
{
return new Elephant(z.Name);
}
}
Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[]
to Elephant[]
, given that the Zebras can be now converted to a homogeneous collection of Elephants:
var compilerInferredAnimals = new []
{
new Zebra("Zed"),
new Elephant("Ellie")
};
Using Implicit Conversion Operators at run time
*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic
:
var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
new Zebra("Zed"),
new Elephant("Ellie")
};
foreach (dynamic animal in mixedAnimals)
{
castedAnimals.Add(animal);
}
// Returns Zed, Ellie
UIImage
contains a CGImage
as its main content member as well as scaling and orientation factors. Since CGImage
and its various functions are derived from OSX, it expects a coordinate system that is upside down compared to the iPhone. When you create a UIImage
, it defaults to an upside-down orientation to compensate (you can change this!). Use the .CGImage
property to access the very powerful CGImage
functions, but drawing onto the iPhone screen etc. is best done with the UIImage
methods.
It may not be your speficic situation, but I had a similar problem.
In my case, I was using angular-i18n, and getting the locale dictionary asynchronously. The problem was that the json file it was getting was incorrectly indented (mixing spaces and tabs). The GET request didn't failed.
Correcting the indentation solved the problem.
There are many possibilities to do this in R. Here are some of them:
df <- read.table(header = TRUE, text = 'Gene Value
A 12
A 10
B 3
B 5
B 6
C 1
D 3
D 4')
# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)
# tapply
tapply(df$Value, df$Gene, max)
# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))
# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))
# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))
# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]
# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)
# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')
# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]
When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global
declaration.
When you access a variable in a function, its value is looked up using the LEGB scoping rules.
So, the first example
x = 1
def inc():
x += 5
inc()
produces an UnboundLocalError
because Python determined x
inside inc
to be a local variable,
while accessing x
works in your second example
def inc():
print x
because here, in accordance with the LEGB rule, Python looks for x
in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId()
.
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.
Perhaps declare it above your first while
?
To run multiple commands in the docker-compose file by using bash -c
.
command: >
bash -c "python manage.py makemigrations
&& python manage.py migrate
&& python manage.py runserver 0.0.0.0:8000"
Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date
, DateFormat
and SimpleDateFormat
classes. It all goes more natural with the modern Java date and time API.
To get a date-time object from your millis:
ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("Australia/Sydney"));
If millis
equals 1318388699000L
, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]
. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.
If you want the date-time in your string format for presentation:
String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
Result:
12/10/2011 14:04:59
PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59
.
It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.
I attach you my code:
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'
MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if(error) {
return console.log('Error connecting to the server.')
}
console.log('Succesfully connected.')
})
_x000D_
My suggestion would be
$value = $_POST["myfield"];
$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
I was stuck with ast.literal_eval()
. I was trying it in IntelliJ IDEA debugger, and it kept returning None
on debugger output.
But later when I assigned its output to a variable and printed it in code. It worked fine. Sharing code example:
import ast
sample_string = '[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]'
output_value = ast.literal_eval(sample_string)
print(output_value)
Its python version 3.6.
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
If you don't want to put @SuppressWarning("unchecked") on each sf.getEntries() call, you can always make a wrapper that will return List.
You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/
HTML:
<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?
CSS:
div {
display: none;
border:1px solid #000;
height:30px;
width:290px;
margin-left:10px;
}
a:hover + div {
display: block;
}?
I've put some of the above answers into a short bash script that you can put into a file called get.sh
and link to /usr/local/bin/get
(or whatever other name you prefer).
#!/bin/bash
if [ "${1}" == "" ]; then
echo "error: blank line number";
exit 1
fi
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "error: line number arg not a number";
exit 1
fi
if [ "${2}" == "" ]; then
echo "error: blank file name";
exit 1
fi
sed "${1}q;d" $2;
exit 0
Ensure it's executable with
$ chmod +x get
Link it to make it available on the PATH
with
$ ln -s get.sh /usr/local/bin/get
Enjoy responsibly!
P
The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.
.dropdown-submenu{_x000D_
position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
transform: rotate(-90deg);_x000D_
position: absolute;_x000D_
right: 3px;_x000D_
top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
position: absolute !important;_x000D_
margin-top: -30px;_x000D_
left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
.dropdown-menu{_x000D_
width: 50%;_x000D_
}_x000D_
.dropdown-menu .dropdown-submenu{_x000D_
width: auto;_x000D_
}_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Link 1</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
<ul class="dropdown-menu">_x000D_
<a class="dropdown-item" href="#">A</a>_x000D_
<a class="dropdown-item" href="#">b</a>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
In my case, I was going nuts since there wasn't any issues with the string to be decoded, since I could successfully decode it on online tools.
Until I found out that you first have to decodeURIComponent
what you are decoding, like so:
atob(decodeURIComponent(dataToBeDecoded));
The solution no one tells is that in Mysql v5.5 and later InnoDB is the default storage engine which does not have this problem but in many cases like mine there are some old mysql ini configuration files which are using old MYISAM storage engine like below.
default-storage-engine=MYISAM
which is creating all these problems and the solution is to change default-storage-engine to InnoDB in the Mysql's ini configuration file once and for all instead of doing temporary hacks.
default-storage-engine=InnoDB
And if you are on MySql v5.5 or later then InnoDB is the default engine so you do not need to set it explicitly like above, just remove the default-storage-engine=MYISAM
if it exist from your ini
file and you are good to go.
I solved it with window.length
.
But with this solution you can take current error (X-Frame or 404).
iframe.onload = event => {
const isLoaded = event.target.contentWindow.window.length // 0 or 1
}
for you to achieve that, you not only need to know how recursion works but you also need to understand the String method. here is a sample code that I used to achieve it: -
class PalindromeRecursive {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String input=sc.next();
System.out.println("is "+ input + "a palindrome : " + isPalindrome(input));
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
isPalindrome(s.substring(low++,high--));
}
return true;
}
}
In Node.js, you can use Path's parse module...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
HttpHandler Example,
HTTP Handler in ASP.NET 2.0
A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension or by calling the handler directly.The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse to increase performance or whether a new handler is required for each request.
The .ashx file extension is reserved for custom handlers. If you create a custom handler with a file name extension of .ashx, it will automatically be registered within IIS and ASP.NET. If you choose to use an alternate file extension, you will have to register the extension within IIS and ASP.NET. The advantage of using an extension other than .ashx is that you can assign multiple file extensions to one handler.
Configuring HTTP Handlers
The configuration section handler is responsible for mapping incoming URLs to the IHttpHandler or IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit these settings. Administrators use the tag directive to configure the section. directives are interpreted and processed in a top-down sequential order. Use the following syntax for the section handler:
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures: void ProcessRequest(HttpContext); bool IsReusable {get;}
In my case the issue was that the emulator was making a request to:
http://10.0.2.2:8081/debugger-ui
instead of:
http://localhost:8081/debugger-ui
and the request was failing.
To solve the issue: Before enabling remote debugging on your emulator, open http://localhost:8081/debugger-ui
in chrome. Then enable remote debugging and go back to the chrome page where you should see your console logs.
Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:
<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>
Yes I think this would be quicker.
Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1
Here is a function that will do that.
CREATE FUNCTION count_str(haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
BEGIN
RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
END;
If the above does not work then try the following. It solved the problem for me even when the owner was well defined for the database.
SQL Server 2008 replication failing with: process could not execute 'sp_replcmds'
I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from
text2 = text1.Replace(@"\\", @"/");
to
text2 = text1.Replace(@"\", @"/");
and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.
That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type
manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.
I ended up solving it by going to the Body
tab, change the param type from File
to Text
, then back to File
and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
I was getting the same two error messages until I fixed two things in my code:
(1) By default, when you implement methods in the RecyclerView.Adapter
it generates:
@Override
public int getItemCount() {
return 0;
}
Make sure you update your code so it says:
@Override
public int getItemCount() {
return artists.size();
}
Obviously if you have zero items in your items then you will get zero things displayed on the screen.
(2) I was not doing this as shown in the top answer: CardView layout_width="match_parent" does not match parent RecyclerView width
//correct
LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_listitem, parent, false);
//incorrect (what I had)
LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_listitem,null);
(3) EDIT: BONUS:
Also make sure you set up your RecyclerView
like this:
<android.support.v7.widget.RecyclerView
android:id="@+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
NOT like this:
<view
android:id="@+id/RecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I have seen some tutorials using the latter method. While it works I think it generates this error too.
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');_x000D_
let str = 'a1b2c.d3e';_x000D_
console.log(parseNum(str));
_x000D_
With collections.Counter
you could do
>>> import collections
>>> stats = {'a':1000, 'b':3000, 'c': 100}
>>> stats = collections.Counter(stats)
>>> stats.most_common(1)
[('b', 3000)]
If appropriate, you could simply start with an empty collections.Counter
and add to it
>>> stats = collections.Counter()
>>> stats['a'] += 1
:
etc.
Try this:
$(document).ready(function(event) {
$('#countrylist').change(function(e){
// put code here
}).change();
});
Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.
Might be late to answer the original poster, but someone else might benefit from the shorthand notation, and this follows jQuery's chaining, etc
First take a label. set its visibility to false, then on the DataGridView_CellClick event write this
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
// then perform your select statement according to that label.
}
//try it it might work for you
EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:
You can use
Get-Variable foo -Scope Global
and trap the error that is raised when the variable doesn't exist.
IMHO most compatible with older browsers
Array.prototype.inArray = function( needle ){
return Array(this).join(",").indexOf(needle) >-1;
}
var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );
By turning an Array copy in to a CSV string, you can test the string in older browsers.
TEXT
is a string data type that can store up to 65,535 characters.
But still if you want to store more data then change its data type to LONGTEXT
ALTER TABLE name_tabel
CHANGE text_field
LONGTEXT CHARACTER SET utf8
COLLATE utf8_general_ci
NOT NULL;
You don't need to use bi-directional association instead of your code, you have just to add CascaType.Remove as a property to ManyToOne annotation, then use @OnDelete(action = OnDeleteAction.CASCADE), it's works fine for me.
By using a combination of JQuery's .trigger()
and native Javascripts's .reset()
all form elements can be reset to blank state.
$(".reset").click(function(){
$("#<form_id>").trigger("reset");
});
Replace <form_id>
with id of form to reset.
If you change the ManagementObjectSearcher to the following:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%""");
So the "GetUSBDevices() looks like this"
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
Your results will be limited to USB devices (as opposed to all types on your system)
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.
You can use this format
<!-- NAVBAR START -->
<nav class="navbar py-3 py-4 text-uppercase nav-over-video navbar-expand-lg navbar-white bg-white">
<div class="container-fluid d-flex">
<div class="justify-content-start">
<a class="navbar-brand" href="#">
<img src="img/logo.png" height="50px" alt="" class="img">
</a>
</div>
<div class="justify-content-end">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
class="bi bi-menu-button-wide" viewBox="0 0 16 16">
<path
d="M0 1.5A1.5 1.5 0 0 1 1.5 0h13A1.5 1.5 0 0 1 16 1.5v2A1.5 1.5 0 0 1 14.5 5h-13A1.5 1.5 0 0 1 0 3.5v-2zM1.5 1a.5.5 0 0 0-.5.5v2a.5.5 0 0 0 .5.5h13a.5.5 0 0 0 .5-.5v-2a.5.5 0 0 0-.5-.5h-13z" />
<path
d="M2 2.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm10.823.323l-.396-.396A.25.25 0 0 1 12.604 2h.792a.25.25 0 0 1 .177.427l-.396.396a.25.25 0 0 1-.354 0zM0 8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V8zm1 3v2a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2H1zm14-1V8a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v2h14zM2 8.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0 4a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5z" />
</svg>
</span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
<!-- As a link -->
<!-- NAVBAR ENDS -->
you need a return statement in your first function.
function first(){
var nameContent = document.getElementById('full_name').value;
return nameContent;
}
and then in your second function can be:
function second(){
alert(first());
}
A great One Image slider : https://github.com/daimajia/AndroidImageSlider Check it
The best way for paging in sql server 2012 is by using offset and fetch next in a stored procedure. OFFSET Keyword - If we use offset with the order by clause then the query will skip the number of records we specified in OFFSET n Rows.
FETCH NEXT Keywords - When we use Fetch Next with an order by clause only it will returns the no of rows you want to display in paging, without Offset then SQL will generate an error. here is the example given below.
create procedure sp_paging
(
@pageno as int,
@records as int
)
as
begin
declare @offsetcount as int
set @offsetcount=(@pageno-1)*@records
select id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only
end
you can execute it as follow.
exec sp_paging 2,3
You would need to know how to identify an error in your results. If you do not have a standard expected error, I suggest that you run a transformation on each error in the catch block that makes it identifiable in your results.
try {
let resArray = await Promise.all(
state.routes.map(route => route.handler.promiseHandler().catch(e => e))
);
// in catch(e => e) you can transform your error to a type or object
// that makes it easier for you to identify whats an error in resArray
// e.g. if you expect your err objects to have e.type, you can filter
// all errors in the array eg
// let errResponse = resArray.filter(d => d && d.type === '<expected type>')
// let notNullResponse = resArray.filter(d => d)
} catch (err) {
// code related errors
}
Check PHP's strtotime
-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php
If strtotime
can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr
to parse/correct your format and retrieve your timestamp through another function, e.g. mktime
.
Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }
) to see whether the set date/time is in the past or the future.
I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.
Take a look at permatswap()
in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.
mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
This gives:
R> out$perm[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 1
[2,] 0 1 0 1 0
[3,] 0 0 0 1 1
[4,] 1 0 0 0 1
R> out$perm[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 1 1
[2,] 0 0 0 1 1
[3,] 1 0 0 1 0
[4,] 0 0 1 0 1
To explain the call:
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
times
is the number of randomised matrices you want, here 99burnin
is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matricesthin
says only take a random draw every thin
swapsmtype = "prab"
says treat the matrix as presence/absence, i.e. binary 0/1 data.A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin
is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.
Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.
distcp
is used for copying data to and from the hadoop filesystems in parallel. It is similar to the generic hadoop fs -cp
command. In the background process, distcp
is implemented as a MapReduce job where mappers are only implemented for copying in parallel across the cluster.
Usage:
copy one file to another
% hadoop distcp file1 file2
copy directories from one location to another
% hadoop distcp dir1 dir2
If dir2
doesn't exist then it will create that folder and copy the contents. If dir2
already exists, then dir1
will be copied under it. -overwrite
option forces the files to be overwritten within the same folder. -update
option updates only the files that are changed.
transferring data between two HDFS clusters
% hadoop distcp -update -delete hdfs://nn1/dir1 hdfs://nn2/dir2
-delete
option deletes the files or directories from the destination that are not present in the source.
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.
If you are running the script through browser, then set the set_time_limit
to zero for infinite seconds.
set_time_limit(0);
Increase the curl's operation time limit using this option CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds
It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
In layman terms:- JDK = JRE + Development/debugging tools, where JDK is our complete package to work with Java, from creating compiling till running it.On the other hand JRE is just of running of code(Byte Code).
Note:- Whether we are installing JDK or JRE, JVM would come bundled with both the packages and JVM is the part where JIT compiler converts the byte code into the machine specific code.
Just read the article on JDK,JRE ,JVM and JIT
public enum Suit implements java.io.Serializable, Comparable<Suit>{
spades, hearts, diamonds, clubs;
private static final Suit [] lookup = Suit.values();
public Suit fromOrdinal(int ordinal) {
if(ordinal< 1 || ordinal> 3) return null;
return lookup[value-1];
}
}
the test class
public class MainTest {
public static void main(String[] args) {
Suit d3 = Suit.diamonds;
Suit d3Test = Suit.fromOrdinal(2);
if(d3.equals(d3Test)){
System.out.println("Susses");
}else System.out.println("Fails");
}
}
I appreciate that you share with us if you have a more efficient code, My enum is huge and constantly called thousands of times.
In Excel VBA, this function will give you the content of any cell in any worksheet.
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.
I use Letter Press lib for my NonTextView stuff like Buttons and kianoni fontloader lib for my TextViews cause of usage of style in this lib is more easy than Letter Press for me and i got ideal feedback with that. this is great for those who want to use custom font except Roboto Font. so it was my experience with font libs. for those who want to use custom class for change font i highly recommended to create this class with this snippet
public class TypefaceSpan extends MetricAffectingSpan {
/** An <code>LruCache</code> for previously loaded typefaces. */
private static LruCache<String, Typeface> sTypefaceCache =
new LruCache<String, Typeface>(12);
private Typeface mTypeface;
/**
* Load the {@link android.graphics.Typeface} and apply to a {@link android.text.Spannable}.
*/
public TypefaceSpan(Context context, String typefaceName) {
mTypeface = sTypefaceCache.get(typefaceName);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getApplicationContext()
.getAssets(), String.format("fonts/%s", typefaceName));
// Cache the loaded Typeface
sTypefaceCache.put(typefaceName, mTypeface);
}
}
@Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
// Note: This flag is required for proper typeface rendering
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
// Note: This flag is required for proper typeface rendering
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}
And use class like this :
AppData = PreferenceManager.getDefaultSharedPreferences(this);
TextView bannertv= (TextView) findViewById(R.id.txtBanner);
SpannableString s = new SpannableString(getResources().getString(R.string.enterkey));
s.setSpan(new TypefaceSpan(this, AppData.getString("font-Bold",null)), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
bannertv.setText(s);
maybe this help.
Try to use pseudo classes like :first-child & :last-child to remove extra padding from first & last child.
Inspect the generated code of slick slider & try to remove padding on that.
Hope, it'll help!!!
Do not forget to exclude carriage returns from your data !!!
as in:
SELECT
Myotherval
, CASE WHEN TRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '%[^0-9]%' and RTRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '.' and isnumeric(REPLACE([MyVal], char(13) + char(10), '')) = 1 THEN 'my number: ' + [MyVal]
ELSE ISNULL(Cast([MyVal] AS VARCHAR(8000)), '')
END AS 'MyVal'
FROM MyTable
diff --color
option was added to GNU diffutils 3.4 (2016-08-08)
This is the default diff
implementation on most distros, which will soon be getting it.
Ubuntu 18.04 has diffutils
3.6 and therefore has it.
On 3.5 it looks like this:
Tested with:
diff --color -u \
<(seq 6 | sed 's/$/ a/') \
<(seq 8 | grep -Ev '^(2|3)$' | sed 's/$/ a/')
Apparently added in commit c0fa19fe92da71404f809aafb5f51cfd99b1bee2 (Mar 2015).
Word-level diff
Like diff-highlight
. Not possible it seems, feature request: https://lists.gnu.org/archive/html/diffutils-devel/2017-01/msg00001.html
Related threads:
ydiff
does it though, see below.
ydiff
side-by-side word level diff
https://github.com/ymattw/ydiff
Is this Nirvana?
python3 -m pip install --user ydiff
diff -u a b | ydiff -s
Outcome:
If the lines are too narrow (default 80 columns), fit to screen with:
diff -u a b | ydiff -w 0 -s
Contents of the test files:
a
1
2
3
4
5 the original line the original line the original line the original line
6
7
8
9
10
11
12
13
14
15 the original line the original line the original line the original line
16
17
18
19
20
b
1
2
3
4
5 the original line teh original line the original line the original line
6
7
8
9
10
11
12
13
14
15 the original line the original line the original line the origlnal line
16
17
18
19
20
ydiff
Git integration
ydiff
integrates with Git without any configuration required.
From inside a git repository, instead of git diff
, you can do just:
ydiff -s
and instead of git log
:
ydiff -ls
See also: How can I get a side-by-side diff when I do "git diff"?
Tested on Ubuntu 16.04, git 2.18.0, ydiff 1.1.
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
php.ini probably needs to read:
extension=ext\php_sqlsrv_53_nts.dll
Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P
Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents<? phpinfo(); ?>
and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)
Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start
Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/
You can do this to bubble events to parent document:
$('iframe').load(function() {
var eventlist = 'click dblclick \
blur focus focusin focusout \
keydown keypress keyup \
mousedown mouseenter mouseleave mousemove mouseover mouseout mouseup mousemove \
touchstart touchend touchcancel touchleave touchmove';
var iframe = $('iframe').contents().find('html');
// Bubble events to parent
iframe.on(eventlist, function(event) {
$('html').trigger(event);
});
});
Just extend the eventlist for more events.
You don't want to use .toString()
.
Notice that SecretKey inherits from java.security.Key, which itself inherits from Serializable. So the key here (no pun intended) is to serialize the key into a ByteArrayOutputStream, get the byte[] array and store it into the db. The reverse process would be to get the byte[] array off the db, create a ByteArrayInputStream offf the byte[] array, and deserialize the SecretKey off it...
... or even simpler, just use the .getEncoded()
method inherited from java.security.Key (which is a parent interface of SecretKey). This method returns the encoded byte[] array off Key/SecretKey, which you can store or retrieve from the database.
This is all assuming your SecretKey implementation supports encoding. Otherwise, getEncoded()
will return null.
You should look at the Key/SecretKey javadocs (available right at the start of a google page):
http://download.oracle.com/javase/6/docs/api/java/security/Key.html
Or this from CodeRanch (also found with the same google search):
http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Usually this is due to another directive in-between your ng-controller and your input that is creating a new scope. When the select writes out it value, it will write it up to the most recent scope, so it would write it to this scope rather than the parent that is further away.
The best practice is to never bind directly to a variable on the scope in an
ng-model
, this is also known as always including a "dot" in your ngmodel. For a better explanation of this, check out this video from John:
Solution from: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU
On Android 7 works it:
ip route get 8.8.8.8
output will be: 8.8.8.8 via gateway...
I've already encountered this problem on people using my in-house tools on new 64 bit machines with Office 2010.
all I had to do was change lines of code like this:
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
To This:
#If VBA7 Then
Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#Else
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#End If
You will, of course want to make sure that the library you're using is available on both machines, but so far nothing I've used has been a problem.
Note that in the old VB6, PtrSafe isn't even a valid command, so it'll appear in red as though you have a compile error, but it won't actually ever give an error because the compiler will skip the first part of the if block.
Applications using the above code compile and run perfectly on Office 2003, 2007, and 2010 32 and 64 bit.
You don't need to import any custom library.
I prefer to use the modern AlertDialog
so this is the Kotlin version for the great answer posted by Kishan Donga in this page.
fun setProgressDialog(context:Context, message:String):AlertDialog {
val llPadding = 30
val ll = LinearLayout(context)
ll.orientation = LinearLayout.HORIZONTAL
ll.setPadding(llPadding, llPadding, llPadding, llPadding)
ll.gravity = Gravity.CENTER
var llParam = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)
llParam.gravity = Gravity.CENTER
ll.layoutParams = llParam
val progressBar = ProgressBar(context)
progressBar.isIndeterminate = true
progressBar.setPadding(0, 0, llPadding, 0)
progressBar.layoutParams = llParam
llParam = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
llParam.gravity = Gravity.CENTER
val tvText = TextView(context)
tvText.text = message
tvText.setTextColor(Color.parseColor("#000000"))
tvText.textSize = 20.toFloat()
tvText.layoutParams = llParam
ll.addView(progressBar)
ll.addView(tvText)
val builder = AlertDialog.Builder(context)
builder.setCancelable(true)
builder.setView(ll)
val dialog = builder.create()
val window = dialog.window
if (window != null) {
val layoutParams = WindowManager.LayoutParams()
layoutParams.copyFrom(dialog.window?.attributes)
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
dialog.window?.attributes = layoutParams
}
return dialog
}
val dialog = setProgressDialog(this, "Loading..")
dialog.show()
int i = 255;
std::string s = std::to_string(i);
In c++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.
It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).
Anyway, if that is an array wrapper, you'll want something like this:
$('#my-hidden-field').val(theObject[0].id);
You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,
$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;
This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Visual Studio does elevate itself automatically if the project's application manifest specifies an administrative requestedExecutionLevel
, so you just need to edit that. Visual Studio will detect that and relaunch itself as administrator when needed.
Or if you want to hide/show the title bar at any point:
private void toggleFullscreen(boolean fullscreen)
{
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullscreen)
{
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
else
{
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
Objective-C
// Create the Button with RoundedRect type
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// instend of "Click Me" you can write your own message/Label
[mybutton setTitle:@"Click Me" forState:UIControlStateNormal];
// create the Rectangle Frame with specified size
mybutton.frame = CGRectMake(10, 10, 300, 140); // x,y,width,height [self.view addSubview:mybutton];// add button to your view.
Swift
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
self.view.addSubview(button)
You can use form-inline class for each form-group :)
<form>
<div class="form-group form-inline">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
</form>
Converting int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
Try this below code it is also works well in angular 2
<span>{{current_date | date: 'yyyy-MM-dd'}}</span>
If you want to pass a parameter to the function from the NSTimer then here is your solution:
var somethingToPass = "It worked"
let timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "tester:", userInfo: somethingToPass, repeats: false)
func tester(timer: NSTimer)
{
let theStringToPrint = timer.userInfo as String
println(theStringToPrint)
}
Include the colon in the selector text (tester:), and your parameter(s) go in userInfo.
Your function should take NSTimer as a parameter. Then just extract userInfo to get the parameter that passed.
Below find the PHP code to get current UTC(Coordinated Universal Time) time
<?php_x000D_
// Prints the day_x000D_
echo gmdate("l") . "<br>";_x000D_
_x000D_
// Prints the day, date, month, year, time, AM or PM_x000D_
echo gmdate("l jS \of F Y h:i:s A");_x000D_
?>
_x000D_
Just the thread.
I had the same problem in Android Studio 1.2.1.1. It was just liske the other answers said, however, I was not able to find where to add the dependencies. Finally I found it under File->Project structure->Dependencies This menu will give you the option at add the dependency to the Google Play Services library.
I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:
search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)
The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.
select * from information_schema.columns
where table_name = 'your_table' and table_schema = 'your_database'
An alternate method that limits the scope of the lambda rather than giving it access to the whole this
is to pass in a local reference to the member variable, e.g.
auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
It helped me. Just add it in your pom.xml.
By default maven compiler plugin uses Java 1.5 or 1.6, you have to redefine it in your pom.xml.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
If you are using mobile,
Turn on your developer options.
Turn on USB debugging option
Just To mention, in CSS 3
:after
should be used like this
::after
From https://developer.mozilla.org/de/docs/Web/CSS/::after :
The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.
So it should be:
li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }
Event though ,oment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function formatDuration(ms) {
var duration = moment.duration(ms);
return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
}
You will get something like x:xx:xx.
In the case you may want to skip the hour, when the duration is only < 60minutes.
function formatDuration(ms) {
var duration = moment.duration(ms);
if (duration.asHours() > 1) {
return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
} else {
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
}
This workaround in moment was introduced in this Issue.
That fixed the problem for me, when trying to upgrade to El Capitan:
sudo softwareupdate --clear-catalog
if you don't mind to combine the net command with grep you can use the following script.
@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end
An extension of some other answers that covers hexadecimal representation:
public int CharToInt(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'a' && c <= 'f')
{
return 10 + c - 'a';
}
else if (c >= 'A' && c <= 'F')
{
return 10 + c - 'A';
}
return -1;
}
My solution is:
$maxs = array_keys($array, max($array))
Note:
this way you can retrieve every key related to a given max value.
If you are interested only in one key among all simply use $maxs[0]
Just set this to v21/styles.xml file
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
and be sure
<item name="android:windowTranslucentStatus">false</item>
import numpy as np
import scipy.stats
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
you can calculate like this way.
domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.
loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.
Try This
ImagePath = "http://localhost/profilepics/abc.png";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
You can reset by update sequence after deleted rows in your-table
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
public static void main(String[] args) {
List<String> ls=new ArrayList<String>();
ls.add("1");
ls.add("2");
ls.add("3");
ls.add("4");
//Then you can use "foreache" loop to iterate.
for(String item:ls){
System.out.println(item);
}
}
cleanBuildCache
no longer works.
Android Gradle plugin now utilizes Gradle cache feature
https://guides.gradle.org/using-build-cache/
TO CLEAR CACHE
Clean the cache directory to avoid any hits from previous builds
rm -rf $GRADLE_HOME/caches/build-cache-*
https://guides.gradle.org/using-build-cache/#caching_android_projects
Other digressions: see here (including edits).
Newest solution using Gradle task:
cleanBuildCache
Available via Android plugin for Gradle, revision 2.3.0 (February 2017)
Dependencies:
More info at:
https://developer.android.com/studio/build/build-cache.html#clear_the_build_cache
Build cache
Stores certain outputs that the Android plugin generates when building your project (such as unpackaged AARs and pre-dexed remote dependencies). Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. Projects using Android plugin 2.3.0 and higher use the build cache by default. To learn more, read Improve Build Speed with Build Cache.
NOTE: The cleanBuildCache task is not available if you disable the build cache.
Windows:
gradlew cleanBuildCache
Linux / Mac:
gradle cleanBuildCache
Android Studio / IntelliJ:
gradle tab (default on right) select and run the task or add it via the configuration window
NOTE: gradle
/ gradlew
are system specific files containing scripts. Please see the related system info how to execute the scripts:
The accepted answer seems not adequate in several situations.
To check whether the localStorage
or sessionStorage
are supported, I use the following snippet from MDN.
function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}
Use this snippet like this, and fallback to, for example, using cookie:
if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
document.cookie = key + "=" + encodeURIComponent(value) + expires + "; path=/";
}
I have made the fallbackstorage package which uses this snippet to check for the storage availability and fallback to a manually implemented MemoryStorage.
import {getSafeStorage} from 'fallbackstorage'
getSafeStorage().setItem('test', '1') // always work
I read this article it was really helpful for troubleshooting any kind of inconveniences
https://support.microsoft.com/en-us/kb/224453
this is a case of waitresource KEY: 16:72057595075231744 (ab74b4daaf17)
-- First SQL Provider to find the SPID (Session ID)
-- Second Identify problem, check Status, Open_tran, Lastwaittype, waittype, and waittime
-- iMPORTANT Waitresource select * from sys.sysprocesses where spid = 57
select * from sys.databases where database_id=16
-- with Waitresource check this to obtain object id
select * from sys.partitions where hobt_id=72057595075231744
select * from sys.objects where object_id=2105058535
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.
In the example you gave, there is no difference, in terms of output, between append
and +=
. But there is a difference between append
and +
(which the question originally asked about).
>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312
>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720
As you can see, append
and +=
have the same result; they add the item to the list, without producing a new list. Using +
adds the two lists and produces a new list.
You could also use clip-path
to clip (hide) all overflowing edges but the one you want to show:
.shadow {
box-shadow: 0 4px 4px black;
clip-path: polygon(0 0, 100% 0, 100% 200%, 0 200%);
}
See clip-path (MDN). The arguments to polygon
are the top-left point, the top-right point, the bottom-right point, and the bottom-left point. By setting the bottom edge to 200%
(or whatever number bigger than 100%
) you constrain your overflow to only the bottom edge.
Examples:
.shadow {
box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
}
.shadow-top {
clip-path: polygon(0% -20%, 100% -20%, 100% 100%, 0% 100%);
}
.shadow-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 100%, 0% 100%);
}
.shadow-bottom {
clip-path: polygon(0% 0%, 100% 0%, 100% 120%, 0% 120%);
}
.shadow-left {
clip-path: polygon(-20% 0%, 100% 0%, 100% 100%, -20% 100%);
}
.shadow-bottom-right {
clip-path: polygon(0% 0%, 120% 0%, 120% 120%, 0% 120%);
}
/* layout for example */
.box {
display: inline-block;
vertical-align: top;
background: #338484;
color: #fff;
width: 4em;
height: 2em;
margin: 1em;
padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow shadow-all">all</div>
<div class="box shadow shadow-top">top</div>
<div class="box shadow shadow-right">right</div>
<div class="box shadow shadow-bottom">bottom</div>
<div class="box shadow shadow-left">left</div>
<div class="box shadow shadow-bottom-right">bottom right</div>
_x000D_