SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.
So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:
HTML
<div class="header">
<p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
<p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
<p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
<p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
<div id="S1" class="curtain">
blabla
</div>
<div id="S2" class="curtain">
blabla
</div>
<div id="S3" class="curtain">
blabla
</div>
<div id="S4" class="curtain">
blabla
</div>
</div>
NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).
JS code:
<script>
function scrollTo(to, duration) {
if (document.body.scrollTop == to) return;
var diff = to - document.body.scrollTop;
var scrollStep = Math.PI / (duration / 10);
var count = 0, currPos;
start = element.scrollTop;
scrollInterval = setInterval(function(){
if (document.body.scrollTop != to) {
count = count + 1;
currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
document.body.scrollTop = currPos;
}
else { clearInterval(scrollInterval); }
},10);
}
function test(elID)
{
var dest = document.getElementById(elID);
scrollTo(dest.offsetTop, 500);
}
</script>
It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.
Thanks everyone for your help.
Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use
process.env[v]
.
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query
Quotes:
"url: http://www.example-site.com/"
To clarify, I meant “quote the value” and originally thought the entire thing was the value. If http://www.example-site.com/
is the value, just quote it like so:
url: "http://www.example-site.com/"
Use an extension method.
Ex:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Usage:
DateTime.Now.Tomorrow();
or
AnyObjectOfTypeDateTime.Tomorrow();
.phtml
was the standard file extension for PHP 2 programs. .php3
took over for PHP 3. When PHP 4 came out they switched to a straight .php
.
The older file extensions are still sometimes used, but aren't so common.
You need to escape the backslash \
:
println yourString.replace("\\", "/")
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
In a simpler way open search window and search for connection.xml
gives a right click on that file and select open file/folder location.
Once you get that connection.xml
try to import it into SQLDeveloper by right clicking to CONNECTIONS.
Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity
has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar
you either need to get activity and set your Toolbar
as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar
's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
Extrapolating from Edwin's answer:
from math import ceil, floor
def float_round(num, places = 0, direction = floor):
return direction(num * (10**places)) / float(10**places)
To use:
>>> float_round(0.21111, 3, ceil) #round up
>>> 0.212
>>> float_round(0.21111, 3) #round down
>>> 0.211
>>> float_round(0.21111, 3, round) #round naturally
>>> 0.211
If these are MyISAM tables, then plopping the .FRM, .MYD, and .MYI files into a database directory (e.g., /var/lib/mysql/dbname
) will make that table available. It doesn't have to be the same database as they came from, the same server, the same MySQL version, or the same architecture. You may also need to change ownership for the folder (e.g., chown -R mysql:mysql /var/lib/mysql/dbname
)
Note that permissions (GRANT
, etc.) are part of the mysql
database. So they won't be restored along with the tables; you may need to run the appropriate GRANT
statements to create users, give access, etc. (Restoring the mysql
database is possible, but you need to be careful with MySQL versions and any needed runs of the mysql_upgrade
utility.)
Actually, you probably just need the .FRM (table structure) and .MYD (table data), but you'll have to repair table to rebuild the .MYI (indexes).
The only constraint is that if you're downgrading, you'd best check the release notes (and probably run repair table). Newer MySQL versions add features, of course.
[Although it should be obvious, if you mix and match tables, the integrity of relationships between those tables is your problem; MySQL won't care, but your application and your users may. Also, this method does not work at all for InnoDB tables. Only MyISAM, but considering the files you have, you have MyISAM]
I find that using a long if/else chain (or switch), in addition to the list of findViewById(btn).setOnClickListener(this)
is ugly. how about creating new View.OnlickListeners with override, in-line:
findViewById(R.id.signInButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { signIn(); }});
findViewById(R.id.signOutButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { signOut(); }});
findViewById(R.id.keyTestButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { decryptThisTest(); }});
findViewById(R.id.getBkTicksButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { getBookTickers(); }});
findViewById(R.id.getBalsButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { getBalances(); }});
I've seen this style being used:
if (when || who || format || data || len);
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
Tried on Playground
class MyClass {
struct Constants {
static let testStr = "test"
static let testStrLen = testStr.characters.count
//testInt will not be accessable by other classes in different swift files
private static let testInt = 1
static func singletonFunction()
{
//accessable
print("Print singletonFunction testInt=\(testInt)")
var newInt = testStrLen
newInt = newInt + 1
print("Print singletonFunction testStr=\(testStr)")
}
}
func ownFunction() {
//not accessable
//var newInt1 = Constants.testInt + 1
var newInt2 = Constants.testStrLen
newInt2 = newInt2 + 1
print("Print ownFunction testStr=\(Constants.testStr)")
print("Print ownFunction newInt2=\(newInt2)")
}
}
let newInt = MyClass.Constants.testStrLen
print("Print testStr=\(MyClass.Constants.testStr)")
print("Print testInt=\(newInt)")
let myClass = MyClass()
myClass.ownFunction()
MyClass.Constants.singletonFunction()
box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);
The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.
The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.
reference: CSS Box Shadow Property
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
Similar to the above solutions I used @Input()
in a directive and able to pass multiple arrays of values in the directive.
selector: '[selectorHere]',
@Input() options: any = {};
Input.html
<input selectorHere [options]="selectorArray" />
Array from TS file
selectorArray= {
align: 'left',
prefix: '$',
thousands: ',',
decimal: '.',
precision: 2
};
When you have some styles on a parent element that interfere with a popover, you’ll want to specify a custom container so that the popover’s HTML appears within that element instead.
For instance say the parent for a popover is body then you can use.
<a href="#" data-toggle="tooltip" data-container="body"> Popover One </a>
Other case might be when popover is placed inside some other element and you want to show popover over that element, then you'll need to specify that element in data-container. ex: Suppose, we have popover inside a bootstrap modal with id as 'modal-two', then you'll need to set 'data-container' to 'modal-two'.
<a href="#" data-toggle="tooltip" data-container="#modal-two"> Popover Two </a>
Yet another option is to use the decimal
module:
import numpy as np
from decimal import *
arr = np.array([ 56.83, 385.3 , 6.65, 126.63, 85.76, 192.72, 112.81, 10.55])
arr2 = [str(Decimal(i).quantize(Decimal('.01'))) for i in arr]
# ['56.83', '385.30', '6.65', '126.63', '85.76', '192.72', '112.81', '10.55']
The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :
import numpy as np
big_array = [] # empty regular list
for i in range(5):
arr = i*np.ones((2,4)) # for instance
big_array.append(arr)
big_np_array = np.array(big_array) # transformed to a numpy array
of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.
1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.
2) No. See the whatsapp security white paper.
3) See #1.
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
I used the following script to read a text file that has a list of all my SVN repos and convert them to GIT, and later use git clone --bare to convert to a bare git repo
#!/bin/bash
file="list.txt"
while IFS= read -r repo_name
do
printf '%s\n' "$repo_name"
sudo git svn clone --shared --preserve-empty-dirs --authors-file=users.txt file:///programs/svn/$repo_name
sudo git clone --bare /programs/git/$repo_name $repo_name.git
sudo chown -R www-data:www-data $repo_name.git
sudo rm -rf $repo_name
done <"$file"
list.txt has the format
repo1_name
repo2_name
and users.txt has the format
(no author) = Prince Rogers <[email protected]>
www-data is the Apache web server user, permission is needed to push changes over HTTP
I recently updated from PHP 5.4.44 to PHP 5.6.12 on my Windows 8.1 OS and got this phpMyAdmin missing mbstring error message.
After trying the above suggestions, none of which worked for me, I discovered version 5.4.44 placed the DLL extensions in the PHP root directory whereas version 5.6.12 placed them in the PHP\ext subdirectory.
All very fine except unfortunately someone forgot to change the php.ini accordingly. So two possible solutions:
I chose the easier first and phpMyAdmin now works fine.
Use following to call function of a frame in parent page
parent.document.getElementById('frameid').contentWindow.somefunction()
for all xml with namespace use local-name()
//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name
No regex, so no need for //.
this should work:
$str = str_replace("\\", '/', $str);
You need to escape "\" as well.
Calculate the Distance between Two Points in javascript
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
For more details refer this: Reference Link
Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length
instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.
if (!str.trim().length) {
console.log('str is empty!');
}
You can read more about trim here.
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are |
and \t
.
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
output:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
output:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
As you can see, we have passed csv.QUOTE_NONNUMERIC
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_NONNUMERIC
specifies the writer
object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_ALL
- Specifies the writer
object to write CSV file with quotes around all the entries.csv.QUOTE_MINIMAL
- Specifies the writer
object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)csv.QUOTE_NONE
- Specifies the writer
object that none of the entries should be quoted. It is the default value.import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
output:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
It wasn't obvious in Vishal's answer what the file name was supposed to be in cases where there is no file on disk. I've modified his answer to work without modification for most needs.
from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
def unzip_string(zipped_string):
unzipped_string = ''
zipfile = ZipFile(StringIO(zipped_string))
for name in zipfile.namelist():
unzipped_string += zipfile.open(name).read()
return unzipped_string
.section {
display: flex;
}
.element-left {
width: 94%;
}
.element-right {
flex-grow: 1;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
or
.section {
display: flex;
flex-wrap: wrap;
}
.element-left {
flex: 2;
}
.element-right {
width: 100px;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
For me this is what worked, I have a Huawei device and I had to install HiSuite from the AppStore, followed its instructions to enable HDB, then in my phone change USB mode to PTP and I started to see some popups about authorizing the device, after that adb devices
detected the device.
import os
def count_files(in_directory):
joiner= (in_directory + os.path.sep).__add__
return sum(
os.path.isfile(filename)
for filename
in map(joiner, os.listdir(in_directory))
)
>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049
For repeating an action in the future, there is the built in setInterval
function that you can use instead of setTimeout
.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
199 on Windows XP NTFS, I just checked.
This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.
Is there some other setting limiting this, I wonder? Try it for yourself.
If you do not mind having to compile/generate the file then you could use a pre processing technique. This gives you the power of the generate but results in a clean Verilog file which is often easier to debug and leads to less simulator issues.
I use RubyIt to generate verilog files from templates using ERB (Embedded Ruby).
parameter ROWBITS = <%= ROWBITS %> ;
always @(posedge sysclk) begin
<% (0...ROWBITS).each do |addr| -%>
temp[<%= addr %>] <= 1'b0;
<% end -%>
end
Generating the module_name.v file with :
$ ruby_it --parameter ROWBITS=4 --outpath ./ --file ./module_name.rv
The generated module_name.v
parameter ROWBITS = 4 ;
always @(posedge sysclk) begin
temp[0] <= 1'b0;
temp[1] <= 1'b0;
temp[2] <= 1'b0;
temp[3] <= 1'b0;
end
Changing the value of the select input or adjusting the selected attribute can overwrite the default selectedOptions property of the DOM element, resulting in an element that may not reset properly in a form that has had the reset event called.
Use jQuery's prop method to clear and set the option needed:
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
I found the answers so far lacking insight as well as warnings. You could and should watch for incompatibilities with IE10+ (if you care).
This is the complete example with the application part and service part after. Note that we set the observe: "response" to catch the header for the filename. Also note that the Content-Disposition header has to be set and exposed by the server, otherwise the current Angular HttpClient will not pass it on. I added a dotnet core piece of code for that below.
public exportAsExcelFile(dataId: InputData) {
return this.http.get(this.apiUrl + `event/export/${event.id}`, {
responseType: "blob",
observe: "response"
}).pipe(
tap(response => {
this.downloadFile(response.body, this.parseFilename(response.headers.get('Content-Disposition')));
})
);
}
private downloadFile(data: Blob, filename: string) {
const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;'});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
private parseFilename(contentDisposition): string {
if (!contentDisposition) return null;
let matches = /filename="(.*?)"/g.exec(contentDisposition);
return matches && matches.length > 1 ? matches[1] : null;
}
private object ConvertFileResponse(ExcelOutputDto excelOutput)
{
if (excelOutput != null)
{
ContentDisposition contentDisposition = new ContentDisposition
{
FileName = excelOutput.FileName.Contains(_excelExportService.XlsxExtension) ? excelOutput.FileName : "TeamsiteExport.xlsx",
Inline = false
};
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
return File(excelOutput.ExcelSheet, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
else
{
throw new UserFriendlyException("The excel output was empty due to no events.");
}
}
I've seen scripts just use variable assignment to do the job:
$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar
Whitespace is automatically coalesced and trimmed. One has to be careful of shell metacharacters (potential injection risk).
I would also recommend always double-quoting variable substitutions in shell conditionals:
if [ -n "$var" ]; then
since something like a -o or other content in the variable could amend your test arguments.
Realise this is an old post, but I came across it looking - in the end I decided apon the below function as it sorted what I was doing at the time better than any of the above:
private static List<DirectoryInfo> SplitDirectory(DirectoryInfo parent)
{
if (parent == null) return null;
var rtn = new List<DirectoryInfo>();
var di = parent;
while (di.Name != di.Root.Name)
{
rtn.Add(new DirectoryInfo(di));
di = di.Parent;
}
rtn.Add(new DirectoryInfo(di.Root));
rtn.Reverse();
return rtn;
}
As posted in another answer, the wildcard library works for both glob and regex filename matching: http://code.google.com/p/wildcard/
I used the following code to match glob patterns including absolute and relative on *nix style file systems:
String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
baseDir = File.separator;
filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();
I spent some time trying to get the FileUtils.listFiles methods in the Apache commons io library (see Vladimir's answer) to do this but had no success (I realise now/think it can only handle pattern matching one directory or file at a time).
Additionally, using regex filters (see Fabian's answer) for processing arbitrary user supplied absolute type glob patterns without searching the entire file system would require some preprocessing of the supplied glob to determine the largest non-regex/glob prefix.
Of course, Java 7 may handle the requested functionality nicely, but unfortunately I'm stuck with Java 6 for now. The library is relatively minuscule at 13.5kb in size.
Note to the reviewers: I attempted to add the above to the existing answer mentioning this library but the edit was rejected. I don't have enough rep to add this as a comment either. Isn't there a better way...
It seems all the answers assume high level languages and mainly C/C++.
But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:
byte = 8 bits
word = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name']
after your javascript was executed.
Regards
Database memory usage is a complex topic. The MySQL Performance Blog does a good job of covering your question, and lists many reasons why it's hugely impractical to "reserve" memory.
If you really want to impose a hard limit, you could do so, but you'd have to do it at the OS level as there is no built-in setting. In linux, you could utilize ulimit, but you'd likely have to modify the way MySQL starts in order to impose this.
The best solution is to tune your server down, so that a combination of the usual MySQL memory settings will result in generally lower memory usage by your MySQL installation. This will of course have a negative impact on the performance of your database, but some of the settings you can tweak in my.ini
are:
key_buffer_size
query_cache_size
query_cache_limit
table_cache
max_connections
tmp_table_size
innodb_buffer_pool_size
I'd start there and see if you can get the results you want. There are many articles out there about adjusting MySQL memory settings.
Edit:
Note that some variable names have changed in the newer 5.1.x releases of MySQL.
For example:
table_cache
Is now:
table_open_cache
Although the question didn't include the MONEY data type some people coming across this thread might be tempted to use the MONEY data type for financial calculations.
Be wary of the MONEY data type, it's of limited precision.
There is a lot of good information about it in the answers to this Stackoverflow question:
Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?
app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
$scope.post = {url: 'http://', title: ''};
$scope.createVariable = function(url) {
$window.location.href = url;
};
$scope.createFixed = function() {
$window.location.href = '/tab/newpost';
};
});
HTML
<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>
Use the shutil module.
copyfile(src, dst)
Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.
Take a look at filesys for all the file and directory handling functions available in standard Python modules.
A remark about this answer's comments: print(traceback.format_exc())
does a better job for me than traceback.print_exc()
. With the latter, the hello
is sometimes strangely "mixed" with the traceback text, like if both want to write to stdout or stderr at the same time, producing weird output (at least when building from inside a text editor and viewing the output in the "Build results" panel).
Traceback (most recent call last):
File "C:\Users\User\Desktop\test.py", line 7, in
hell do_stuff()
File "C:\Users\User\Desktop\test.py", line 4, in do_stuff
1/0
ZeroDivisionError: integer division or modulo by zero
o
[Finished in 0.1s]
So I use:
import traceback, sys
def do_stuff():
1/0
try:
do_stuff()
except Exception:
print(traceback.format_exc())
print('hello')
The accepted answer suggests to add the following:
export PATH="$HOME/.rbenv/bin:$PATH"
This will not work on Mac OSX, which the OP references. In fact, if you install rbenv via brew install rbenv
, which is really the only installation method in Mac OSX, since curl -fsSL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer | bash
will FAIL in OSX, then the rbenv executable will be installed in:
$ which rbenv
/usr/local/bin/rbenv
However, even in OSX, the rbenv root will remain in the $HOME directory:
~ viggy$ rbenv root
/Users/viggy/.rbenv
What does this mean? It means when you install rubies, they will install in the given home directory under .rbenv:
$ rbenv install 2.6.0
$ ls ~/.rbenv/versions
2.6.0
Now the brew installation did some work that you would have to perform manually in Linux. For example, in Linux, you would have to install ruby-build manually as a plugin:
$ mkdir -p "$(rvbenv root)/plugins"
$ git clone https://github.com/rbenv/ruby-build.git "(rbenv root)"/plugins/ruby-build
This is already done with the homebrew installation. There is one important step that must be done in the homebrew installation, as in the Linux installation. You must add the rbenv shims to your path. In order to do that, when your shell starts, you have to evaluate the following command (which will in turn add the rbenv shims to the beginning of your $PATH):
$ vim ~/.bash_profile
eval "$(rbenv init -)"
$ source ~/.bash_profile
Now when you run echo $PATH
, you will see the rbenv shims:
$ echo $PATH
/Users/viggy/.rbenv/shims:
Now check your ruby version and it will reflect the rbenv ruby installed:
ruby -v
ruby 2.6.0p0
I found a solution that adds columns at runtime, and binds to a DataTable
.
Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?
xaml
<DataGrid
Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}">
</DataGrid>
xaml.cs using System.Windows.Data;
if (table != null) // table is a DataTable
{
foreach (DataColumn col in table.Columns)
{
dataGrid.Columns.Add(
new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(string.Format("[{0}]", col.ColumnName))
});
}
dataGrid.DataContext = table;
}
Amit's answer tells you how to get your AWS_ACCESS_KEY_ID
, but the Your Security Credentials page won't reveal your AWS_SECRET_ACCESS_KEY
. As this blog points out:
Secret access keys are, as the name implies, secrets, like your password. Just as AWS doesn’t reveal your password back to you if you forgot it (you’d have to set a new password), the new security credentials page does not allowing retrieval of a secret access key after its initial creation. You should securely store your secret access keys as a security best practice, but you can always generate new access keys at any time.
So if you don't remember your AWS_SECRET_ACCESS_KEY
, the blog goes on to tell how to create a new one:
As for your other questions:
MERCHANT_ID
and MARKETPLACE_ID
.Try this:
String SQL = "select col1, col2, coln from mytable where timecol = yesterday";
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement(SQL, SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, SQLServerResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(2000);
stmt.set....
stmt.execute();
ResultSet rset = stmt.getResultSet();
while (rset.next()) {
// ......
The most complete, concise definition of false I've come across is:
Anything that stringifies to the empty string or the string
0
is false. Everything else is true.
Therefore, the following values are false:
Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.
A note on "true zeroes"
While numbers that stringify to 0
are false, strings that numify to zero aren't necessarily. The only false strings are 0
and the empty string. Any other string, even if it numifies to zero, is true.
The following are strings that are true as a boolean and zero as a number:
"0.0"
"0E0"
"00"
"+0"
"-0"
" 0"
"0\n"
".0"
"0."
"0 but true"
"\t00"
"\n0e1"
"+0.e-9"
Scalar::Util::looks_like_number
returns false. (e.g. "abc"
)JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
Remove display: block;
in the div #tfl
style property
<div id="tfl" style="display: block; width: 187px; height: 260px;
Inline style take priority then css file
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
That's the way I did it with pure JS:
var files = document.getElementById('filePoster');_x000D_
var submit = document.getElementById('submitFiles');_x000D_
var warning = document.getElementById('warning');_x000D_
files.addEventListener("change", function () {_x000D_
if (files.files.length > 10) {_x000D_
submit.disabled = true;_x000D_
warning.classList += "warn"_x000D_
return;_x000D_
}_x000D_
submit.disabled = false;_x000D_
});
_x000D_
#warning {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#warning.warn {_x000D_
color: red;_x000D_
transform: scale(1.5);_x000D_
transition: 1s all;_x000D_
}
_x000D_
<section id="shortcode-5" class="shortcode-5 pb-50">_x000D_
<p id="warning">Please do not upload more than 10 images at once.</p>_x000D_
<form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">_x000D_
<div class="input-group">_x000D_
<input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />_x000D_
<button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>_x000D_
</div>_x000D_
</form>_x000D_
</section>
_x000D_
Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are:
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
Here the implementation details of Full Name is hidden from the user and is not accessible directly to the user, unlike a public attribute.
Install Aptana plugin to your Eclipse installation.
It has built-in FTP support, and it works excellently.
You can:
As a matter of fact the FTP support is so good I'm using Aptana (or Eclipse + Aptana) now for all my FTP needs. Plus I get syntax highlighting/whatever coding support there is. Granted, Eclipse is not the speediest app to launch, but it doesn't bug me so much.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True"
onsorting="GridView1_Sorting" EnableViewState="true">
<Columns><asp:BoundField DataField="bookid" HeaderText="BOOK ID" SortExpression="bookid" />
<asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
<asp:BoundField DataField="writer" HeaderText="WRITER" />
<asp:BoundField DataField="totalbook" HeaderText="TOTAL BOOK" SortExpression="totalbook" />
<asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
//gridview code on page load under ispostback false//after that.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
if (DT != null)
{
DataView dataView = new DataView(DT);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string GridViewSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
}
Using a range loop feels the most natural to me:
for (var child of node.childNodes) {
child.remove();
}
According to my measurements in Chrome and Firefox, it is about 1.3x slower. In normal circumstances, this will perhaps not matter.
I encountered this issue on a linuxmint distro. It appeared to have happened when there was so many folders and subfolders/files I added to the /public folder in my app. I applied this fix and it worked well...
$
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
change directory into the /etc folder:
cd /etc
then run this:
sudo systcl -p
You may have to close your terminal and npm start
again to get it to work.
If this fails i recommend installing react-scripts globally and running your application directly with that.
$
npm i -g --save react-scripts
then instead of npm start
run react-scripts start
to run your application.
In Material theme 3.1.4 you can change theme like this: Tools->Metherial Theme->Material Theme Config. Its very easy.
In addition to Khriz's answer.
If you need to add 5 minutes to the current time in Mysql
format you can do:
$cur_time=date("Y-m-d H:i:s");
$duration='+5 minutes';
echo date('Y-m-d H:i:s', strtotime($duration, strtotime($cur_time)));
For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()
db.person.find().snapshot().forEach( function (hombre) {
hombre.name = hombre.firstName + ' ' + hombre.lastName;
db.person.save(hombre);
});
http://docs.mongodb.org/manual/reference/method/cursor.snapshot/
You have to reset each individual property back to its default value. It's not great, but it's the only way, given the information you've given us.
In your example, you would do:
.c1 {
height: auto;
}
You should search for each property here:
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
For example, height
:
Initial value :
auto
Another example, max-height
:
Initial value :
none
In 2017, there is now another way, the unset
keyword:
.c1 {
height: unset;
}
Some documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/unset
The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.
Browser support is good: http://caniuse.com/css-unset-value
Having this C source:
int a = 10;
int * ptr = &a;
Use this
printf("The address of ptr is %p\n", (void *) &ptr);
to print the address of ptr
.
Please note that the conversion specifier p
is the only conversion specifier to print a pointer's value and it is defined to be used with void*
typed pointers only.
From man printf
:
p
The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
process.env is a reference to your environment, so you have to set the variable there.
To set an environment variable in Windows:
SET NODE_ENV=development
on OS X or Linux:
export NODE_ENV=development
For example this will start XBMC:
adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/android.app.NativeActivity
(More general answers are already posted, but I missed a nice example here.)
The @Tim Pietzcker's answer here
(?<=\[)[^]]+(?=\])
is almost the one I've been looking for. But there is one issue that some legacy browsers can fail on positive lookbehind. So I had to made my day by myself :). I manged to write this:
/([^[]+(?=]))/g
Maybe it will help someone.
console.log("this is a [sample] string with [some] special words. [another one]".match(/([^[]+(?=]))/g));
_x000D_
Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.
public class Test {
public static void main(String [] args) throws Exception {
Generic g = new Generic();
g.initParameter();
}
}
import java.lang.reflect.ParameterizedType;
public abstract class GenericAbstract<T extends Foo> {
protected T parameter;
@SuppressWarnings("unchecked")
void initParameter() throws Exception, ClassNotFoundException,
InstantiationException {
// Get the class name of this instance's type.
ParameterizedType pt
= (ParameterizedType) getClass().getGenericSuperclass();
// You may need this split or not, use logging to check
String parameterClassName
= pt.getActualTypeArguments()[0].toString().split("\\s")[1];
// Instantiate the Parameter and initialize it.
parameter = (T) Class.forName(parameterClassName).newInstance();
}
}
public class Generic extends GenericAbstract<Foo> {
}
public class Foo {
public Foo() {
System.out.println("Foo constructor...");
}
}
Try below code
string Name = "Abhishek";
string firstfour = Name.Substring(0, 4);
Response.Write(firstfour);
copy your war file to /tmp now extract the contents:
cp warfile.war /tmp
cd /tmp
unzip warfile.war
cd WEB-INF
nano web.xml (or vim or any editor you want to use)
cd ..
zip -r -u warfile.war WEB-INF
now you have in /tmp/warfile.war your file updated.
I had the same problem, make sure that if using submodules (for example, you not only have app.component.module.ts, but you have a separate component such as login.module.ts, that you include ReactiveFormsModule import in this login.module.ts import, for it to work. I don't even have to import ReactiveFormsModule in my app.component.module because I'm using submodules for everything.
login.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoginPageRoutingModule } from './login-routing.module';
import { LoginPage } from './login.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
LoginPageRoutingModule
],
declarations: [LoginPage]
})
export class LoginPageModule {}
You could do something like this:
\documentclass{article}
\begin{document}
Normal:
\begin{itemize}
\item foo
\item bar
\item baz
\end{itemize}
Less space:
\begin{itemize}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
Yes, you can put arrays in sessions, example:
$_SESSION['name_here'] = $your_array;
Now you can use the $_SESSION['name_here']
on any page you want but make sure that you put the session_start()
line before using any session functions, so you code should look something like this:
session_start();
$_SESSION['name_here'] = $your_array;
Possible Example:
session_start();
$_SESSION['name_here'] = $_POST;
Now you can get field values on any page like this:
echo $_SESSION['name_here']['field_name'];
As for the second part of your question, the session variables remain there unless you assign different array data:
$_SESSION['name_here'] = $your_array;
Session life time is set into php.ini file.
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Just found this one (don't know it, not tested, check yourself)
As you only need this for curiosity you could look into the source of this applet.
It does OCR of handwritten characters with a neural network
Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).
"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.
A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format
man page).
So for every branch name that would be represented by a multi-word expression, using a '-
' (dash) as a separator is a good idea.
Just copy the array. There are many ways to do that:
function sort(arr) {
return arr.concat().sort();
}
// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects
Use this SQL:
SELECT DATE_FORMAT(date_column_here,'%d/%m/%Y') FROM table_name;
It's Very Simple First You Define a value
state = {
checked_Array: []
}
Now,
fun(index) {
var checked = this.state.checked_Array;
var values = checked.indexOf(index)
checked.splice(values, 1);
this.setState({checked_Array: checked});
console.log(this.state.checked_Array)
}
This answers the title, not the details as most just read the title from a search result on google like me so I felt it was necessary to explain from a web developer perspective.
JavaScript so clearly dominates the web by a huge margin and JavaScript developers prefer using JSON as the data format overwhelmingly along with popular web APIs so it becomes difficult to argue using YAML over JSON when doing web programming in the general sense as you will likely be outvoted in a team environment. In fact, the majority of web programmers aren't even aware YAML exists, let alone consider using it.
If you are doing any web programming, JSON is the default way to go because no translation step is needed when working with JavaScript so then you must come up with a better argument to use YAML over JSON in that case.
You could use --where option on mysqldump to produce an output that you are waiting for:
mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql
At most 100 rows from test.t1 will be dumped from database table.
Cheers, WB
Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]
# 1. 'Actual' and 'Predicted' data
df <- data.frame(
y_actual = c(1:5),
y_predicted = c(0.8, 2.4, 2, 3, 4.8))
# 2. R2 Score components
# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)
# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)
# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total
You can't call a non-static method without first creating an instance of its parent class.
So from the static method, you would have to instantiate a new object...
Vehicle myCar = new Vehicle();
... and then call the non-static method.
myCar.Drive();
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
leave the dependency array blank . hope this will help you understand better.
useEffect(() => {
doSomething()
}, [])
empty dependency array runs Only Once, on Mount
useEffect(() => {
doSomething(value)
}, [value])
pass value
as a dependency. if dependencies has changed since the last time, the effect will run again.
useEffect(() => {
doSomething(value)
})
no dependency. This gets called after every render.
wmic OS get TotalVisibleMemorySize /Value
Note not TotalPhysicalMemory
as suggested elsewhere
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
I was able to generate
static {
WSDL_LOCATION = null;
}
by configuring pom file to have a null for wsdlurl:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/service.wsdl</wsdl>
<extraargs>
<extraarg>-client</extraarg>
<extraarg>-wsdlLocation</extraarg>
<wsdlurl />
</extraargs>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
The InstallUtil.exe
tool is simply a wrapper around some reflection calls against the installer component(s) in your service. As such, it really doesn't do much but exercise the functionality these installer components provide. Marc Gravell's solution simply provides a means to do this from the command line so that you no longer have to rely on having InstallUtil.exe
on the target machine.
Here's my step-by-step that based on Marc Gravell's solution.
How to make a .NET Windows Service start right after the installation?
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.
tl;dr; apply the a
and b
styles to the parent <div>
, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
You could do this in one of three ways:
print('"A word that needs quotation marks"')
"A word that needs quotation marks"
print("\"A word that needs quotation marks\"")
"A word that needs quotation marks"
print(""" "A word that needs quotation marks" """)
"A word that needs quotation marks"
Well, the problem is that Git can't find KDiff3 in the %PATH%.
In a typical Unix installation all executables reside in several well-known locations (/bin/
, /usr/bin/
, /usr/local/bin/
, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe
:) ).
In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3
in a cmd
session and get KDiff3 running.
The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe
. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)
The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.
For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie
module!
First install the cookie module (and save as a dependency):
npm install --save cookie
Then import and use:
import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed)
console.log(parsed.cookie1);
This will redirect command1 stderr to command2 stdin, while leaving command1 stdout as is.
exec 3>&1
command1 2>&1 >&3 3>&- | command2 3>&-
exec 3>&-
Taken from LDP
TL;DR. In Visual Studio 2019
, when you add an Icon
resource to a Win32
(desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows
compatible should have the following formats:
| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256 | 32-bit | PNG |
| 64x64 | 32-bit | BMP |
| 48x48 | 32-bit | BMP |
| 32x32 | 32-bit | BMP |
| 16x16 | 32-bit | BMP |
| 48x48 | 8-bit | BMP |
| 32x32 | 8-bit | BMP |
| 16x16 | 8-bit | BMP |
Spring Boot 1.4 Use this for Javascript HTML Json all compressions.
server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript
Simple way to save multiple files
cshtml
@using (Html.BeginForm("Index","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Files:</label>
<input type="file" multiple name="files" id="files" /><br><br>
<input type="submit" value="Upload Files" />
<br><br>
@ViewBag.Message
}
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
}
return View();
}
A thread is nothing more than a memory context (or how Tanenbaum better puts it, resource grouping) with execution rules. It's a software construct. The CPU has no idea what a thread is (some exceptions here, some processors have hardware threads), it just executes instructions.
The kernel introduces the thread and process concept to manage the memory and instructions order in a meaningful way.
you can still use
String Item = getIntent().getExtras().getString("name");
in the fragment
, you just need call getActivity()
first:
String Item = getActivity().getIntent().getExtras().getString("name");
This saves you having to write some code.
met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
This will work if your route looks like this: localhost:8888/p?tagid=1234
var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234
Otherwise use the following code if your route looks like this: localhost:8888/p/1234
var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}
There's a special variable for this in bash:
kill $!
$! expands to the PID of the last process executed in the background.
Full solution in Firefox 5:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
This is an example with ChartJs - 2.9.4
var maximumPoints = 5;// with this variable you can decide how many points are display on the chart
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
var d = data[0];
dataset.data.push(d);
data.shift();
});
var canRemoveData = false;
chart.data.datasets.forEach((dataset) => {
if (dataset.data.length > maximumPoints) {
if (!canRemoveData) {
canRemoveData = true;
chart.data.labels.shift();
}
dataset.data.shift();
}
});
chart.update();
}
window.onload = function () {
var canvas = document.getElementById('elm-chart'),
ctx = canvas.getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [
{
data: [],
label: 'Dataset-1',
backgroundColor: "#36a2eb88",
borderColor: "#36a2eb",
},
{
data: [],
label: 'Dataset-2',
backgroundColor: "#ff638488",
borderColor: "#ff6384",
}
],
},
options: {
responsive: false,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var index = 0;
setInterval(function () {
var data = [];
myLineChart.data.datasets.forEach((dataset) => {
data.push(Math.random() * 100);
});
addData(myLineChart, index, data);
index++;
}, 1000);
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="elm-chart" width="640" height="480"></canvas>
_x000D_
Why not use let; I find it much easier. Here's an example you may find useful:
start=`date +%s`
# ... do something that takes a while ...
sleep 71
end=`date +%s`
let deltatime=end-start
let hours=deltatime/3600
let minutes=(deltatime/60)%60
let seconds=deltatime%60
printf "Time spent: %d:%02d:%02d\n" $hours $minutes $seconds
Another simple example - calculate number of days since 1970:
let days=$(date +%s)/86400
In our case it was Windows-integrated authentication specified in the app's web.config
BUT the windows-auth module was not installed on the IIS machine at all.
Just adding another possible reason.
Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:
SELECT DATABASE() FROM DUAL;
There is much discussion over whether or not FROM DUAL
should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use the following instead:
SELECT DATABASE();
That said, it is perhaps important to note, that while FROM DUAL
does not actually do anything, it is valid MySQL syntax. From a strict perspective, including braces in a single line conditional in JavaScript also does not do anything, but it is still a valid practice.
The properties that can be set for a figure
is referenced here.
You could then use:
figure_number = 1;
x = 0; % Screen position
y = 0; % Screen position
width = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)
figure(figure_number, 'Position', [x y width height]);
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
with CSS
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).
use the following
It will return a true or false
theObject instanceof Object
This exception can be solved by specifying a full class path.
Example:
If you are using a class named ExceptionDetails
Wrong Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(ExceptionDetails.class);
Right Way of passing arguments
JAXBContext jaxbContext = JAXBContext.newInstance(com.tibco.schemas.exception.ExceptionDetails.class);
If nothing works, then try uninstalling and then reinstalling Eclipse. This is how i just fixed this problem after trying everything suggested on this forum.
Add !importent in your css
* {
font-size: 16px !importent;
line-height: 2;
}
If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):
if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi
Have a nice day
Yes and no. Only one application can actively listen on a port. But that application can bequeath its connection to another process. So you could have multiple processes working on the same port.
Try to use a filename relative to the current files path. Example for './my_file':
fn = os.path.join(os.path.dirname(__file__), 'my_file')
In Python 3.4+ you can also use pathlib:
fn = pathlib.Path(__file__).parent / 'my_file'
I see this is old but... I dont know if you are looking for code to generate the numbers/options every time its loaded or not. But I use an excel or open office calc page and place use the auto numbering all the time. It may look like this...
| <option>
| 1 | </option>
|
Then I highlight the cells in the row and drag them down until there are 100 or the number that I need. I now have code snippets that I just refer back to.
Sorry, I didn't notice the PHP tag - however someone else might be interested in a VB solution:
Module Module1
Sub Main()
Dim d As Date = Now
Dim nextFriday As Date = DateAdd(DateInterval.Weekday, DayOfWeek.Friday - d.DayOfWeek(), Now)
Console.WriteLine("next friday is " & nextFriday)
Console.ReadLine()
End Sub
End Module
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
this would do it excluding exactly 'Music'
cp -a ^'Music' /target
this and that for excluding things like Music?* or *?Music
cp -a ^\*?'complete' /target
cp -a ^'complete'?\* /target
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'fr', layout: google.translate.TranslateElement.FloatPosition.TOP_RIGHT}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
You can do this in the following way:
<a href="path to PDF file">Open PDF</a>
If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess
file setting by this way:
<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
Order Allow,Deny
Allow from all
</FilesMatch>
But now allow just certain necessary files.
I have used this code and it worked perfectly.
I use the approach with PATH variable. Path to Notepad++ is added to system's PATH variable and then core.editor is set like following:
git config --global core.editor notepad++
Also, you may add some additional parameters for Notepad++:
git config --global core.editor "notepad++.exe -multiInst"
(as I detailed in "Git core.editor
for Windows")
And here you can find some options you may use when stating Notepad++ Command Line Options.
You can install npx
to use Angular CLI installed in your directory:
npm install -g npx
npx ng serve
Filippo Valsorda wrote a cross-platform tool, mkcert
, to do this for lots of trust stores. I presume he wrote it for the same reason that there are so many answers to this question: it is a pain to do the "right" thing for SubjectAltName
certificates signed by a trusted root CA.
mkcert
is included in the major package management systems for Windows, macOS, and several Linux flavors. It is also mentioned in the Chromium docs in Step 4 of Testing Powerful Features.
mkcert
mkcert
is a simple tool for making locally-trusted development certificates. It requires no configuration.$ mkcert -install Created a new local CA at "/Users/filippo/Library/Application Support/mkcert" The local CA is now installed in the system trust store! ?? The local CA is now installed in the Firefox trust store (requires browser restart)! $ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1 Using the local CA at "/Users/filippo/Library/Application Support/mkcert" ? Created a new certificate valid for the following names - "example.com" - "*.example.com" - "example.test" - "localhost" - "127.0.0.1" - "::1" The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ?
The usual way to do this is something like the following.
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include
Example: ./src/public/,src/components/
You could do this with MapReduce:
mr = db.runCommand({
"mapreduce" : "my_collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "my_collection" + "_keys"
})
Then run distinct on the resulting collection so as to find all the keys:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
In order to simply visualize the image in a notebook you can use display()
%matplotlib inline
from PIL import Image
im = Image.open(im_path)
display(im)
I had the same issue as you, I figured it out. Facebook now roles some features as plugins. In the left hand side select Products and add product. Then select Facbook Login. Pretty straight forward from there, you'll see all the Oauth options show up.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
or hide any br that follows the p tag, which are obviously not wanted
p + br {
display: none;
}
Hi this might be late but worth trying. This is from a playground file. You can make it a String extension.
This is written in Swift 5.3
Method 1:
var str = "\n \tHello, playground "
if let regexp = try? NSRegularExpression(pattern: "^\\s+", options: NSRegularExpression.Options.caseInsensitive) {
let mstr = NSMutableString(string: str)
regexp.replaceMatches(in: mstr, options: [], range: NSRange(location: 0, length: str.count), withTemplate: "")
str = mstr as String
}
Result: "Hello, playground "
Method 2:
if let c = (str.first { !($0 == " " || $0 == "\t" || $0 == "\n") }) {
if let nonWhiteSpaceIndex = str.firstIndex(of: c) {
str.replaceSubrange(str.startIndex ..< nonWhiteSpaceIndex, with: "")
}
}
Result: "Hello, playground "
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
find /root/directory/to/search -name 'filename.*'
# Directory is optional (defaults to cwd)
Standard UNIX globbing is supported. See man find
for more information.
If you're using Vim, you can use:
:e **/filename.cpp
Or :tabn
or any Vim command which accepts a filename.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
String sDate = "22-01-2019 9:0:0 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sDate = displayFormat.format(date);
LOGGER.info("The required format : " + sDate);
} catch (Exception e) {}
}
}
You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.
Use this:
HttpContext.Current.User.Identity.Name
After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.
Instead of having to ask each FragmentClass like
if(FragmentClass1){
...
if(FragmentClass2){
...
}
Create your own interface, and maker your child fragments implement it, something like
public interface MyChildFragment {
void updateView(int position);
}
Then, you can do something like this to initiate and update your inner fragments.
Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
if (childFragment != null) {
((MyChildFragment) childFragment).updateView();
}
P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState
of your child fragment will be null therefor
public void onCreate(@Nullable Bundle savedInstanceState){
super(savedInstanceState)
}
Will crash your app.
Good luck
No CSS required, visible class should like this: visible-md-block
not just visible-md
and the code should be like this:
<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">
</div>
</div>
</div>
<div class="mobile hidden-md hidden-lg ">
test
</div>
Extra css is not required at all.
In my case the problem was that there was a ghost eclipse hanging on background; it was not using any workspace and had no windows, so it was only on process list that I found it. Killing it resolved the issue.
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
I don't think you can. You may need to use an Iframe instead.
I've just had this same issue with Ionic.
It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.
After going back into the app, my states worked fine.
I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.
From Implementing toString:
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
if
and grep -Eq
arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
echo 'second'
fi
where:
-q
prevents grep
from producing output, it just produces the exit status-E
enables extended regular expressionsI like this because:
case
One downside is that this is likely slower than case
since it calls an external grep
program, but I tend to consider performance last when using Bash.
case
is POSIX 7
Bash appears to follow POSIX by default without shopt
as mentioned by https://stackoverflow.com/a/4555979/895245
Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":
The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]
The format for the case construct is as follows:
case word in [(] pattern1 ) compound-list ;; [[(] pattern[ | pattern] ... ) compound-list ;;] ... [[(] pattern[ | pattern] ... ) compound-list] esac
and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?
, *
and []
.
As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail: https://git-scm.com/book/en/v2/Git-Branching-Rebasing
points
or lines
comes handy if
y2
is generated later, orx
but still should go into the same coordinate system.As your y
s share the same x
, you can also use matplot
:
matplot (x, cbind (y1, y2), pch = 19)
(without the pch
matplopt
will plot the column numbers of the y
matrix instead of dots).
Or you can use the fetch API
fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())
I don't know what the performance difference is, and this will show up on your network tab in DevTools as well.
In bootstrap 4 is easiest.
You can use the classes:
bg-transparent
and border-0
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');
sectionName, groupName and fieldName are present in etc/system.xml file of your module.
The above code will automatically fetch config value of currently viewed store.
If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig
function as below:
$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);
An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:
So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:
window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);
For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:
<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage);
</script>
If the upload failed, set the
errorMessage
to some non-zero-length string and empty the url, and vice versa on success.
The problem with using the git hash as the build number is that it's not monotonically increasing. OSGi suggests using a time-stamp for the build number. It looks like the number of commits to the branch could be used in place of the subversion or perforce change number.
When I run your code, I get the following output for example.
<usb.Device object at 0xef38c0>
Device: 001
idVendor: 7531 (0x1d6b)
idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2
Noteworthy are that a) I have usb.Device
objects whereas you have usb.legacy.Device
objects, and b) I have device filenames.
Each usb.Bus
has a dirname
field and each usb.Device
has the filename. As you can see, the filename is something like 001
, and so is the dirname. You can combine these to get the bus file. For dirname=001
and filname=001
, it should be something like /dev/bus/usb/001/001.
You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy
sub-module.
Finally, you should use the idVendor
and idProduct
fields to uniquely identify the device when it's plugged in.
You can disable optimizations if you pass -O0 with the gcc command-line.
E.g. to turn a .C file into a .S file call:
gcc -O0 -S test.c
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
return ds;
}
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
Just add http://download.eclipse.org/egit/updates to your Eclipse update manager.
index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
Check out ruby documents for more information.
I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/
In order to get the image view with the proper size and in the center, you should use the following approach:
let width = 120 // choose the image width
let height = 20 // choose the image height
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) //44 is the standard size of the top bar
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width - width)/2, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit //choose other if it makes sense
imageView.image = UIImage(named: "your_image_name")
titleView.addSubview(imageView)
navigationItem.titleView = titleView
All hail HTML5 _/\_
var videoElement = document.getElementById('videoId');
videoElement.webkitRequestFullScreen();
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
Here is an answer for those who compile from the command line/Command Prompt. It doesn't require changing your Path
environment variable; it simply lets you use the 32-bit JVM
for the program with the 32-bit DLL
.
For the compilation, it shouldn't matter which javac
gets used - 32-bit or 64-bit.
>javac MyProgramWith32BitNativeLib.java
For the actual execution of the program, it is important to specify the path to the 32-bit version of java.exe
I'll post a code example for Windows
, since that seems to be the OS used by the OP.
Windows
Most likely, the code will be something like:
>"C:\Program Files (x86)\Java\jre#.#.#_###\bin\java.exe" MyProgramWith32BitNativeLib
The difference will be in the numbers after jre
. To find which numbers you should use, enter:
>dir "C:\Program Files (x86)\Java\"
On my machine, the process is as follows
C:\Users\me\MyProject>dir "C:\Program Files (x86)\Java"
Volume in drive C is Windows
Volume Serial Number is 0000-9999
Directory of C:\Program Files (x86)\Java
11/03/2016 09:07 PM <DIR> .
11/03/2016 09:07 PM <DIR> ..
11/03/2016 09:07 PM <DIR> jre1.8.0_111
0 File(s) 0 bytes
3 Dir(s) 107,641,901,056 bytes free
C:\Users\me\MyProject>
So I know that my numbers are 1.8.0_111
, and my command is
C:\Users\me\MyProject>"C:\Program Files (x86)\Java\jre1.8.0_111\bin\java.exe" MyProgramWith32BitNativeLib
I was having a similar issue with a property being null or undefined.
This ended up being that IE's document mode was being defaulted to IE7 Standards. This was due to the compatibility mode being automatically set to be used for all intranet sites (Tools > Compatibility View Setting > Display Intranet Sites in Compatibility View).
Quite often this means that the listener hasn't started. Check the Services panel.
On Windows (as you are) another common cause is that the ORACLE_SID is not defined in the registry. Either edit the registry or set the ORACLE_SID in a CMD box. (Because you want to run sqlplusw.exe I suggest you edit the registry.)
git-status porcelain (machine-readable) v2 output looks like this:
$ git status -b --porcelain=v2
# branch.oid d0de00da833720abb1cefe7356493d773140b460
# branch.head the-branch-name
# branch.upstream gitlab/the-branch-name
# branch.ab +2 -2
And to get the branch upstream only:
$ git status -b --porcelain=v2 | grep -m 1 "^# branch.upstream " | cut -d " " -f 3-
gitlab/the-branch-name
If the branch has no upstream, the above command will produce an empty output (or fail with set -o pipefail
).
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
On Version 1.9.6.1. For UnPushed commit.
This article sums it up pretty well
Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.
URIs should be readable, even when used to send data.
I found that with curl 7.18.2 the download progress bar is not hidden with:
curl -s http://google.com > temp.html
but it is with:
curl -ss http://google.com > temp.html
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
I ran into a situation where I had to track clicks on a social media button pulled in through an iframe. A new window would be opened when the button was clicked. Here was my solution:
var iframeClick = function () {
var isOverIframe = false,
windowLostBlur = function () {
if (isOverIframe === true) {
// DO STUFF
isOverIframe = false;
}
};
jQuery(window).focus();
jQuery('#iframe').mouseenter(function(){
isOverIframe = true;
console.log(isOverIframe);
});
jQuery('#iframe').mouseleave(function(){
isOverIframe = false;
console.log(isOverIframe);
});
jQuery(window).blur(function () {
windowLostBlur();
});
};
iframeClick();
With your example:
avgDists = np.array([1, 8, 6, 9, 4])
Obtain indexes of n maximal values:
ids = np.argpartition(avgDists, -n)[-n:]
Sort them in descending order:
ids = ids[np.argsort(avgDists[ids])[::-1]]
Obtain results (for n=4):
>>> avgDists[ids]
array([9, 8, 6, 4])
Another option is to enclose the unwanted lines in an IF block that can never be true
if 1==0 (
...
)
Of course nothing within the if block will be executed, but it will be parsed. So you can't have any invalid syntax within. Also, the comment cannot contain )
unless it is escaped or quoted. For those reasons the accepted GOTO solution is more reliable. (The GOTO solution may also be faster)
Update 2017-09-19
Here is a cosmetic enhancement to pdub's GOTO solution. I define a simple environment variable "macro" that makes the GOTO comment syntax a bit better self documenting. Although it is generally recommended that :labels are unique within a batch script, it really is OK to embed multiple comments like this within the same batch script.
@echo off
setlocal
set "beginComment=goto :endComment"
%beginComment%
Multi-line comment 1
goes here
:endComment
echo This code executes
%beginComment%
Multi-line comment 2
goes here
:endComment
echo Done
Or you could use one of these variants of npocmaka's solution. The use of REM instead of BREAK makes the intent a bit clearer.
rem.||(
remarks
go here
)
rem^ ||(
The space after the caret
is critical
)
use a simple formula: WHO.WHAT = VALUE
where,
WHO is the element in the storyboard you want to make changes to for eg. label
WHAT is the property of that element you wish to change for eg. text
VALUE is the change that you wish to be displayed
for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1
In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road
so our final code will be as follows: Final code
screenshot 1 changes to screenshot 2 once the above code is executed.
I hope this solution helps you solve your issue. Thank you!
Now you can use insertOne method and in promise's result.insertedId