The main difference between name()
and toString()
is that name()
is a final
method, so it cannot be overridden. The toString()
method returns the same value that name()
does by default, but toString()
can be overridden by subclasses of Enum.
Therefore, if you need the name of the field itself, use name()
. If you need a string representation of the value of the field, use toString()
.
For instance:
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
public String toString() {
return name().charAt(0) + name().substring(1).toLowerCase();
}
}
In this example,
WeekDay.MONDAY.name()
returns "MONDAY", and
WeekDay.MONDAY.toString()
returns "Monday".
WeekDay.valueOf(WeekDay.MONDAY.name())
returns WeekDay.MONDAY
, but WeekDay.valueOf(WeekDay.MONDAY.toString())
throws an IllegalArgumentException
.
While most people blindly follow the advice of the javadoc, there are very specific situations where you want to actually avoid toString(). For example, I'm using enums in my Java code, but they need to be serialized to a database, and back again. If I used toString() then I would technically be subject to getting the overridden behavior as others have pointed out.
Additionally one can also de-serialize from the database, for example, this should always work in Java:
MyEnum taco = MyEnum.valueOf(MyEnum.TACO.name());
Whereas this is not guaranteed:
MyEnum taco = MyEnum.valueOf(MyEnum.TACO.toString());
By the way, I find it very odd for the Javadoc to explicitly say "most programmers should". I find very little use-case in the toString of an enum, if people are using that for a "friendly name" that's clearly a poor use-case as they should be using something more compatible with i18n, which would, in most cases, use the name() method.
Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.
I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.
This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!
function Test-Port {
[CmdletBinding()]
Param (
[string] $ComputerName,
[int] $Port,
[int] $Delay = 1,
[int] $Count = 3
)
function Test-TcpClient ($IPAddress, $Port) {
$TcpClient = New-Object Net.Sockets.TcpClient
Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}
If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
Return $False
}
function Invoke-Test ($ComputerName, $Port) {
Try { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString }
Catch { Return $False }
[array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
If ($Results -contains $True) { Return $True } Else { Return $False }
}
for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
{
if ($i -ge $Count) {
Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
Return $false
}
Write-Warning "Port $Port not open, retrying..."
Sleep $Delay
}
Return $true
}
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
hi i'm using ruby on rails for csv generation. In our application we plan to go for the multi language(I18n) and we faced an issue while viewing I18n content in the CSV file of windows excel.
Was fine with Linux (Ubuntu) and mac.
We identified that windows excel need to be imported the data again to view the actual data. While import we will get more options to choose character set.
But this can’t be educated for each and every user, so solution we looking for is to open just by double click.
Then we identified the way of showing data by open mode and bom in windows excel with the help of aghuddleston gist. Added at reference.
Example I18n content
In Mac and Linux
Swedish : Förnamn English : First name
In Windows
Swedish : Förnamn English : First name
def user_information_report(report_file_path, user_id)
user = User.find(user_id)
I18n.locale = user.current_lang
open_mode = "w+:UTF-16LE:UTF-8"
bom = "\xEF\xBB\xBF"
body user, open_mode, bom
end
def headers
headers = [
"ID", "SDN ID",
I18n.t('sys_first_name'), I18n.t('sys_last_name'), I18n.t('sys_dob'),
I18n.t('sys_gender'), I18n.t('sys_email'), I18n.t('sys_address'),
I18n.t('sys_city'), I18n.t('sys_state'), I18n.t('sys_zip'),
I18n.t('sys_phone_number')
]
end
def body tenant, open_mode, bom
File.open(report_file_path, open_mode) do |f|
csv_file = CSV.generate(col_sep: "\t") do |csv|
csv << headers
tenant.patients.find_each(batch_size: 10) do |patient|
csv << [
patient.id, patient.patientid,
patient.first_name, patient.last_name, "#{patient.dob}",
"#{translate_gender(patient.gender)}", patient.email, "#{patient.address_1.to_s} #{patient.address_2.to_s}",
"#{patient.city}", "#{patient.state}", "#{patient.zip}",
"#{patient.phone_number}"
]
end
end
f.write bom
f.write(csv_file)
end
end
Important things to note here is open mode and bom
open_mode = "w+:UTF-16LE:UTF-8"
bom = "\xEF\xBB\xBF"
Before writing the CSV insert BOM
f.write bom
f.write(csv_file)
Windows and Mac
File can be opened directly by double clicking.
Linux (ubuntu)
While opening a file ask for the separator options -> choose “TAB”
An alternative would be to set a variable, and check whether it is defined:
SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")
Unfortunately, using %1
directly with DEFINED
doesn't work.
KDiff3 is not XML specific, but it is free. It does a nice job of comparing and merging text files.
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'
or, from a windows cmd.exe shell, the second line becomes :
git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
The changes (relative to Charles Bailey):
Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools
EDIT (Feb 2014)
As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).
You can display list of supported tools by running:
git mergetool --tool-help
You should see p4merge in either available or valid list. If not, please update your git.
If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:
git config --global merge.tool p4merge
If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:
git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe
~
should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe
), this did not work for me$LOCALAPPDATA/Perforce/p4merge.exe
), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)Find your location in the Google Earth program, and click the icon "View in Google Maps". The URL bar in your browser will show the URL you need.
Recommend use: pathinfo
with PATHINFO_FILENAME
$filename = 'abc_123_filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files
Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:
That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the *
with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:
paths:
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:
# coding: utf-8
from __future__ import print_function
import ruamel.yaml as yaml
class Paths:
def __init__(self):
self.d = {}
def __repr__(self):
return repr(self.d).replace('ordereddict', 'Paths')
@staticmethod
def __yaml_in__(loader, data):
result = Paths()
loader.construct_mapping(data, result.d)
return result
@staticmethod
def __yaml_out__(dumper, self):
return dumper.represent_mapping('!Paths', self.d)
def __getitem__(self, key):
res = self.d[key]
return self.expand(res)
def expand(self, res):
try:
before, rest = res.split(u'?', 1)
kw, rest = rest.split(u'? +', 1)
rest = rest.lstrip() # strip any spaces after "+"
# the lookup will throw the correct keyerror if kw is not found
# recursive call expand() on the tail if there are multiple
# parts to replace
return before + self.d[kw] + self.expand(rest)
except ValueError:
return res
yaml_str = """\
paths: !Paths
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
"""
loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)
paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']
for k in ['root', 'pathc']:
print(u'{} -> {}'.format(k, paths[k]))
which will print:
root -> /path/to/root/
pathc -> /path/to/root/c
The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.
By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:
dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))
this will change the mapping key ordering. If that is a problem you have
to make self.d
a CommentedMap
(imported from ruamel.yaml.comments.py
)
This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.
Pointing to Best Practices for Using Strings in the .NET Framework:
StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for comparisons as your safe default for culture-agnostic string matching.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for better performance.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
values instead of string operations based on CultureInfo.InvariantCulture
when the comparison is linguistically irrelevant (symbolic, for example).And finally:
StringComparison.InvariantCulture
in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.I was having this problem. When connecting with Sequel Pro, I need to use 33060
as the port, but in the .env file it has to be 3306
. I had 33060
in the .env file. Changed it to 3306
and it worked.
body{
height:100%
}
#app div{
height:100%
}
this works for me..
I hope this could be helpful for whom has similar problem .
In ObjectExplorer
window, select your database=> Tables,=> your table=> Constraints. If the customer is defined on create column time, you can see the default name of constraint including the column name.
then use:
ALTER TABLE yourTableName DROP CONSTRAINT DF__YourTa__NewCo__47127295;
(the constraint name is just an example)
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
Strongly typed var don't seem to be available, I have to do the following in order to get access to them:
String MyVar = Dts.Variables["MyVarName"].Value.ToString();
In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like
class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
...
}
then just issue the command
Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName
and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:
Update-Database -ConfigurationTypeName MyNewContextConfiguration
Done.
You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.
You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.
To add a file/folder to the project, a good way is:
First of all add your files to /path/to/your/project/my/added/files, and then run following commands:
svn cleanup /path/to/your/project
svn add --force /path/to/your/project/*
svn cleanup /path/to/your/project
svn commit /path/to/your/project -m 'Adding a file'
I used cleanup to prevent any segmentation fault (core dumped), and now the SVN project is updated.
I'm surprised there hasn't been a functional solution suggested that allows you to set the length in one line. The following is based on UnderscoreJS:
var test = _.map(_.range(4), function () { return undefined; });
console.log(test.length);
For reasons mentioned above, I'd avoid doing this unless I wanted to initialize the array to a specific value. It's interesting to note there are other libraries that implement range including Lo-dash and Lazy, which may have different performance characteristics.
You cannot execute php functions from JavaScript.
PHP runs on the server before the browser sees it. PHP outputs HTML and JavaScript.
When the browser reads the html and javascript it executes it.
I know it's old.. I'll just leave this code here for the sake of convenience.
Integer only:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
Accepts Double
:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or x = ".", x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
Accepts basic operations + - * /
, parentheses ( ) [ ] { }
and Double
:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or ".+-*/()[]{}".Contains(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Instead of $location.path(...)
to change or refresh the page, I used the service $window
. In Angular this service is used as interface to the window
object, and the window
object contains a property location
which enables you to handle operations related to the location or URL stuff.
For example, with window.location
you can assign a new page, like this:
$window.location.assign('/');
Or refresh it, like this:
$window.location.reload();
It worked for me. It's a little bit different from you expect but works for the given goal.
SQL Compare by RedGate http://www.red-gate.com/products/SQL_Compare/index.htm
DBDeploy to help with database change management in an automated fashion http://dbdeploy.com/
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right.
I'm not busting your balls, I mean that with all the best intention.
try:
parent.childNodes[1].style.color = "rgb(155, 102, 102)";
Or
parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);
MSDN FileInfo.Length says that it is "the size of the current file in bytes."
My typical Google search for something like this is: msdn FileInfo
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
I think you want this?
Column Name to Column Number
Sub Sample()
ColName = "C"
Debug.Print Range(ColName & 1).Column
End Sub
Edit: Also including the reverse of what you want
Column Number to Column Name
Sub Sample()
ColNo = 3
Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub
FOLLOW UP
Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.
In such a case I would recommend using .FIND
See this example below
Option Explicit
Sub Sample()
Dim strSearch As String
Dim aCell As Range
strSearch = "Salary"
Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address & _
" and the Cell Column Number is " & aCell.Column
End If
End Sub
SNAPSHOT
Is it possible to select an element if it contains a specific child element?
Unfortunately not yet.
The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.
This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.
An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.
The subject was going to be the element in the selector chain that would have styles applied to it.
Example HTML<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>
This selector would style the span
element
p span {
color: red;
}
This selector would style the p
element
!p span {
color: red;
}
A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()
"
:has()
would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has()
pseudo-selector*.
In any event, continuing the example from above, to select the p
element that contains a span
one could use:
p:has(span) {
color: red;
}
* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.
You could get the offset set only for xs devises by negating the higher pixels with 0 offset. Like so,
class="col-xs-offset-1 col-md-offset-0"
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.
Generating the current time in Perl is rather easy:
perl -e 'print time, "\n"'
Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime()
function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) =
POSIX::strptime("string", "Format");
The function mktime
in the POSIX module has the signature:
mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)
So, if you know the format of your data, you could write a variant on:
perl -MPOSIX -MPOSIX::strptime -e \
'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'
You should use the exit
keyword.
Use the .data()
method:
$('div').data('info', '222');
Note that this doesn't create an actual data-info
attribute. If you need to create the attribute, use .attr()
:
$('div').attr('data-info', '222');
Use the layout_weight
attribute. The layout will roughly look like this:
<LinearLayout android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
</LinearLayout>
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if pArray
is the array, type pArray,10
in the watch window.
By changing
compile 'com.google.android.gms:play-services:8.1.0'
to only needed files, the problem can be solved This Issue is generated because of exceeding files in th build.gradle file.
A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:
Inside your model.rb
validate :date_field_must_be_a_date_or_blank
# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
date_field_before_type_cast.to_date
rescue ArgumentError
errors.add(:birthday, :invalid)
end
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
Use backslash-escaped sed
.
On linux:
Replace all tabs with 1 hyphen inplace, in all *.txt files:
sed -i $'s/\t/-/g' *.txt
Replace all tabs with 1 space inplace, in all *.txt files:
sed -i $'s/\t/ /g' *.txt
Replace all tabs with 4 spaces inplace, in all *.txt files:
sed -i $'s/\t/ /g' *.txt
On a mac:
Replace all tabs with 4 spaces inplace, in all *.txt files:
sed -i '' $'s/\t/ /g' *.txt
package distanceAlgorithm;
public class CalDistance {
public static void main(String[] args) {
// TODO Auto-generated method stub
CalDistance obj=new CalDistance();
/*obj.distance(38.898556, -77.037852, 38.897147, -77.043934);*/
System.out.println(obj.distance(38.898556, -77.037852, 38.897147, -77.043934, "M") + " Miles\n");
System.out.println(obj.distance(38.898556, -77.037852, 38.897147, -77.043934, "K") + " Kilometers\n");
System.out.println(obj.distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
}
public double distance(double lat1, double lon1, double lat2, double lon2, String sr) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (sr.equals("K")) {
dist = dist * 1.609344;
} else if (sr.equals("N")) {
dist = dist * 0.8684;
}
return (dist);
}
public double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
public double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
To show just yours:
SELECT
db, type, specific_name, param_list, returns
FROM
mysql.proc
WHERE
definer LIKE
CONCAT('%', CONCAT((SUBSTRING_INDEX((SELECT user()), '@', 1)), '%'));
use this code
while ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;
?>
With current latest python 3.6.5
pip3 install PyQt5
works fine
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
I've written an extension class to help me deserializing from JSON sources (string, stream, file).
public static class JsonHelpers
{
public static T CreateFromJsonStream<T>(this Stream stream)
{
JsonSerializer serializer = new JsonSerializer();
T data;
using (StreamReader streamReader = new StreamReader(stream))
{
data = (T)serializer.Deserialize(streamReader, typeof(T));
}
return data;
}
public static T CreateFromJsonString<T>(this String json)
{
T data;
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(json)))
{
data = CreateFromJsonStream<T>(stream);
}
return data;
}
public static T CreateFromJsonFile<T>(this String fileName)
{
T data;
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
data = CreateFromJsonStream<T>(fileStream);
}
return data;
}
}
Deserializing is now as easy as writing:
MyType obj1 = aStream.CreateFromJsonStream<MyType>();
MyType obj2 = "{\"key\":\"value\"}".CreateFromJsonString<MyType>();
MyType obj3 = "data.json".CreateFromJsonFile<MyType>();
Hope it will help someone else.
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Just code, with implementation of GetHashCode
and NULL
validation:
public class Class_reglementComparer : IEqualityComparer<Class_reglement>
{
public bool Equals(Class_reglement x, Class_reglement y)
{
if (x is null || y is null))
return false;
return x.Numf == y.Numf;
}
public int GetHashCode(Class_reglement product)
{
//Check whether the object is null
if (product is null) return 0;
//Get hash code for the Numf field if it is not null.
int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();
return hashNumf;
}
}
Example: list of Class_reglement distinct by Numf
List<Class_reglement> items = items.Distinct(new Class_reglementComparer());
Your variable(s1)
spans multiple lines. In order to do this (i.e you want your string to span multiple lines), you have to use triple quotes(""").
s1="""some very long
string............"""
It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.
https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Seems like having "Build Automatically" under the Project menu ought to take care of all of this. It does for Java.
Both are used to send some data and receive some response using that data.
GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto
So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?
POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.
AJAX: $.get()
and $.post()
contain features that are subsets of $.ajax()
. It has more configuration.
$.get ()
method, which is a kind of shorthand for $.ajax()
. When using $.get ()
, instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.
There are no decompilers which I know about. W32dasm is good Win32 disassembler.
here list attribute name set in request request.setAttribute("List",list);
and ArrayList list=new ArrayList();
<%
ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");
out.print(a);
for(int i=0;i<a.size();i++)
{
out.println(a.get(i));
}
%>
typeof(BaseClass).IsAssignableFrom(unknownType);
Just to add to this list of possible locations...
This didn't work for me:
\Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
However this did:
\Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives!
New-Item -path $profile -type file -force
if you use pg_dump with -Fp to backup in plain text format, use following command:
cat db.txt | psql dbname
to copy all data to your database with name dbname
You can use this code
<script>
// Replace the <textarea id="editor"> with a CKEditor
// instance, using default configuration.
CKEDITOR.config.filebrowserImageBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserImageUploadUrl = '/admin/laravel-filemanager/upload?type=Images&_token=';
CKEDITOR.config.filebrowserBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserUploadUrl = '/admin/laravel-filemanager/upload?type=Files&_token=';
CKEDITOR.replaceAll( 'editor');
</script>
You can do it in multiple ways:
1. Using greater
as comparison function :
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Using custom structure or class :
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Same result can be obtained by operator overloading :
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
In main function :
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Click here for a tutorial and working example from my website.
You no longer need to use hacks just to look jQuery Mobile Screen Orientation nor should you use PhoneGap anymore, unless you're actually using PhoneGap.
To make this work in the year 2015 we need:
And one of these plugins depending on your Cordova version:
cordova plugin add net.yoik.cordova.plugins.screenorientation
cordova plugin add cordova-plugin-screen-orientation
And to lock screen orientation just use this function:
screen.lockOrientation('landscape');
To unlock it:
screen.unlockOrientation();
Possible orientations:
portrait-primary The orientation is in the primary portrait mode.
portrait-secondary The orientation is in the secondary portrait mode.
landscape-primary The orientation is in the primary landscape mode.
landscape-secondary The orientation is in the secondary landscape mode.
portrait The orientation is either portrait-primary or portrait-secondary (sensor).
landscape The orientation is either landscape-primary or landscape-secondary (sensor).
Also this issue occurres when the response contenttype is not application/json
. In my case response contenttype was text/html
and i faced this problem. I changed it to application/json
then it worked.
I solved this issue by correcting my JDBC code.
the correct JDBC string should be...
conection = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","ishantyagi");
But the JDBC string I was using was ...
conection = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl","system","ishantyagi");
So, the mistake of specifying orcl instead of xe showed this error as the SID name was wrong.
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
Restrict the dimension of the NVARCHAR to 7, supplied to CONVERT to show only "YYYY-MM"
SELECT CONVERT(NVARCHAR(7),PaymentDate,120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(7),PaymentDate,120)
ORDER BY [Month]
Actually most of the answers here doesn't really scale the image to the width of itself.
We need to have a width and height of auto on the img
element itself so we can start with it's original size.
After that a container element can scale the image for us.
Simple HTML example:
<div style="position: relative;">
<figure>
<img src="[email protected]" />
</figure>
</div>
And here are the CSS rules. I use an absolute container in this case:
figure {
position: absolute;
left: 0;
top: 0;
-webkit-transform: scale(0.5);
-moz-transform: scale(0.5);
-ms-transform: scale(0.5);
-o-transform: scale(0.5);
transform: scale(0.5);
transform-origin: left;
}
figure img {
width: auto;
height: auto;
}
You could tweak the image positioning with rules like transform: translate(0%, -50%);
.
If you want to get the path of the workbook from where the macro is being executed - use Application.ThisWorkbook.Path
.
Application.ActiveWorkbook.Path
can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).
Since Guava 15.0 (released September 2013) there's EvictingQueue:
A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.
This class is not thread-safe, and does not accept null elements.
Example use:
EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]
The following will truncate the log.
USE [yourdbname]
GO
-- TRUNCATE TRANSACTION LOG --
DBCC SHRINKFILE(yourdbname_log, 1)
BACKUP LOG yourdbname WITH TRUNCATE_ONLY
DBCC SHRINKFILE(yourdbname_log, 1)
GO
-- CHECK DATABASE HEALTH --
ALTER FUNCTION [dbo].[checker]() RETURNS int AS BEGIN RETURN 0 END
GO
It would be more helpful if you posed a more complete working (or in this case non-working) example.
I tried the following:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(1000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()
This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1]
.
Further, as per the hist
documentation (i.e. ax.hist?
from ipython
), I think the sum is fine too:
*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``. In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::
pdf, bins, patches = ax.hist(...)
print np.sum(pdf * np.diff(bins))
Giving this a try after the commands above:
np.sum(n * np.diff(bins))
I get a return value of 1.0
as expected. Remember that normed=True
doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n)
returned approx 7.2767
.
Check this out : readdir()
This bit of code should list all entries in a certain directory:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
Edit: miah's solution is much more elegant than mine, you should use his solution instead.
Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.
string text = no.ToString("0000");
Because JavaScript is handling the click event. When you click, the following code is called:
el.addEvent('click', function(e){
if(obj.options.onOpen){
new Event(e).stop();
if(obj.options.open == i){
obj.options.open = null;
obj.options.onClose(this.href, i);
}else{
obj.options.open = i;
obj.options.onOpen(this.href, i);
}
}
})
The onOpen
manually changes the location
.
Edit: Regarding your comment...
If you can modify ImageMenu.js, you could update the script which calls onClose
to pass the a
element object (this
, rather than this.href
)
obj.options.onClose(this, i);
Then update your ImageMenu instance, with the following onOpen
change:
window.addEvent('domready', function(){
var myMenu = new ImageMenu($$('#imageMenu a'), {
openWidth: 310,
border: 2,
onOpen: function(e, i) {
if (e.target === '_blank') {
window.open(e.href);
} else {
location = e.href;
}
}
});
});
This would check for the target property of the element to see if it's _blank
, and then call window.open
, if found.
If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen
handler. Say something like:
<a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a>
Then, update your onOpen
call to:
onOpen: function(e, i) {
if (e.indexOf('_b=1') > -1) {
window.open(e);
} else {
location = e;
}
}
The only downside to this is the user sees the hash on hover.
Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like:
var linksThatOpenInANewWindow = {
'http://www.foracure.org.au': 1
};
onOpen: function(e, i) {
if (linksThatOpenInANewWindow[e] === 1) {
window.open(e);
} else {
location = e
}
}
The only downside is maintenance, depending on the number of links.
Others have suggested modifying the link (using #
or javascript:
) and adding an inline event handler (onclick
) - I don't recommend that at all as it breaks links when JS is disabled/not supported.
I built my answer thanks to previous contributors.
Not having time for a custom counter.exe, I downloaded sed for FREEDOS.
And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):
Just remember to manually create a file "test.txt" with written on the first row
0
sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
I've also had this happen (by accident) after creating a new venv while inside an existing virtual environment. an easy way to diagnose this would be to see where the python
is symlinked to, i.e. run:
ls -l venv/bin/python
and make sure it points to the appropriate Python binary. For most systems this will be /usr/bin/python
or /usr/bin/python3
. while if it points to an existing virtual environment it'll be something like /home/youruser/somedir/bin/python
. if it's the latter than I'd suggest recreating the venv while making sure that you aren't "inside" any existing virtualenv (i.e. run deactivate
)
For me, It was a permission issue. I installed SQL server using a local user account and before joining my companies domain. Later on , I tried to restore a database using my domain account which doesn't have the permissions needed to restore SQL server databases. You need to fix the permission for your domain account and give it system admin permission on the SQL server instance you have.
Didn't have +clipboard so I came up with this alternative solution using xsel:
Add to your ~/.vimrc:
vnoremap <C-C> :w !xsel -b<CR><CR>
If you installed from source, you can issue the following command:
sudo make uninstall
If you followed the instructions on https://github.com/nodejs/node/wiki to install to your $HOME/local/node, then you have to type the following before the line above:
./configure --prefix=$HOME/local/node
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
There is another simple solution to provide custom background for "Flat" buttons while keeping their "Material" effects.
i.e. :
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/blue">
<Button
style="?android:attr/buttonStyleSmall"
android:background="?android:attr/selectableItemBackground"
android:textColor="@android:color/white"
android:textAllCaps="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button1"
/>
</FrameLayout>
Can be used for Flat buttons, it works on API >=11, and you will get ripple effect on >=21 devices, keeping regular buttons on pre-21 till AppCompat is updated to support ripple there as well.
You can also use selectableItemBackgroundBorderless for >=21 buttons only.
I found success with the following, works with .zip
(Simplified here for posting: no error checking & just unzips all files to current folder)
function DownloadAndUnzip(URL){
var unzip = require('unzip');
var http = require('http');
var request = http.get(URL, function(response) {
response.pipe(unzip.Extract({path:'./'}))
});
}
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
function readFile() {_x000D_
_x000D_
if (this.files && this.files[0]) {_x000D_
_x000D_
var FR= new FileReader();_x000D_
_x000D_
FR.addEventListener("load", function(e) {_x000D_
document.getElementById("img").src = e.target.result;_x000D_
document.getElementById("b64").innerHTML = e.target.result;_x000D_
}); _x000D_
_x000D_
FR.readAsDataURL( this.files[0] );_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById("inp").addEventListener("change", readFile);
_x000D_
<input id="inp" type='file'>_x000D_
<p id="b64"></p>_x000D_
<img id="img" height="150">
_x000D_
(P.S: A base64 encoded image (String) 4/3 the size of the original image data)
Check this answer for multiple images upload.
Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit
.content {
width: 200px;
height: 600px;
background-color: blue;
position: absolute; /*Can also be `fixed`*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
max-width: 100%;
max-height: 100%;
overflow: auto;
}
I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:
window.location.href="pagelink"
It should be MM
for months. You are asking for minutes.
DateTime.Now.ToString("dd/MM/yyyy");
See Custom Date and Time Format Strings on MSDN for details.
To really update just one package install NCU and then run it just for that package. This will bump to the real latest.
npm install -g npm-check-updates
ncu -f your-intended-package-name -u
You can get active store information like this:
Mage::app()->getStore(); // for store object
Mage::app()->getStore()->getStoreId; // for store ID
If you just want to filter null values out of a stream, you can simply use a method reference to java.util.Objects.nonNull(Object). From its documentation:
This method exists to be used as a Predicate,
filter(Objects::nonNull)
For example:
List<String> list = Arrays.asList( null, "Foo", null, "Bar", null, null);
list.stream()
.filter( Objects::nonNull ) // <-- Filter out null values
.forEach( System.out::println );
This will print:
Foo
Bar
Quick alternative
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.
it is completely transparent Edittext with transparent background.
<item>
<shape android:shape="rectangle" >
<solid android:color="@color/transparent" />
</shape>
</item>
<item android:top="-3dp" android:right="-3dp" android:left="-3dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:width="2dp"
android:color="@color/bottomline" />
</shape>
</item>
In C++17 we gain the attribute [[maybe_unused]] which is covered in [dcl.attr.unused]
The attribute-token maybe_unused indicates that a name or entity is possibly intentionally unused. It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present. ...
Example:
[[maybe_unused]] void f([[maybe_unused]] bool thing1, [[maybe_unused]] bool thing2) { [[maybe_unused]] bool b = thing1 && thing2; assert(b); }
Implementations should not warn that b is unused, whether or not NDEBUG is defined. —end example ]
For the following example:
int foo ( int bar) {
bool unused_bool ;
return 0;
}
Both clang and gcc generate a diagnostic using -Wall -Wextra for both bar and unused_bool (See it live).
While adding [[maybe_unused]] silences the diagnostics:
int foo ([[maybe_unused]] int bar) {
[[maybe_unused]] bool unused_bool ;
return 0;
}
In C++11 an alternative form of the UNUSED
macro could be formed using a lambda expression(via Ben Deane) with an capture of the unused variable:
#define UNUSED(x) [&x]{}()
The immediate invocation of the lambda expression should be optimized away, given the following example:
int foo (int bar) {
UNUSED(bar) ;
return 0;
}
we can see in godbolt that the call is optimized away:
foo(int):
xorl %eax, %eax
ret
Another way:
Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree, I right-clicked on the and selected "Reset BRANCHNAME to this commit".
Then navigate to your repository's local directory and run this command:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f -- tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME
This will erase all commits after the current one in your local repository but only for that one branch.
If you want to match the entire string where you want to match everything but certain strings you can do it like this:
^(?!(red|green|blue)$).*$
This says, start the match from the beginning of the string where it cannot start and end with red, green, or blue and match anything else to the end of the string.
You can try it here: https://regex101.com/r/rMbYHz/2
Note that this only works with regex engines that support a negative lookahead.
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
To spool from a BEGIN
END
block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop
. Sample code is given below.
BEGIN
FOR x IN
(
SELECT COLUMN1,COLUMN2 FROM TABLE1
UNION ALL
SELECT COLUMN1,COLUMN2 FROM TABLEB
)
LOOP
dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;
END;
/
I've read this whole thread, and I just want to point out what seems like an inconsistency to me.
The compiler prevents you from doing the assignment with Lists:
List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList; // Compiler error
But the compiler is perfectly fine with arrays:
Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray; // No problem
The argument about whether the assignment is known to be safe falls apart here. The assignment I did with the array is not safe. To prove that, if I follow that up with this:
myAnimalsArray[1] = new Giraffe();
I get a runtime exception "ArrayTypeMismatchException". How does one explain this? If the compiler really wants to prevent me from doing something stupid, it should have prevented me from doing the array assignment.
It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.
This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString()
. I.e.
System.out.println(preparedStatement);
To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx()
methods and finally populates a SQL string on toString()
based on the logged information. For example Log4jdbc or P6Spy.
Try this
After selecting a block of text, press Shift+i or capital I.
Lowercase i will not work.
Then type the things you want and finally to apply it to all lines, press Esc twice.
If this doesn't work...
Check if you have +visualextra
enabled in your version of Vim.
You can do this by typing in :ver
and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)
Enabling it is outside the scope of this question but I'm sure you can find it somewhere.
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method only takes up constant memory(like iteration).
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
def fact(n):
return math.factorial(n)
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:
// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
int data;
apple * next;
};
// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }
void add(E &e) {
// access its next pointer by the member pointer
e.*next_ptr = head;
head = &e;
}
E * head;
E *E::*next_ptr;
};
int main() {
List<apple> lst(&apple::next);
apple a;
lst.add(a);
}
function char_convert() {
var chars = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"];
var codes = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","­","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"];
for(x=0; x<chars.length; x++){
for (i=0; i<arguments.length; i++){
arguments[i].value = arguments[i].value.replace(chars[x], codes[x]);
}
}
}
char_convert(this);
All the answers provided here uses normal function but these days most of our code uses arrow functions in ES6. I hope my answer will help readers on how to use arrow function when we do iteration over array of objects
let data = {
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
Do .forEach on array using arrow function
data.messages.forEach((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
Do .map on array using arrow function
data.messages.map((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
In case, like me, none of the above worked for you, I figured out a very stupid solution.
I'm using a HTC One X on a 2011 Macbook Pro. I just disabled NFC in Settings > Wireless & Networks > More > NFC and viola! Working normally.
It was moved to functools
.
Had the same error with PHP 7 on XAMPP and OSX.
The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:
Get root / intermediate certificate
First of all I had to figure out what's the root and the intermediate certificate.
The most convenient way is maybe an online cert-tool like the ssl-shopper
There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).
All I need to do is just search the internet for both of them. In my case, this is the root:
thawte DV SSL SHA256 CA
And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.
Get the host certificate
Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:
openssl s_client -showcerts -connect whatsyoururl.de:443 </dev/null 2>/dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert
Now bring them all together
Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:
cat /tmp/thawteRoot.crt > /tmp/chain.crt
cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt
tell PHP where to find the chain
There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).
So this is now my PHP-Code
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
"verify_peer"=> true,
"verify_peer_name"=> true,
),
);
$response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));
That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.
Note: if you're using(importing) org.json.simple.JSONArray
, you have to use JSONArray.size()
to get the data you want. But use JSONArray.length()
if you're using org.json.JSONArray
.
A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.
Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.
drop schema test1
Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.
You cannot drop a schema when it is in use. You have to first remove all objects from the schema.
Related reading:
Using typescript, I use a custom interface that only applies to my function. Example use case.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.
Later in my code I can use
<input type='text' value={this.state.value} onChange={this.handleChange} />
A cleaner approach would be to put the interface to a separate file.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
then later use the following function definition:
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.
The answer is in the current spec:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.
Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.
Reference:
Also see:
It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div>
is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").
A better example, from my understanding, might look something like this:
<div id="content">
<article>
<h2>How to use the section tag</h2>
<section id="disclaimer">
<h3>Disclaimer</h3>
<p>Don't take my word for it...</p>
</section>
<section id="examples">
<h3>Examples</h3>
<p>But here's how I would do it...</p>
</section>
<section id="closing_notes">
<h3>Closing Notes</h3>
<p>Well that was fun. I wonder if the spec will change next week?</p>
</section>
</article>
</div>
Note that <div>
, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.
If the answer of Kapil Vats is not working try something like this:
drawable/divider_horizontal_green_22.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="22dip"/>
<solid android:color="#00ff00"/>
</shape>
layout/your_layout.xml
LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/llTopBar"
android:orientation="horizontal"
android:divider="@drawable/divider_horizontal_green_22"
android:showDividers="middle"
>
I encountered an issue where the padding attribute wasn't working, thus I had to set the height of the divider directly in the divider.
Note:
If you want to use it in vertical LinearLayout, make a new one, like this: drawable/divider_vertical_green_22.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:height="22dip"/>
<solid android:color="#00ff00"/>
</shape>
Unless you need to access more memory that 32b addressing will allow you, the benefits will be small, if any.
When running on 64b CPU, you get the same memory interface no matter if you are running 32b or 64b code (you are using the same cache and same BUS).
While x64 architecture has a few more registers which allows easier optimizations, this is often counteracted by the fact pointers are now larger and using any structures with pointers results in a higher memory traffic. I would estimate the increase in the overall memory usage for a 64b application compared to a 32b one to be around 15-30 %.
Nesting a stackpanel will cause the textbox to wrap properly:
<Viewbox Margin="120,0,120,0">
<StackPanel Orientation="Vertical" Width="400">
<TextBlock x:Name="subHeaderText"
FontSize="20"
TextWrapping="Wrap"
Foreground="Black"
Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
</StackPanel>
</Viewbox>
This error happens when the branch you are switching to, has changes that your current branch doesn't have.
If you are seeing this error when you try to switch to a new branch, then your current branch is probably behind one or more commits. If so, run:
git fetch
You should also remove dependencies which may also conflict with the destination branch.
For example, for iOS developers:
pod deintegrate
then try checking out a branch again.
If the desired branch isn't new you can either cherry pick a commit and fix the conflicts or stash the changes and then fix the conflicts.
1. Git Stash (recommended)
git stash
git checkout <desiredBranch>
git stash apply
2. Cherry pick (more work)
git add <your file>
git commit -m "Your message"
git log
Copy the sha of your commit. Then discard unwanted changes:
git checkout .
git checkout -- .
git clean -f -fd -fx
Make sure your branch is up to date:
git fetch
Then checkout to the desired branch
git checkout <desiredBranch>
Then cherry pick the other commit:
git cherry-pick <theSha>
Now fix the conflict.
git checkout -f branch
What your looking for is the DefaultListModel - Dynamic String List Variable.
Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.
FileName: StringList.java
package YOUR_PACKAGE_GOES_HERE;
//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
public class StringList {
public static String OutputAsString(DefaultListModel list, int entry) {
return GetEntry(list, entry);
}
public static Object OutputAsObject(DefaultListModel list, int entry) {
return GetEntry(list, entry);
}
public static int OutputAsInteger(DefaultListModel list, int entry) {
return Integer.parseInt(list.getElementAt(entry).toString());
}
public static double OutputAsDouble(DefaultListModel list, int entry) {
return Double.parseDouble(list.getElementAt(entry).toString());
}
public static byte OutputAsByte(DefaultListModel list, int entry) {
return Byte.parseByte(list.getElementAt(entry).toString());
}
public static char OutputAsCharacter(DefaultListModel list, int entry) {
return list.getElementAt(entry).toString().charAt(0);
}
public static String GetEntry(DefaultListModel list, int entry) {
String result = "";
result = list.getElementAt(entry).toString();
return result;
}
public static void AddEntry(DefaultListModel list, String entry) {
list.addElement(entry);
}
public static void RemoveEntry(DefaultListModel list, int entry) {
list.removeElementAt(entry);
}
public static DefaultListModel StrToList(String input, String delimiter) {
DefaultListModel dlmtemp = new DefaultListModel();
input = input.trim();
delimiter = delimiter.trim();
while (input.toLowerCase().contains(delimiter.toLowerCase())) {
int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
dlmtemp.addElement(input.substring(0, index).trim());
input = input.substring(index + delimiter.length(), input.length()).trim();
}
return dlmtemp;
}
public static String ListToStr(DefaultListModel list, String delimiter) {
String result = "";
for (int i = 0; i < list.size(); i++) {
result = list.getElementAt(i).toString() + delimiter;
}
result = result.trim();
return result;
}
public static String LoadFile(String inputfile) throws IOException {
int len;
char[] chr = new char[4096];
final StringBuffer buffer = new StringBuffer();
final FileReader reader = new FileReader(new File(inputfile));
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static void SaveFile(String outputfile, String outputstring) {
try {
FileWriter f0 = new FileWriter(new File(outputfile));
f0.write(outputstring);
f0.flush();
f0.close();
} catch (IOException ex) {
Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.
SaveFile & LoadFile are to save and load strings to and from files.
StrToList & ListToStr are to place delimiters between each entry.
ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.
AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.
RemoveEntry is to delete a string from the DefaultListModel.
You use the DefaultListModel instead of an array here like this:
DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.
To the base question, the following will do the trick (hiding the taskbar)
private void Form1_Load(object sender, EventArgs e)
{
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
}
But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.
The answer already given of using find and sed
find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;
is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g'
instead of the sed
command.
For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:
rpl -R foo bar .
It's not available by default on most Linux distros but is quick to install (apt-get install rpl
or similar).
However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:
Check the README for examples.
Easiest method is
<TD>
<xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
</TD>
when the XML Structure is
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
If someone wants to transfer file from windows host to vagrant, then this solution worked for me.
1. Make sure to install **winscp** on your windows system
2. run **vagrant up** command
3. run **vagrant ssh-config** command and note down below details
4. Enter Hostname, Port, Username: vagrant, Password: vagrant in winscp and select **SCP**, file protocol
5. In most cases, hostname: 127.0.0.1, port: 2222, username: vagrant, password: vagrant.
You should be able to see directories in your vagrant machine.
I was experiencing this segmentation fault after upgrading dlib on RPI. I tracebacked the stack as suggested by Shiplu Mokaddim above and it settled on an OpenBLAS library.
Since OpenBLAS is also multi-threaded, using it in a muilt-threaded application will exponentially multiply threads until segmentation fault. For multi-threaded applications, set OpenBlas to single thread mode.
In python virtual environment, tell OpenBLAS to only use a single thread by editing:
$ workon <myenv>
$ nano .virtualenv/<myenv>/bin/postactivate
and add:
export OPENBLAS_NUM_THREADS=1
export OPENBLAS_MAIN_FREE=1
After reboot I was able to run all my image recognition apps on rpi3b which were previously crashing it.
reference: https://github.com/ageitgey/face_recognition/issues/294
This takes a lot of the grunt work out of printing / logging local values. It automatically captures the variable name within a String. This saves a lot of typing and typo correction.
The template:
+ ", ${1:var}: " + ${1:var}
It has two pitfalls:
Although you are prompted to select a local / parameter / field, this does not include primitives :(
Prompting occurs most whenever the code is compiled with no errors. Often using this macro yields temporarily broken syntax, so some juggling is necessary to insert multiple variables. Nothing close to the convenience of not having typos in variable names.
Or you can use std::advance
vector<int>::iterator i = L.begin();
advance(i, 2);
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
It's much better practise to avoid using sys.exit() and instead raise/handle exceptions to allow the program to finish cleanly. If you want to turn off traceback, simply use:
sys.trackbacklimit=0
You can set this at the top of your script to squash all traceback output, but I prefer to use it more sparingly, for example "known errors" where I want the output to be clean, e.g. in the file foo.py:
import sys
from subprocess import *
try:
check_call([ 'uptime', '--help' ])
except CalledProcessError:
sys.tracebacklimit=0
print "Process failed"
raise
print "This message should never follow an error."
If CalledProcessError is caught, the output will look like this:
[me@test01 dev]$ ./foo.py
usage: uptime [-V]
-V display version
Process failed
subprocess.CalledProcessError: Command '['uptime', '--help']' returned non-zero exit status 1
If any other error occurs, we still get the full traceback output.
Without explicitly providing the type as in command.Parameters.Add("@ID", SqlDbType.Int);
, it will try to implicitly convert the input to what it is expecting.
The downside of this, is that the implicit conversion may not be the most optimal of conversions and may cause a performance hit.
There is a discussion about this very topic here: http://forums.asp.net/t/1200255.aspx/1
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
I found this question while trying to split multiple contacts in a single vCard VCF file to separate files. Here's what I did based on Lee's code. I had to look up how to create a new StreamReader object and changed null to $null.
$reader = new-object System.IO.StreamReader("C:\Contacts.vcf")
$count = 1
$filename = "C:\Contacts\{0}.vcf" -f ($count)
while(($line = $reader.ReadLine()) -ne $null)
{
Add-Content -path $fileName -value $line
if($line -eq "END:VCARD")
{
++$count
$filename = "C:\Contacts\{0}.vcf" -f ($count)
}
}
$reader.Close()
I don't have R on this computer, but here is a crack at it. You can use par
to display multiple plots in a window, or like this to prompt for a click before displaying the next page.
plotfun <- function(col)
plot(data[ , col], ylab = names(data[col]), type = "l")
par(ask = TRUE)
sapply(seq(1, length(data), 1), plotfun)
This bash script will accept the root password as option and optimize it one by one, with status output:
#!/bin/bash
if [ -z "$1" ] ; then
echo
echo "ERROR: root password Parameter missing."
exit
fi
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
TBLLIST=""
COMMA=""
SQL="SELECT CONCAT(table_schema,'.',table_name) FROM information_schema.tables WHERE"
SQL="${SQL} table_schema NOT IN ('information_schema','mysql','performance_schema')"
for DBTB in `mysql ${MYSQL_CONN} -ANe"${SQL}"`
do
echo OPTIMIZE TABLE "${DBTB};"
SQL="OPTIMIZE TABLE ${DBTB};"
mysql ${MYSQL_CONN} -ANe"${SQL}"
done
I always prefer to use the example mentioned in Konva JS: Image Events to load images.
You need to have a list of image URLs as object or array, for example:
var sources = {
lion: '/assets/lion.png',
monkey: '/assets/monkey.png'
};
Define the Function definition, where it receives list of image URLs and a callback function in its arguments list, so when it finishes loading image you can start excution on your web page:
function loadImages(sources, callback) {_x000D_
var images = {};_x000D_
var loadedImages = 0;_x000D_
var numImages = 0;_x000D_
for (var src in sources) {_x000D_
numImages++;_x000D_
}_x000D_
for (var src in sources) {_x000D_
images[src] = new Image();_x000D_
images[src].onload = function () {_x000D_
if (++loadedImages >= numImages) {_x000D_
callback(images);_x000D_
}_x000D_
};_x000D_
images[src].src = sources[src];_x000D_
}_x000D_
}
_x000D_
$(document).ready(function (){
loadImages(sources, buildStage);
});
Use gson. https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);
output
{
"name": "mkyong",
"age": 35,
"position": "Founder",
"salary": 10000,
"skills": [
"java",
"python",
"shell"
]
}
If all the previous answers didn't give any solution, you should check your user privileges.
If you could login as root
to mysql
then you should add this:
CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY '***';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.1.100' IDENTIFIED BY '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100
. It should work.
This error can occur for lots of reasons, and the last time, I solved it by modifying the Reference.svcmap
file, and changing how the WSDL file is referenced.
Throwing exception:
<MetadataSource Address="C:\Users\Me\Repo\Service.wsdl" Protocol="file" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="file:///C:/Users/Me/Repo/Service.wsdl" />
Working fine:
<MetadataSource Address="https://server.domain/path/Service.wsdl" Protocol="http" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="https://server.domain/path/Service.wsdl" />
This seems weird, but I have reproduced it. This was in a console application on .NET 4.5 and 4.7, as well as a .NET WebAPI site on 4.7.
No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)
Does the -verbose
flag to your java
command yield any useful info? If not, maybe java -X
reveals something specific to your version that might help?
Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.
CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...
or
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Code should go somewhere in your Global.asax file
protected void Application_Start(){ ...
Bitcode (iOS, watchOS)
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.
Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.
Devs don't have to make changes and submit the app again to support new platforms.
Let's take the example of iPhone 5s when apple introduced x64
chip in it. Although x86
apps were totally compatible with x64
architecture but to fully utilise the x64
platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.
If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64
bit architecture.
Try it:
<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>
<script>
window.onload = function() {
document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
if (event.keyCode == 13) {
document.getElementById('btnSearch').click();
}
};
document.getElementById('btnSearch').onclick =doSomething;
}
</script>
just a tip,
try to use JodaTime instead of java,util.Date it is much more powerfull and it has a method toString("") that you can pass the format you want like toString("yyy-MM-dd HH:mm:ss");
You could do something with APIs.
Private Const SW_SHOW = 5
Private Const GW_HWNDNEXT = 2
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function ShowWindow Lib "user32" _
(ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function GetWindow Lib "user32" _
(ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Function FindWindowPartialX(ByVal Title As String) As Long
Dim hWndThis As Long
hWndThis = FindWindow(vbNullString, vbNullString)
While hWndThis
Dim sTitle As String, sClass As String
sTitle = Space$(255)
sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
sClass = Space$(255)
sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
If InStr(sTitle, Title) > 0 Then
FindWindowPartialX = hWndThis
Exit Function
End If
hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
Wend
End Function
Sub CopySheet()
Dim objXL As Excel.Application
' A suitable portion of the window title such as file name '
WinHandle = FindWindowPartialX("LTD.xls")
ShowWindow WinHandle, SW_SHOW
Set objXL = GetObject(, "Excel.Application")
objXL.Worksheets("Source").Activate
objXL.ActiveSheet.UsedRange.Copy
Application.ActiveSheet.Paste
End Sub
=ROUND((TODAY()-A1)/365,0)
will provide number of years between date in cell A1 and today's date
Sounds like you really want a Dictionary<int, string>
or possibly a switch
statement...
You can do it with the conditional operator though:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
While you could put that in one line, I'd strongly urge you not to.
I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.
Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.
<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere"
style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>
<asp:Label id="Label1" runat="server"/>
Then it will be available when in your handler:
protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}
More info on MSDN
you can check first if name of your function isn`t exists or not before you write function By
if (!function_exists('generate_salt'))
{
function generate_salt()
{
........
}
}
OR you can change name of function to another name
I used to reset the IFS value and rollback when done.
# backup IFS value
O_IFS=$IFS
# reset IFS value
IFS=""
FILES=(
"2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg"
)
for file in ${FILES[@]}; do
echo ${file}
done
# rollback IFS value
IFS=${O_IFS}
Possible output from the loop:
2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
You Can use simply git checkout <commit hash>
in this sequence
bash
git clone [URLTORepository]
git checkout [commithash]
commit hash looks like this "45ef55ac20ce2389c9180658fdba35f4a663d204"
I would prefer the C++ min/max functions, if you are using C++, because they are type-specific. fmin/fmax will force everything to be converted to/from floating point.
Also, the C++ min/max functions will work with user-defined types as long as you have defined operator< for those types.
HTH
What is a constant reference (not a reference to a constant)
A Constant Reference is actually a Reference to a Constant.
A constant reference/ Reference to a constant is denoted by:
int const &i = j; //or Alternatively
const int &i = j;
i = 1; //Compilation Error
It basically means, you cannot modify the value of type object to which the Reference Refers.
For Example:
Trying to modify value(assign 1
) of variable j
through const reference, i
will results in error:
assignment of read-only reference ‘i’
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99;
Doesn't change the reference, it assigns the value of the type to which the reference refers. References cannot be made to refer any other variable than the one they are bound to at Initialization.
First statement assigns the value y
to i
Second statement assigns the value 99
to i
Do you mean like this
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
string also implements IEnumberable<char>
so you can also enumerate it like this
foreach (char c in s)
Console.WriteLine(c);
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.
// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2
function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}
P.S. would have commented directly to vitran's post but I don't have the rep to do that.
It is located in the AppData
hidden folder
C:\Users\[user]\AppData\Local\Android\sdk\platform-tools
From l33t's comment below you may use the following shortcut:
%LOCALAPPDATA%\Android\sdk\platform-tools
For following Error:
ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.
Run following NPM command:
$ npm install [email protected]
Source Link
Yes, all you need to do is call finish() in any Activity you would like to close.
Try
$("#myModal").modal("toggle")
To open or close the modal with id myModal.
If the above is not working then it means bootstrap.js has been overridden by some other js file. Here is a solution
1:- Move bootstrap.js to the bottom so that it will override other js files.
2:- Make sure the order is like below
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>
In case your session expires, you can use this, to login again
$(document).ajaxComplete(function(e, xhr, opt){
if(xhr.status===419){
if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
}
});
It sounds like you'd be happer with a single table. The five having the same schema, and sometimes needing to be presented as if they came from one table point to putting it all in one table.
Add a new column which can be used to distinguish among the five languages (I'm assuming it's language that is different among the tables since you said it was for localization). Don't worry about having 4.5 million records. Any real database can handle that size no problem. Add the correct indexes, and you'll have no trouble dealing with them as a single table.
You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.
For a side-by-side visual representation, I use git difftool
with openDiff
set to the default viewer.
Example usage:
git difftool tags/<FIRST TAG> tags/<SECOND TAG>
If you are only interested in a specific file, you can use:
git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>
As a side-note, the tags/<TAG>
s can be replaced with <BRANCH>
es if you are interested in diff
ing branches.
I use a mixture of float and overflow-x:hidden. Minimal code, always works.
https://jsfiddle.net/9934sc4d/4/ - PLUS you don't need to clear your float!
.left-half{
width:200px;
float:left;
}
.right-half{
overflow-x:hidden;
}
My app, DropDMG, is an easy way to create disk images with background pictures, icon layouts, custom volume icons, and software license agreements. It can be controlled from a build system via the "dropdmg" command-line tool or AppleScript. If desired, the picture and license RTF files can be stored under your version control system.
One liner for modern browsers (IE10+):
var d = new Date(Date.parse("2010-06-09 13:12:01"));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
And just for fun, here's a one-liner that will work across older browsers (now fixed):
new (Function.prototype.bind.apply(Date, [null].concat("2010-06-09 13:12:01".split(/[\s:-]/)).map(function(v,i){return i==2?--v:v}) ));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
return {_x000D_
country: elem.country,_x000D_
launches: elem.launches+10,_x000D_
} _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
In fact, except the Html object, you also could use the Spannable type classes, e.g. TextAppearanceSpan or TypefaceSpan and SpannableString togather. Html class also uses these mechanisms. But with the Spannable type classes, you've more freedom.
The accepted answer is correct, but not complete.
In order for Select All
to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All
will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.
Here you can find the direct download link for Curl.exe
I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just
unzip it and then go to bin folder there you get exe file
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
As with all date manipulation you have to use NSDateComponents and NSCalendar
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:10];
NSDate *today10am = [calendar dateFromComponents:components];
in iOS8 Apple introduced a convenience method that saves a few lines of code:
NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];
Swift:
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!
I have try with the SCFRench and with the Ru Hasha on octave.
And finally it works: but I have done some modification
function message = makefuns
assignin('base','fun1', @fun1); % Ru Hasha
assignin('base', 'fun2', @fun2); % Ru Hasha
message.fun1=@fun1; % SCFrench
message.fun2=@fun2; % SCFrench
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
Can be called in other 'm' file:
printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());
update:
I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).
yes, %c
will print a single char:
printf("%c", 'h');
also, putchar
/putc
will work too. From "man putchar":
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
Often you will want to have a definition of an interface without having to ship the entire code. For example, if you have a shared library, you would ship a header file with it which defines all the functions and symbols used in the shared library. Without header files, you would need to ship the source.
Within a single project, header files are used, IMHO, for at least two purposes:
My problem was with Yeoman, using (capitalized):
yo angular:factory Test
Made files (uncapitalized):
app/scripts/services/test.js
but the index.html file included (capitalized):
<script src="scripts/services/Test.js"></script>
Hope this helps someone.
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
To get the text content
document.getElementById ( "tdid" ).innerText
or
document.getElementById ( "tdid" ).textContent
var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerText | tdElem.textContent;
If you can use jQuery then you can use
$("#tdid").text();
To get the HTML content
var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerHTML;
in jQuery
$("#tdid").html();
just made something like this as an exercise in Eloquent JavaScript
function range(start, end, step) {
var ar = [];
if (start < end) {
if (arguments.length == 2) step = 1;
for (var i = start; i <= end; i += step) {
ar.push(i);
}
}
else {
if (arguments.length == 2) step = -1;
for (var i = start; i >= end; i += step) {
ar.push(i);
}
}
return ar;
}
They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.
For those who want to know the reason, but don't want to read the article referenced in is vs typeof.
Cleanly read in a couple prompted values:
// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
strings.TrimSpace(text), strings.TrimSpace(text2))
Here's a run:
Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"
I found this helpful...
http://www.cmake.org/pipermail/cmake/2011-June/045222.html
From their example:
ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)
foreach (string s in sList)
{
if (s.equals("ok"))
return true;
}
return false;
Alternatively, if you need to do some other things after you've found the item:
bool found = false;
foreach (string s in sList)
{
if (s.equals("ok"))
{
found = true;
break; // get out of the loop
}
}
// do stuff
return found;
First, if you wanna cast type, then this:
import org.apache.spark.sql
df.withColumn("year", $"year".cast(sql.types.IntegerType))
With same column name, the column will be replaced with new one. You don't need to do add and delete steps.
Second, about Scala vs R.
This is the code that most similar to R I can come up with:
val df2 = df.select(
df.columns.map {
case year @ "year" => df(year).cast(IntegerType).as(year)
case make @ "make" => functions.upper(df(make)).as(make)
case other => df(other)
}: _*
)
Though the code length is a little longer than R's. That is nothing to do with the verbosity of the language. In R the mutate
is a special function for R dataframe, while in Scala you can easily ad-hoc one thanks to its expressive power.
In word, it avoid specific solutions, because the language design is good enough for you to quickly and easy build your own domain language.
side note: df.columns
is surprisingly a Array[String]
instead of Array[Column]
, maybe they want it look like Python pandas's dataframe.
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.
import java.util.Arrays
public class ResizingArray {
public static void main(String[] args) {
String[] stringArray = new String[2] //A string array with 2 strings
stringArray[0] = "string1";
stringArray[1] = "string2";
// increase size and add string to array by copying to a temporary array
String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
// Add in the new string
tempStringArray[2] = "string3";
// Copy temp array to original array
stringArray = tempStringArray;
// decrease size by removing certain string from array (string1 for example)
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == string1) {
stringArray[i] = stringArray[stringArray.length - 1];
// This replaces the string to be removed with the last string in the array
// When the array is resized by -1, The last string is removed
// Which is why we copied the last string to the position of the string we wanted to remove
String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
// Set the original array to the new array
stringArray = tempStringArray2;
}
}
}
}
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
You can use readonly
attribute, if you want your input only to be read. And you can use disabled
attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).
You can't apply a keypair to a running instance. You can only use the new keypair to launch a new instance.
For recovery, if it's an EBS boot AMI, you can stop it, make a snapshot of the volume. Create a new volume based on it. And be able to use it back to start the old instance, create a new image, or recover data.
Though data at ephemeral storage will be lost.
Due to the popularity of this question and answer, I wanted to capture the information in the link that Rodney posted on his comment.
Credit goes to Eric Hammond for this information.
You can examine and edit files on the root EBS volume on an EC2 instance even if you are in what you considered a disastrous situation like:
On a physical computer sitting at your desk, you could simply boot the system with a CD or USB stick, mount the hard drive, check out and fix the files, then reboot the computer to be back in business.
A remote EC2 instance, however, seems distant and inaccessible when you are in one of these situations. Fortunately, AWS provides us with the power and flexibility to be able to recover a system like this, provided that we are running EBS boot instances and not instance-store.
The approach on EC2 is somewhat similar to the physical solution, but we’re going to move and mount the faulty “hard drive” (root EBS volume) to a different instance, fix it, then move it back.
In some situations, it might simply be easier to start a new EC2 instance and throw away the bad one, but if you really want to fix your files, here is the approach that has worked for many:
Setup
Identify the original instance (A) and volume that contains the broken root EBS volume with the files you want to view and edit.
instance_a=i-XXXXXXXX
volume=$(ec2-describe-instances $instance_a |
egrep '^BLOCKDEVICE./dev/sda1' | cut -f3)
Identify the second EC2 instance (B) that you will use to fix the files on the original EBS volume. This instance must be running in the same availability zone as instance A so that it can have the EBS volume attached to it. If you don’t have an instance already running, start a temporary one.
instance_b=i-YYYYYYYY
Stop the broken instance A (waiting for it to come to a complete stop), detach the root EBS volume from the instance (waiting for it to be detached), then attach the volume to instance B on an unused device.
ec2-stop-instances $instance_a
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_b --device /dev/sdj $volume
ssh to instance B and mount the volume so that you can access its file system.
ssh ...instance b...
sudo mkdir -p 000 /vol-a
sudo mount /dev/sdj /vol-a
Fix It
At this point your entire root file system from instance A is available for viewing and editing under /vol-a on instance B. For example, you may want to:
Note: The uids on the two instances may not be identical, so take care if you are creating, editing, or copying files that belong to non-root users. For example, your mysql user on instance A may have the same UID as your postfix user on instance B which could cause problems if you chown files with one name and then move the volume back to A.
Wrap Up
After you are done and you are happy with the files under /vol-a, unmount the file system (still on instance-B):
sudo umount /vol-a
sudo rmdir /vol-a
Now, back on your system with ec2-api-tools, continue moving the EBS volume back to it’s home on the original instance A and start the instance again:
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_a --device /dev/sda1 $volume
ec2-start-instances $instance_a
Hopefully, you fixed the problem, instance A comes up just fine, and you can accomplish what you originally set out to do. If not, you may need to continue repeating these steps until you have it working.
Note: If you had an Elastic IP address assigned to instance A when you stopped it, you’ll need to reassociate it after starting it up again.
Remember! If your instance B was temporarily started just for this process, don’t forget to terminate it now.
Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.
Your problem is that class B is not declared as a "new-style" class. Change it like so:
class B(object):
and it will work.
super()
and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object)
on any class definition to make sure it is a new-style class.
Old-style classes (also known as "classic" classes) are always of type classobj
; new-style classes are of type type
. This is why you got the error message you saw:
TypeError: super() argument 1 must be type, not classobj
Try this to see for yourself:
class OldStyle:
pass
class NewStyle(object):
pass
print type(OldStyle) # prints: <type 'classobj'>
print type(NewStyle) # prints <type 'type'>
Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
If you set up an IAM role for your server that has the AmazonAPIGatewayInvokeFullAccess permission, you still need to pass headers on each request. You can do this in python with the aws-requests-auth library like so:
import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
auth = BotoAWSRequestsAuth(
aws_host="API_ID.execute-api.us-east-1.amazonaws.com",
aws_region="us-east-1",
aws_service="execute-api"
)
response = requests.get("https://API_ID.execute-api.us-east-1.amazonaws.com/STAGE/RESOURCE", auth=auth)
I know this is old as dirt but it ranked pretty high in google.
The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks
In the example given
num = 0
While num < 10
If status = "Fail" Then
num = 10
End If
num = num + 1
Wend
After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.
Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:
num = 0
While num < 10
If folder = "System32" Then
num = 10
End If
RecursiveDeleteFunction folder
num = num + 1
Wend
Using Do While
or Do Until
allows you to stop execution of the loop using Exit Do
instead of using trickery with your loop condition to maintain the While ... Wend
syntax. I would recommend using that instead.
No, because there's no precompiler. However, in your case you could achieve the same thing as follows:
class MyClass
{
private static final int PROTEINS = 0;
...
MyArray[] foo = new MyArray[PROTEINS];
}
The compiler will notice that PROTEINS
can never, ever change and so will inline it, which is more or less what you want.
Note that the access modifier on the constant is unimportant here, so it could be public
or protected
instead of private, if you wanted to reuse the same constant across multiple classes.
You could use SET DATEFORMAT, like in this example
declare @dates table (orig varchar(50) ,parsed datetime)
SET DATEFORMAT ydm;
insert into @dates
select '2008-09-01','2008-09-01'
SET DATEFORMAT ymd;
insert into @dates
select '2008-09-01','2008-09-01'
select * from @dates
You would need to specify the dateformat in the code when you parse your XML data