Better to support all the browsers:
img.lessOpacity {
opacity: 0.4;
filter: alpha(opacity=40);
zoom: 1; /* needed to trigger "hasLayout" in IE if no width or height is set */
}
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
You can use -exec to run a command on the output of a command. So it will be a reuse of the output as an example given with a find
command below:
find . -name anything.out -exec rm {} \;
you are saying here -> find a file called anything.out in the current folder, if found, remove it. If it is not found, the remaining after -exec will be skipped.
It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.
We use three libraries:
(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,
(2) iTextPDF (itextpdf-5.5.0.jar),
(3) XMLWorker (xmlworker-5.5.1.jar).
public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
if ( !path.exists() ){ path.mkdir(); }
File file = new File(path, fileName);
try{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// ?????????????? HTML
String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
// ???????? ???????? PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont());
document.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:
public class MyFont implements FontProvider{
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }
@Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color){
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
@Override
public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}
Here we use the standard Android font Droid Sans, which is located in the system folder:
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
The easiest way to do this would be to use a filter.
You can either filter for any cells in column A that don't have a "-" and copy / paste, or (my more preferred method) filter for all cells that do have a "-" and then select all and delete - Once you remove the filter, you're left with what you need.
Hope this helps.
Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver
under on reboot and wanted to keep all my cron jobs in one place.
I was getting the following error for the VNC cron:
vncserver: The USER environment variable is not set. E.g.:
In my case, I was able to use sudo
to specify who to run the task as.
@reboot sudo -u [someone] vncserver ...
Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:
<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->
If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:
<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>
(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:
Whatever Node.js version you have installed, run its installer again. It asks you to remove Node.js like this:
I see that this question is already old but still...
We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.
I hope it helps :)
In my XFCE (version 4.12), it's in Settings -> Window Manager Tweaks -> Accessibility
.
There's a dropdown field Key used to grab and move windows:
, set this to None
.
Alt + Click works now in VS Code to add more cursor.
Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.
You can do something like this.
bind your event into a common function and call the event either with keypress or button click.
for example.
function callME(event){
alert('Hi');
}
$('button').on("click",callME);
$('input ').keypress(function(event){
if (event.which == 13) {
callME(event);
}
});
Also possible is to fix this with np.arange() instead of range which works for float numbers:
import numpy as np
for i in np.arange(c/10):
No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.
Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.
I was getting this error while trying to show DatePicker
from Fragment
.
I changed
val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)
to
val datePickerDialog = DatePickerDialog(requireContext(), ...)
and it worked just fine.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
Take a look at the .classpath file in your project, which probably contains most of the information that you want. The easiest option may be to roll your own "build.xml export", i.e. process .classpath into a new build.xml during the build itself, and then call it with an ant subtask.
Parsing a little XML sounds much easier to me than to hook into Eclipse JDT.
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
(\d+)\s+(\(.*?\))?\s?Z
Note the escaped parentheses, and the ?
(zero or once) quantifiers. Any of the groups you don't want to capture can be (?:
non-capture groups).
I agree about the spaces. \s
is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^
at the front and a $
at the end).
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.
Using standard javax.sound API, a single Maven dependency, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
Well the easiest way to reset root password is:
restart mysqld --skip-grant-tables option. This enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.
Connect to the mysqld server with this command:
shell> mysql Issue the following statements in the mysql client. Replace the password with the password that you want to use.
mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass') -> WHERE User='root'; mysql> FLUSH PRIVILEGES;
Stop the server, then restart it normally (without the --skip-grant-tables and --skip-networking options).
Source Mysql documentation and personal experience:
http://dev.mysql.com/doc/refman/5.6/en/resetting-permissions.html
I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured
However, the IISExpress.config settings file had:
<windowsAuthentication enabled="false">
The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.
Converting a date String of the format "2011-06-23T15:11:32" to our time zone.
private String getDate(String ourDate)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
ourDate = dateFormatter.format(value);
//Log.d("ourDate", ourDate);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}
Some applications launches themselves by protocols. like itunes with "itms://" links. I don't know however how you can register that with windows.
The accepted answer may solve the question, but if you want multiline if
conditions in the dockerfile, you can do that placing \
at the end of each line (similar to how you would do in a shell script) and ending each command with ;
. You can even define someting like set -eux
as the 1st command.
Example:
RUN set -eux; \
if [ -f /path/to/file ]; then \
mv /path/to/file /dest; \
fi; \
if [ -d /path/to/dir ]; then \
mv /path/to/dir /dest; \
fi
In your case:
FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
echo Argument not provided; \
else \
echo Argument is $arg; \
fi
Then build with:
docker build -t my_docker . --build-arg arg=42
You could use PhoneGap.
This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView
as detailed in @Enigma's answer.
See below for an explanation.
$(document).ready(function() {_x000D_
_x000D_
function exportTableToCSV($table, filename) {_x000D_
_x000D_
var $rows = $table.find('tr:has(td)'),_x000D_
_x000D_
// Temporary delimiter characters unlikely to be typed by keyboard_x000D_
// This is to avoid accidentally splitting the actual contents_x000D_
tmpColDelim = String.fromCharCode(11), // vertical tab character_x000D_
tmpRowDelim = String.fromCharCode(0), // null character_x000D_
_x000D_
// actual delimiter characters for CSV format_x000D_
colDelim = '","',_x000D_
rowDelim = '"\r\n"',_x000D_
_x000D_
// Grab text from table into CSV formatted string_x000D_
csv = '"' + $rows.map(function(i, row) {_x000D_
var $row = $(row),_x000D_
$cols = $row.find('td');_x000D_
_x000D_
return $cols.map(function(j, col) {_x000D_
var $col = $(col),_x000D_
text = $col.text();_x000D_
_x000D_
return text.replace(/"/g, '""'); // escape double quotes_x000D_
_x000D_
}).get().join(tmpColDelim);_x000D_
_x000D_
}).get().join(tmpRowDelim)_x000D_
.split(tmpRowDelim).join(rowDelim)_x000D_
.split(tmpColDelim).join(colDelim) + '"';_x000D_
_x000D_
// Deliberate 'false', see comment below_x000D_
if (false && window.navigator.msSaveBlob) {_x000D_
_x000D_
var blob = new Blob([decodeURIComponent(csv)], {_x000D_
type: 'text/csv;charset=utf8'_x000D_
});_x000D_
_x000D_
// Crashes in IE 10, IE 11 and Microsoft Edge_x000D_
// See MS Edge Issue #10396033_x000D_
// Hence, the deliberate 'false'_x000D_
// This is here just for completeness_x000D_
// Remove the 'false' at your own risk_x000D_
window.navigator.msSaveBlob(blob, filename);_x000D_
_x000D_
} else if (window.Blob && window.URL) {_x000D_
// HTML5 Blob _x000D_
var blob = new Blob([csv], {_x000D_
type: 'text/csv;charset=utf-8'_x000D_
});_x000D_
var csvUrl = URL.createObjectURL(blob);_x000D_
_x000D_
$(this)_x000D_
.attr({_x000D_
'download': filename,_x000D_
'href': csvUrl_x000D_
});_x000D_
} else {_x000D_
// Data URI_x000D_
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);_x000D_
_x000D_
$(this)_x000D_
.attr({_x000D_
'download': filename,_x000D_
'href': csvData,_x000D_
'target': '_blank'_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
// This must be a hyperlink_x000D_
$(".export").on('click', function(event) {_x000D_
// CSV_x000D_
var args = [$('#dvData>table'), 'export.csv'];_x000D_
_x000D_
exportTableToCSV.apply(this, args);_x000D_
_x000D_
// If CSV, don't do event.preventDefault() or return false_x000D_
// We actually need this to be a typical hyperlink_x000D_
});_x000D_
});
_x000D_
a.export,_x000D_
a.export:visited {_x000D_
display: inline-block;_x000D_
text-decoration: none;_x000D_
color: #000;_x000D_
background-color: #ddd;_x000D_
border: 1px solid #ccc;_x000D_
padding: 8px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" class="export">Export Table data into Excel</a>_x000D_
<div id="dvData">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Column One</th>_x000D_
<th>Column Two</th>_x000D_
<th>Column Three</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row1 Col1</td>_x000D_
<td>row1 Col2</td>_x000D_
<td>row1 Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row2 Col1</td>_x000D_
<td>row2 Col2</td>_x000D_
<td>row2 Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row3 Col1</td>_x000D_
<td>row3 Col2</td>_x000D_
<td>row3 Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row4 'Col1'</td>_x000D_
<td>row4 'Col2'</td>_x000D_
<td>row4 'Col3'</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row5 "Col1"</td>_x000D_
<td>row5 "Col2"</td>_x000D_
<td>row5 "Col3"</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row6 "Col1"</td>_x000D_
<td>row6 "Col2"</td>_x000D_
<td>row6 "Col3"</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
Now uses HTML5 Blob
and URL
as the preferred method with Data URI
as a fallback.
Other answers suggest window.navigator.msSaveBlob
; however, it is known to crash IE10/Window 7 and IE11/Windows 10. Whether it works using Microsoft Edge is dubious (see Microsoft Edge issue ticket #10396033).
Merely calling this in Microsoft's own Developer Tools / Console causes the browser to crash:
navigator.msSaveBlob(new Blob(["hello"], {type: "text/plain"}), "test.txt");
?Four years after my first answer, new IE versions include IE10, IE11, and Edge. They all crash on a function that Microsoft invented (slow clap).
Add
navigator.msSaveBlob
support at your own risk.
Typically this would be performed using a server-side solution, but this is my attempt at a client-side solution. Simply dumping HTML as a Data URI
will not work, but is a helpful step. So:
window.open
approach would not work in Firefox, so I used <a href="{Data URI here}">
.<a>
tag's download
attribute, which only works in Firefox and Google Chrome. Since it is just an attribute, it degrades gracefully.About the "download" attribute, see these:
Browsers testing includes:
The CSV is exported correctly, but when imported into Excel, the character ü
is printed out as ä
. Excel interprets the value incorrectly.
Introduce var csv = '\ufeff';
and then Excel 2013+ interprets the values correctly.
If you need compatibility with Excel 2007, add UTF-8 prefixes at each data value. See also:
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
You can use UITapGestureRecongnizer method for dismissing keyboard by clicking outside of UITextField. By using this method whenever user will click outside of UITextField then keyboard will get dismiss. Below is the code snippet for using it.
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissk)];
[self.view addGestureRecognizer:tap];
//Method
- (void) dismissk
{
[abctextfield resignFirstResponder];
[deftextfield resignFirstResponder];
}
Apache
, as usual, has a good answer from Apache Commons-Lang
in the form of
NumberUtils.isCreatable(String)
.
Handles null
s, no try
/catch
block required.
You use:
yourcommand > /dev/null 2>&1
If it should run in the Background add an &
yourcommand > /dev/null 2>&1 &
>/dev/null 2>&1
means redirect stdout
to /dev/null
AND stderr
to the place where stdout
points at that time
If you want stderr
to occur on console and only stdout
going to /dev/null
you can use:
yourcommand 2>&1 > /dev/null
In this case stderr
is redirected to stdout
(e.g. your console) and afterwards the original stdout
is redirected to /dev/null
If the program should not terminate you can use:
nohup yourcommand &
Without any parameter all output lands in nohup.out
Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.
The easiest way to handle this is to rename the column, copy the data over, then drop the original column:
alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;
alter table EVAPP_FEES add AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_OLD;
alter table EVAPP_FEES drop column AMOUNT_OLD;
If you really want to retain the column ordering, you can move the data twice instead:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
I feel a little stupid, but my issue was that I was running docker-compose, and my Dockerfile was in a ./deploy subdirectory. My ADD reference needed to be relative to the root of the project, not the Dockerfile.
Changed: ADD ./file.tar.gz /etc/folder/ to: ADD ./deploy/file.tar.gz /etc/folder/
Anyhow, thought I'd post in case someone ran into the same issue.
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
Make an equals
check on the keySet()
of both HashMap
s.
NOTE:
If your Map
contains String
keys then it is no problem, but if your Map contains objA
type keys then you need to make sure that your class objA
implements equals()
.
Setting android:background
and android:button
of the RadioButton like the accepted answer didn't work for me. The drawable image was being displayed as a background(eventhough android:button
was being set to transparent ) to the radio button text as
android:background="@drawable/radiobuttonstyle"
android:button="@android:color/transparent"
so gave radiobutton as the custom drawable radiobuttonstyle.xml
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Maintenance"
android:id="@+id/radioButton1"
android:button="@drawable/radiobuttonstyle"
/>
and radiobuttonstyle.xml is as follows
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/ic_radio_checked"></item>
<item android:state_checked="false" android:drawable="@drawable/ic_radio_unchecked"></item>
</selector>
and after this radiobutton with custom button style worked.
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async
/await
/Promise()
or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert()
- or finishing the task at hand)
Using async
/await
/Promise()
:
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
_x000D_
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
_x000D_
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial
to utilize the two-parameter operator.mul
with a fixed multiple
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
Take a look from here https://www.regextester.com/?fam=114662
Use this following Regular Expression Details, This will support leap year also.
var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([1][26]|[2468][048]|[3579][26])00))))$/g;
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
Here's a bash function which checks all your servers, assuming you're using DNS round-robin. Note that this requires GNU date and won't work on Mac OS
function check_certs () {
if [ -z "$1" ]
then
echo "domain name missing"
exit 1
fi
name="$1"
shift
now_epoch=$( date +%s )
dig +noall +answer $name | while read _ _ _ _ ip;
do
echo -n "$ip:"
expiry_date=$( echo | openssl s_client -showcerts -servername $name -connect $ip:443 2>/dev/null | openssl x509 -inform pem -noout -enddate | cut -d "=" -f 2 )
echo -n " $expiry_date";
expiry_epoch=$( date -d "$expiry_date" +%s )
expiry_days="$(( ($expiry_epoch - $now_epoch) / (3600 * 24) ))"
echo " $expiry_days days"
done
}
Output example:
$ check_certs stackoverflow.com
151.101.1.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.65.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.129.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.193.69: Aug 14 12:00:00 2019 GMT 603 days
Try like it:
vagrant plugin install vagrant-vbguest
In Vagrantfile add:
config.vbguest.iso_path = "http://download.virtualbox.org/virtualbox/VERSION/VBoxGuestAdditions_VERSION.iso"
config.vbguest.auto_update = false
config.vbguest.installer_arguments = %w{--nox11 -- --force}
Run:
vagrant vbguest --do install -f -b
vagrant reload
Instead of injecting ElementRef
and using querySelector
or similar from there, a declarative way can be used instead to access elements in the view directly:
<input #myname>
@ViewChild('myname') input;
element
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
@ViewChildren('var1,var2,var3')
). <ng-content>
projected elements).descendants
@ContentChildren()
is the only one that allows to also query for descendants
@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField;
{descendants: true}
should be the default but is not in 2.0.0 final and it's considered a bug
This was fixed in 2.0.1
read
If there are a component and directives the read
parameter allows to specify which instance should be returned.
For example ViewContainerRef
that is required by dynamically created components instead of the default ElementRef
@ViewChild('myname', { read: ViewContainerRef }) target;
subscribe changes
Even though view children are only set when ngAfterViewInit()
is called and content children are only set when ngAfterContentInit()
is called, if you want to subscribe to changes of the query result, it should be done in ngOnInit()
https://github.com/angular/angular/issues/9689#issuecomment-229247134
@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;
ngOnInit() {
this.viewChildren.changes.subscribe(changes => console.log(changes));
this.contentChildren.changes.subscribe(changes => console.log(changes));
}
direct DOM access
can only query DOM elements, but not components or directive instances:
export class MyComponent {
constructor(private elRef:ElementRef) {}
ngAfterViewInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
// for transcluded content
ngAfterContentInit() {
var div = this.elRef.nativeElement.querySelector('div');
console.log(div);
}
}
get arbitrary projected content
CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,
However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).
You can read blog from Simon here . He also recommends CSS over Xpath.
If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.
Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better
We just had a similar issue, looks like the user reset his password on Friday and over the weekend and on Monday he kept getting locked out.
Turned out to be he forgot to update his password on his mobile phone.
Very simple you have to just put
\n
where ever you want to break line in your string resource.
For example
String s = my string resource have \n line break here;
I found that pathlib module also supports this.
from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')
As with C, ultimately, everything is passed by value. Unlike C, you can't actually back up and pass the location of a variable, because it doesn't have pointers, just references.
And the references it has are all to objects, not variables. There are several ways of achieving the same result, but they have to be done by hand, not just adding a keyword at either the call or declaration site.
I found a nice third party library which can detect actual encoding: http://glaforge.free.fr/wiki/index.php?wiki=GuessEncoding
I didn't test it extensively but it seems to work.
After you malloc
a node
make sure to set node->next = NULL
.
int addNodeBottom(int val, node *head)
{
node *current = head;
node *newNode = (node *) malloc(sizeof(node));
if (newNode == NULL) {
printf("malloc failed\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
return 0;
}
I should point out that with this version the head
is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just a head
node.
Since dplyr 1.0.0
, the slice_max()
/slice_min()
functions were implemented:
mtcars %>%
group_by(cyl) %>%
slice_max(mpg, n = 2, with_ties = FALSE)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
5 19.2 8 400 175 3.08 3.84 17.0 0 0 3 2
6 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
The documentation on with_ties
parameter:
Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.
The Substring method on the string class has always felt inadequate to me. Usually when you do a substring, you know the character(s) from where you want to start, and the charachter(s) where you want to end. Thus, I've always felt that have to specify length as the second parameter is stupid. Therefore, I've written my own extension methods. One that takes a startIndex and an endIndex. And one, that takes a startText (string) and endText (string) so you can just specify the text from where to start the substring, and the text for where to end it.
NOTE: I couldn't name the method Substring as in .NET because my first overload takes the same parameter types as one of the .NET overloads. Therefore I named them Subsetstring. Feel free to add to the CodePlex...
public static class StringExtensions
{
/// <summary>
/// Returns a Subset string starting at the specified start index and ending and the specified end
/// index.
/// </summary>
/// <param name="s">The string to retrieve the subset from.</param>
/// <param name="startIndex">The specified start index for the subset.</param>
/// <param name="endIndex">The specified end index for the subset.</param>
/// <returns>A Subset string starting at the specified start index and ending and the specified end
/// index.</returns>
public static string Subsetstring(this string s, int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
throw new InvalidOperationException("End Index must be after Start Index.");
}
if (startIndex < 0)
{
throw new InvalidOperationException("Start Index must be a positive number.");
}
if(endIndex <0)
{
throw new InvalidOperationException("End Index must be a positive number.");
}
return s.Substring(startIndex, (endIndex - startIndex));
}
/// <summary>
/// Finds the specified Start Text and the End Text in this string instance, and returns a string
/// containing all the text starting from startText, to the begining of endText. (endText is not
/// included.)
/// </summary>
/// <param name="s">The string to retrieve the subset from.</param>
/// <param name="startText">The Start Text to begin the Subset from.</param>
/// <param name="endText">The End Text to where the Subset goes to.</param>
/// <param name="ignoreCase">Whether or not to ignore case when comparing startText/endText to the string.</param>
/// <returns>A string containing all the text starting from startText, to the begining of endText.</returns>
public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)
{
if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))
{
throw new ArgumentException("Start Text and End Text cannot be empty.");
}
string temp = s;
if (ignoreCase)
{
temp = s.ToUpperInvariant();
startText = startText.ToUpperInvariant();
endText = endText.ToUpperInvariant();
}
int start = temp.IndexOf(startText);
int end = temp.IndexOf(endText, start);
return Subsetstring(s, start, end);
}
}
Usage:
string s = "This is a tester for my cool extension method!!";
s = s.Subsetstring("tester", "cool",true);
Output: "tester for my "
cv:Mat mat;
int rows = mat.rows;
int cols = mat.cols;
cv::Size s = mat.size();
rows = s.height;
cols = s.width;
Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.
Reference to above link i added 1 new thing called show 4 at time, slide one at a time for bootstrap 3 (v3.3.7)
CODEPLY:- https://www.codeply.com/go/eWUbGlspqU
LIVE SNIPPET
(function(){_x000D_
$('#carousel123').carousel({ interval: 2000 });_x000D_
}());_x000D_
_x000D_
(function(){_x000D_
$('.carousel-showmanymoveone .item').each(function(){_x000D_
var itemToClone = $(this);_x000D_
_x000D_
for (var i=1;i<4;i++) {_x000D_
itemToClone = itemToClone.next();_x000D_
_x000D_
// wrap around if at end of item collection_x000D_
if (!itemToClone.length) {_x000D_
itemToClone = $(this).siblings(':first');_x000D_
}_x000D_
_x000D_
// grab item, clone, add marker class, add to collection_x000D_
itemToClone.children(':first-child').clone()_x000D_
.addClass("cloneditem-"+(i))_x000D_
.appendTo($(this));_x000D_
}_x000D_
});_x000D_
}());
_x000D_
body {_x000D_
margin-top: 50px;_x000D_
}_x000D_
_x000D_
.carousel-showmanymoveone .carousel-control {_x000D_
width: 4%;_x000D_
background-image: none;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.left {_x000D_
margin-left: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.right {_x000D_
margin-right: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .cloneditem-1,_x000D_
.carousel-showmanymoveone .cloneditem-2,_x000D_
.carousel-showmanymoveone .cloneditem-3 {_x000D_
display: none;_x000D_
}_x000D_
@media all and (min-width: 768px) {_x000D_
.carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .prev {_x000D_
left: -50%;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .next {_x000D_
left: 50%;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .left,_x000D_
.carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .active {_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner .cloneditem-1 {_x000D_
display: block;_x000D_
}_x000D_
}_x000D_
@media all and (min-width: 768px) and (transform-3d), all and (min-width: 768px) and (-webkit-transform-3d) {_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
-webkit-transform: translate3d(50%, 0, 0);_x000D_
transform: translate3d(50%, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
-webkit-transform: translate3d(-50%, 0, 0);_x000D_
transform: translate3d(-50%, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
-webkit-transform: translate3d(0, 0, 0);_x000D_
transform: translate3d(0, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
}_x000D_
@media all and (min-width: 992px) {_x000D_
.carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .prev {_x000D_
left: -25%;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .next {_x000D_
left: 25%;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .left,_x000D_
.carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .active {_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner .cloneditem-2,_x000D_
.carousel-showmanymoveone .carousel-inner .cloneditem-3 {_x000D_
display: block;_x000D_
}_x000D_
}_x000D_
@media all and (min-width: 992px) and (transform-3d), all and (min-width: 992px) and (-webkit-transform-3d) {_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
-webkit-transform: translate3d(25%, 0, 0);_x000D_
transform: translate3d(25%, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
-webkit-transform: translate3d(-25%, 0, 0);_x000D_
transform: translate3d(-25%, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
.carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
-webkit-transform: translate3d(0, 0, 0);_x000D_
transform: translate3d(0, 0, 0);_x000D_
left: 0;_x000D_
}_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<div class="carousel carousel-showmanymoveone slide" id="carousel123">_x000D_
<div class="carousel-inner">_x000D_
<div class="item active">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&text=1" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&text=2" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/d6d6d6/333&text=3" class="img-responsive"></a></div>_x000D_
</div> _x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002040/eeeeee&text=4" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&text=5" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&text=6" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/eeeeee&text=7" class="img-responsive"></a></div>_x000D_
</div>_x000D_
<div class="item">_x000D_
<div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/40a1ff/002040&text=8" class="img-responsive"></a></div>_x000D_
</div>_x000D_
</div>_x000D_
<a class="left carousel-control" href="#carousel123" data-slide="prev"><i class="glyphicon glyphicon-chevron-left"></i></a>_x000D_
<a class="right carousel-control" href="#carousel123" data-slide="next"><i class="glyphicon glyphicon-chevron-right"></i></a>_x000D_
</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
_x000D_
Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.
In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.
Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!
Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).
Have you compared the table definitions in Prod and Dev?
And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?
If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.
Can you post the definition of the table and your actual Query?
To install pip, securely download get-pip.py.
Then run the following:
python get-pip.py
Be cautious if you're using a Python install that's managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.
Refer: PIP Installation
Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.
1. About onCreate() and onUpgrade()
onCreate(..)
is called whenever the app is freshly installed. onUpgrade
is called whenever the app is upgraded and launched and the database version is not the same.
2. Incrementing the db version
You need a constructor like:
MyOpenHelper(Context context) {
super(context, "dbname", null, 2); // 2 is the database version
}
IMPORTANT: Incrementing the app version alone is not enough for onUpgrade
to be called!
3. Don't forget your new users!
Don't forget to add
database.execSQL(DATABASE_CREATE_color);
to your onCreate() method as well or newly installed apps will lack the table.
4. How to deal with multiple database changes over time
When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion
:
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
db.execSQL(DATABASE_CREATE_color);
// we want both updates, so no break statement here...
case 2:
db.execSQL(DATABASE_CREATE_someothertable);
}
}
This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)
5. Keeping your revision numbers under control while developing
And finally... calling
adb uninstall <yourpackagename>
totally uninstalls the app. When you install again, you are guaranteed to hit onCreate
which keeps you from having to keep incrementing the database version into the stratosphere as you develop...
remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.
Means if a arraylist contains {20,15,30,40}
I have called the method: arraylist.remove(1)
then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.
For this reason you have to delete higher index item of arraylist first.
So..for your given situation..the code will be..
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");
int i[] = {1,3,5};
for (int j = i.length-1; j >= 0; j--) {
list.remove(i[j]);
}
They are completely different. is
checks for object identity, while ==
checks for equality (a notion that depends on the two operands' types).
It is only a lucky coincidence that "is
" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.
For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:
>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.
CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = @"Tap to Edit";
[textField addSubview:tapEditLbl];
I found UriBuilder
worked really well for this sort of thing:
UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
Uri url = urlb.Uri;
return url.AbsoluteUri;
See UriBuilder Class - MSDN for more constructors and documentation.
Easiest way:
Check in your logcat window - TOP RIGHT corner PAUSE button || (Pause receiving new logcat messages)
Few clicks + eventually restart eclipse (usually works in my case)
You shouldn't be using onClick
any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick
function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick=""
from the <a>
element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using
onclick = function() { return eval(js); }
doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})");
will wrap the 'js' variable in a function enclosure. onclick = new Function(js);
works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function()
constructors
A speed-optimized version:
function escapeHtml(s) {
let out = "";
let p2 = 0;
for (let p = 0; p < s.length; p++) {
let r;
switch (s.charCodeAt(p)) {
case 34: r = """; break; // "
case 38: r = "&" ; break; // &
case 39: r = "'" ; break; // '
case 60: r = '<' ; break; // <
case 62: r = '>' ; break; // >
default: continue;
}
if (p2 < p) {
out += s.substring(p2, p);
}
out += r;
p2 = p + 1;
}
if (p2 == 0) {
return s;
}
if (p2 < s.length) {
out += s.substring(p2);
}
return out;
}
const s = "Hello <World>!";
document.write(escapeHtml(s));
console.log(escapeHtml(s));
_x000D_
Initialize empty frame with column names
import pandas as pd
col_names = ['A', 'B', 'C']
my_df = pd.DataFrame(columns = col_names)
my_df
Add a new record to a frame
my_df.loc[len(my_df)] = [2, 4, 5]
You also might want to pass a dictionary:
my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic
Append another frame to your existing frame
col_names = ['A', 'B', 'C']
my_df2 = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)
Performance considerations
If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.
If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.
For Android Studion version 3.3.2
1) I updated the gradle distribution URL to distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip in gradle-wrapper.properties file
2) Within the top-level build.gradle file updated the gradle plugin to version 3.3.2
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.2.0'
}
I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.
Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible
MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
}
}
Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState();
createdStateInDestroyView = true;
myObject = null;
}
This part would be the same.
private Bundle saveState() {
Bundle state = new Bundle();
state.putSerializable(SAVED_BUNDLE_TAG, myObject);
return state;
}
Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.
@Override
public void onSaveInstanceState(Bundle outState) {
if (myObject == null) {
outState.putBundle(SAVED_BUNDLE_TAG, savedState);
} else {
outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
}
createdStateInDestroyView = false;
super.onSaveInstanceState(outState);
}
Now wherever you want to restore the state just use the savedState bundle
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
if(savedState != null) {
myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
}
...
}
There's now an EMPTY
constant and an empty
function.
import { Observable, empty, of } from 'rxjs';
var delay = empty().pipe(delay(1000));
var delay2 = EMPTY.pipe(delay(1000));
Observable.empty()
doesn't exist anymore.
You can use a css3 psuedo element (:before
and/or :after
) as shown in this article
https://www.exratione.com/2011/09/how-to-overflow-a-background-image-using-css3/
Good Luck...
Sooner or later you will have property with special character. You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
If you are already in an Angular project you could use $filter('date')
.
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:
class Point {
constructor(public x: number, public y: number) {
throw new Error('cannot instantiate using a static class');
}
public distance(p: Point) {
var dx = this.x - p.x;
var dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
static origin = new Point(0, 0);
static distance(p1: Point, p2: Point) {
return p1.distance(p2);
}
}
where Point.distance()
is a static (or "class") method.
On a single line...
pgrep -f process_name | xargs kill -9
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
It's depends on if your computer support WMI
. My computer can't run this WMI demo too.
But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
class Program
{
public class UpdateVisitor : IVisitor
{
public void VisitComputer(IComputer computer)
{
computer.Traverse(this);
}
public void VisitHardware(IHardware hardware)
{
hardware.Update();
foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
}
public void VisitSensor(ISensor sensor) { }
public void VisitParameter(IParameter parameter) { }
}
static void GetSystemInfo()
{
UpdateVisitor updateVisitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(updateVisitor);
for (int i = 0; i < computer.Hardware.Length; i++)
{
if (computer.Hardware[i].HardwareType == HardwareType.CPU)
{
for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
{
if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
}
}
}
computer.Close();
}
static void Main(string[] args)
{
while (true)
{
GetSystemInfo();
}
}
}
}
You need to run this demo as administrator.
You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html
As a fallback there's always od -xc filename
Following is how you can do it using java client.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;
public class AmazonS3Service {
private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
private static final String S3_SECRET_KEY = "SECRET_KEY";
private static final String S3_ENDPOINT = "S3_URL";
private AmazonS3 amazonS3;
public AmazonS3Service() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProtocol(Protocol.HTTPS);
clientConfiguration.setSignerOverride("S3SignerType");
BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
.withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
}
public int countObjects(String bucketName) {
int count = 0;
ObjectListing objectListing = amazonS3.listObjects(bucketName);
int currentBatchCount = objectListing.getObjectSummaries().size();
while (currentBatchCount != 0) {
count += currentBatchCount;
objectListing = amazonS3.listNextBatchOfObjects(objectListing);
currentBatchCount = objectListing.getObjectSummaries().size();
}
return count;
}
}
I think, below procedure help you to what you are looking for.
CREATE PROCEDURE [dbo].[FindEmployeeRecord]
@EmployeeID nvarchar(Max)
AS
BEGIN
DECLARE @sqLQuery VARCHAR(MAX)
Declare @AnswersTempTable Table
(
EmpId int,
EmployeeName nvarchar (250),
EmployeeAddress nvarchar (250),
PostalCode nvarchar (50),
TelephoneNo nvarchar (50),
Email nvarchar (250),
status nvarchar (50),
Sex nvarchar (50)
)
Set @sqlQuery =
'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
from Employee e
join EmployeeDetail ed on e.Empid = ed.iEmpID
where Convert(nvarchar(Max),e.EmpId) in ('+@EmployeeId+')
order by EmpId'
Insert into @AnswersTempTable
exec (@sqlQuery)
select * from @AnswersTempTable
END
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
I converted the VB code in the blog post linked by xsl to C# and modified it a bit:
public static bool TryGetRegisteredApplication(
string extension, out string registeredApp)
{
string extensionId = GetClassesRootKeyDefaultValue(extension);
if (extensionId == null)
{
registeredApp = null;
return false;
}
string openCommand = GetClassesRootKeyDefaultValue(
Path.Combine(new[] {extensionId, "shell", "open", "command"}));
if (openCommand == null)
{
registeredApp = null;
return false;
}
registeredApp = openCommand
.Replace("%1", string.Empty)
.Replace("\"", string.Empty)
.Trim();
return true;
}
private static string GetClassesRootKeyDefaultValue(string keyPath)
{
using (var key = Registry.ClassesRoot.OpenSubKey(keyPath))
{
if (key == null)
{
return null;
}
var defaultValue = key.GetValue(null);
if (defaultValue == null)
{
return null;
}
return defaultValue.ToString();
}
}
EDIT - this is unreliable. See Finding the default application for opening a particular file type on Windows.
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
//output
a: 1
b: 2
The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:
if(defined('E_STRICT')){
error_reporting(E_ALL);
}
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).The response is a bit late - but in case anyone has the issue in the future...
From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.
Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data
There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.
I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.
Edit:
After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.
GMTL -
Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.
Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.
Eigen -
Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.
Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).
IMSL -
Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.
Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.
NT2 -
Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.
Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.
LAPACK -
Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.
Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.
Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.
SELECT 'Free &' || ' Clear' FROM DUAL;
Some of it is possible, specifically accessing subtotals:
"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)
Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/
"""
merge_image takes three parameters first two parameters specify
the two images to be merged and third parameter i.e. vertically
is a boolean type which if True merges images vertically
and finally saves and returns the file_name
"""
def merge_image(img1, img2, vertically):
images = list(map(Image.open, [img1, img2]))
widths, heights = zip(*(i.size for i in images))
if vertically:
max_width = max(widths)
total_height = sum(heights)
new_im = Image.new('RGB', (max_width, total_height))
y_offset = 0
for im in images:
new_im.paste(im, (0, y_offset))
y_offset += im.size[1]
else:
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset, 0))
x_offset += im.size[0]
new_im.save('test.jpg')
return 'test.jpg'
I would recommend you to reset all the HTML elements before writing your css with:
* {
margin: 0;
padding: 0;
}
After that, you can write your custom css, without any problems.
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
Have you considered applying ON DELETE CASCADE
where relevant?
If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.
For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another.
void* p;
says p is a memory address, but I don't know what's in the memorychar* s;
says s is a memory address, and the first byte contains a characterchar** ps;
says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.cf http://www.oberon2005.ru/paper/kr_c.pdf (e-book version of K&R)
In responsive.less, you can comment out the line that imports responsive-1200px-min.less.
// Large desktops
@import "responsive-1200px-min.less";
Like so:
// Large desktops
// @import "responsive-1200px-min.less";
Use the following Code :
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[1];//coz 0th will be getStackTrace so 1st
String methodName = e.getMethodName();
System.out.println(methodName);
The simplest way is to use str directly on column names, there is no need for pd.Series
df.loc[:,df.columns.str.startswith("foo")]
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
GET takes name value pairs.
Try something like:
curl http://server:5050/a/c/getName/?param1=pradeep
or
curl http://server:5050/a/c/getName?param1=pradeep
btw a regular REST should look something like
curl http://server:5050/a/c/getName/pradeep
If it takes JSON in GET URL, it's not a standard way.
With regards to JSR-310 another project of interest might be threetenbp.
JSR-310 provides a new date and time library for Java SE 8. This project is the backport to Java SE 6 and 7.
In case you are working on an Android project you might want to checkout the ThreeTenABP library.
compile "com.jakewharton.threetenabp:threetenabp:${version}"
JSR-310 was included in Java 8 as the java.time.* package. It is a full replacement for the ailing Date and Calendar APIs in both Java and Android. JSR-310 was backported to Java 6 by its creator, Stephen Colebourne, from which this library is adapted.
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print output_file.read()
In that code, I want to read the file, but I use mode wb
instead of r
or r+
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
Hey I have answered this question here. Basically, you need to override
public Object instantiateItem(ViewGroup container, int position)
method of FragmentStatePagerAdapter.
I ran into the same issue today when trying to use a pod written in Objective-C in my Swift project, none of the above solutions seemed to work.
In the podfile I had use_frameworks!
written. Commenting this line and then running pod install
again solved this issue for me and the error went away.
Use Either Debug.WriteLine()
or Trace.WriteLine()
. If in release mode, only the latter will appear in the output window, in debug mode, both will.
If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.
In fact, it's a very old thread but useful...
When namespace declaration is part of your php class file "this kind of weird errors tends to appear".
Solution: Use namespace
with {
, your code shows like this:
<?php
namespace path_to\lib {
require_once "folder/php_class_file_where_namespace_declaration_is_part_of_it.php";
**YOUR CODE HERE**
<?php } ?>
To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.
In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline
would not work.
I was just having the same issue and suggest you use Jupyter Notebook for the visualization.
To answer the question : if you want to exclude certain files of a checkout, you can use sparse-checkout
In .git/info/sparse-checkout
, define what you want to keep. Here, we want all (*) but (note the exclamation mark) config.php :
/* !/config.php
Tell git you want to take sparse-checkout into account
git config core.sparseCheckout true
If you already have got this file locally, do what git does on a sparse checkout (tell it it must exclude this file by setting the "skip-worktree" flag on it)
git update-index --skip-worktree config.php
Enjoy a repository where your config.php file is yours - whatever changes are on the repository.
Please note that configuration values SHOULDN'T be in source control :
- It is a potential security breach
- It causes problems like this one for deployment
This means you MUST exclude them (put them in .gitignore before first commit), and create the appropriate file on each instance where you checkout your app (by copying and adapting a "template" file)
Note that, once a file is taken in charge by git, .gitignore won't have any effect.
Given that, once the file is under source control, you only have two choices () :
rebase all your history to remove the file (with git filter-branch
)
create a commit that removes the file. It is like fighting a loosing battle, but, well, sometimes you have to live with that.
Reason is some un-wanted characters was added when you compose the String. The temp solution is
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
But try to remove hidden characters on source String.
With
git config -l
, I now see I have acredential.helper=osxkeychain
option
That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")
You can disable that option entirely, or only for a single repo.
React Native Docs gives the answer for this.
Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
Pool
performance
[By re using same object's to perform any action on Object-Data] & memory
[allocating and de-allocating many objects creates a significant memory management overhead].« Pooling [ Object
pool, String
Constant Pool, Thread
Pool, Connection pool]
String Constant pool
Example: String to verify Unique Object from pool.
public class StringPoolTest {
public static void main(String[] args) { // Integer.valueOf(), String.equals()
String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();
String s1 = "Yash".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
String s2 = "Yas"+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
String s3 = "Yas".intern()+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
String s4 = "Yas"+"h";
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
}
}
Connection pool using Type-4 Driver using 3rd party libraries[ DBCP2
, c3p0
, Tomcat JDBC
]
Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora].
wiki
In Connection pool mechanism, when the class is loaded it get's the physical JDBC connection
objects and provides a wrapped physical connection object to user. PoolableConnection
is a wrapper around the actual connection.
getConnection()
pick one of the free wrapped-connection form the connection objectpool and returns it.close()
instead of closing it returns the wrapped-connection back to pool.Example: Using ~ DBCP2 Connection Pool with Java 7[try-with-resources
]
public class ConnectionPool {
static final BasicDataSource ds_dbcp2 = new BasicDataSource();
static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
static final DataSource ds_JDBC = new DataSource();
static Properties prop = new Properties();
static {
try {
prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));
ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
ds_dbcp2.setUrl( prop.getProperty("URL") );
ds_dbcp2.setUsername( prop.getProperty("UserName") );
ds_dbcp2.setPassword( prop.getProperty("Password") );
ds_dbcp2.setInitialSize( 5 );
ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
ds_c3p0.setUser( prop.getProperty("UserName") );
ds_c3p0.setPassword( prop.getProperty("Password") );
ds_c3p0.setMinPoolSize(5);
ds_c3p0.setAcquireIncrement(5);
ds_c3p0.setMaxPoolSize(20);
PoolProperties pool = new PoolProperties();
pool.setUrl( prop.getProperty("URL") );
pool.setDriverClassName( prop.getProperty("DriverClass") );
pool.setUsername( prop.getProperty("UserName") );
pool.setPassword( prop.getProperty("Password") );
pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)
pool.setInitialSize(5);
pool.setMaxActive(3);
ds_JDBC.setPoolProperties( pool );
} catch (IOException e) { e.printStackTrace();
} catch (PropertyVetoException e) { e.printStackTrace(); }
}
public static Connection getDBCP2Connection() throws SQLException {
return ds_dbcp2.getConnection();
}
public static Connection getc3p0Connection() throws SQLException {
return ds_c3p0.getConnection();
}
public static Connection getJDBCConnection() throws SQLException {
return ds_JDBC.getConnection();
}
}
public static boolean exists(String UserName, String Password ) throws SQLException {
boolean exist = false;
String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
try ( Connection connection = ConnectionPool.getDBCP2Connection();
PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
pstmt.setString(1, UserName );
pstmt.setString(2, Password );
try (ResultSet resultSet = pstmt.executeQuery()) {
exist = resultSet.next(); // Note that you should not return a ResultSet here.
}
}
System.out.println("User : "+exist);
return exist;
}
jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName>
jdbc:
oracle
:thin:@localhost:1521:myDBName
jdbc:
mysql
://localhost:3306/myDBName
connectionpool.properties
URL : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName : root
Password :
Web Application: To avoid connection problem when all the connection's are closed[MySQL "wait_timeout" default 8 hours] in-order to reopen the connection with underlying DB.
You can do this to Test Every Connection by setting testOnBorrow = true and validationQuery= "SELECT 1" and donot use autoReconnect for MySQL server as it is deprecated. issue
===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
<Resource name="jdbc/MyAppDB" auth="Container"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
type="javax.sql.DataSource"
initialSize="5" minIdle="5" maxActive="15" maxIdle="10"
testWhileIdle="true"
timeBetweenEvictionRunsMillis="30000"
testOnBorrow="true"
validationQuery="SELECT 1"
validationInterval="30000"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/myDBName"
username="yash" password="777"
/>
</Context>
===== ===== web.xml ===== =====
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyAppDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet « init() {}
Normal call used by sevlet « static {}
static DataSource ds;
static {
try {
Context ctx=new InitialContext();
Context envContext = (Context)ctx.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/MyAppDB");
} catch (NamingException e) { e.printStackTrace(); }
}
See these also:
You can use str_pad
for adding 0's
str_pad($month, 2, '0', STR_PAD_LEFT);
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
for x in y[:-1]
If y
is a generator, then the above will not work.
Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.
To change the priority of the connections:
Below code works for me :
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
If I am understanding your question correctly, you want the safest way to determine if an object contains a property.
The easiest way is to use the in
operator.
window.a = "aString";
//window should have 'a' property
//lets test if it exists
if ("a" in window){
//true
}
if ("b" in window){
//false
}
Of course you can nest this as deep as you want
if ("a" in window.b.c) { }
Not sure if this helps.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
git config user.name
git config user.email
I believe these are the commands you are looking for.
Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address
use dnsmasq
pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with
(sudo) systemctl status dnsmasq
If it is just disabled start it with
(sudo) systemctl start dnsmasq
If you have to install it, write
(sudo) apt-get install dnsmasq
To define domains to resolve edit /etc/dnsmasq.conf
like this
address=/example.com/127.0.0.1
to resolve *.example.com
! You need to reload dnsmasq to take effect for the changes !
systemctl reload dnsmasq
(Adding response on old q as this is the top result on google)
I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.
However, what did work was...
await Future.delayed(const Duration(milliseconds: 500));
yield newState;
Awaiting an empty future then running the function afterwards.
It is not a valid answer as it gives following error
Cannot find table 0.
Use the following statement instead
if (ds.Tables.Count == 0)
{
//DataSet is empty
}
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location
service, as injected in your own service or controller:
var paramValue = $location.search().myParam;
This simple syntax will work for http://example.com/path?myParam=paramValue
. However, only if you configured the $locationProvider
in the HTML 5 mode before:
$locationProvider.html5Mode(true);
Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.
Use JSON.stringify()
and JSON.parse()
as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars
).
you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.
Then you controller is probably like this:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
@RequestParam Map<String, String> name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
...
PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
...
list = service.getPatient(patientProfileDto);
return list;
}
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer
element.getBoundingClientRect()
is an exact match to jQuery's $(element).offset()
And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
From http://www.rueckstiess.net/research/snippets/show/ca1d7d90 and http://qingkaikong.blogspot.com/2016/12/python-parallel-method-in-class.html
We can make an external function and seed it with the class self object:
from joblib import Parallel, delayed
def unwrap_self(arg, **kwarg):
return square_class.square_int(*arg, **kwarg)
class square_class:
def square_int(self, i):
return i * i
def run(self, num):
results = []
results = Parallel(n_jobs= -1, backend="threading")\
(delayed(unwrap_self)(i) for i in zip([self]*len(num), num))
print(results)
OR without joblib:
from multiprocessing import Pool
import time
def unwrap_self_f(arg, **kwarg):
return C.f(*arg, **kwarg)
class C:
def f(self, name):
print 'hello %s,'%name
time.sleep(5)
print 'nice to meet you.'
def run(self):
pool = Pool(processes=2)
names = ('frank', 'justin', 'osi', 'thomas')
pool.map(unwrap_self_f, zip([self]*len(names), names))
if __name__ == '__main__':
c = C()
c.run()
I have a similar problem, I tested adding code and found some interesting results. With this code I add, I can deduce that depending on the "provider" to use, the firm can be different? (because the data included in the encryption is not always equal in all providers).
Conclusion.- Signature Decipher= ???(trash) + DigestInfo (if we know the value of "trash", the digital signatures will be equal)
Input data: This is the message being signed
Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
DigestInfo: 3021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
Signature Decipher: 1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class prueba {
/**
* @param args
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*///
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
KeyPair keyPair = KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey puKey = keyPair.getPublic();
String plaintext = "This is the message being signed";
// Hacer la firma
Signature instance = Signature.getInstance("SHA1withRSA","BC");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// En dos partes primero hago un Hash
MessageDigest digest = MessageDigest.getInstance("SHA1", "BC");
byte[] hash = digest.digest((plaintext).getBytes());
// El digest es identico a openssl dgst -sha1 texto.txt
//MessageDigest sha1 = MessageDigest.getInstance("SHA1","BC");
//byte[] digest = sha1.digest((plaintext).getBytes());
AlgorithmIdentifier digestAlgorithm = new AlgorithmIdentifier(new
DERObjectIdentifier("1.3.14.3.2.26"), null);
// create the digest info
DigestInfo di = new DigestInfo(digestAlgorithm, hash);
byte[] digestInfo = di.getDEREncoded();
//Luego cifro el hash
Cipher cipher = Cipher.getInstance("RSA","BC");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digestInfo);
//byte[] cipherText = cipher.doFinal(digest2);
Cipher cipher2 = Cipher.getInstance("RSA","BC");
cipher2.init(Cipher.DECRYPT_MODE, puKey);
byte[] cipherText2 = cipher2.doFinal(signature);
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(hash));
System.out.println("Signature: " + bytes2String(signature));
System.out.println("Signature2: " + bytes2String(cipherText));
System.out.println("DigestInfo: " + bytes2String(digestInfo));
System.out.println("Signature Decipher: " + bytes2String(cipherText2));
}
It's also possible to use jQuery's .load()
$('#submitform').click(function() {
$('#showresults').load('getinfo.asp #showresults', {
txtsearch: $('#appendedInputButton').val()
}, function() {
// alert('Load was performed.')
// $('#showresults').slideDown('slow')
});
});
unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
Make sure you're in the right directory (repository main folder) in your local git so it can find .git folder configuration before you commit or add files.
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
You could use a ArrayList instead of array. So that you can add n number of elements
List<Integer> myVar = new ArrayList<Integer>();
Have you installed Fiddler2?
It will let you see exactly what is being requested, what is being sent back, etc. It doesn't sound plausible that the browser would really hit its cache for different URLs.
enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.
In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg
Have you given a try to Webkit Filters?
You can manipulate not only opacity, but colour, brightness, luminosity and other properties:
You can take a look also at C++ Builder XE6, and XE7 supports android in c++ code, and with Firemonkey library.
http://www.embarcadero.com/products/cbuilder
Pretty easy way to start, and native code. But the binaries have a big size.
Check your npm
version
If it's not properly installed, then install it first
run this command npm install typescript -g
now tsc <file_name>.ts
It'll create a corresponding .js
file. eg <file_name>.js
now try node <file_name>.js
Considering the post JSX In Depth, you can solve your problem this way:
if (isRequired) {
return (
<MyOwnInput name="test" required='required' />
);
}
return (
<MyOwnInput name="test" />
);
simple you want to inialize a 2d array and assign a size of array then a example is
public static void main(String args[])
{
char arr[][]; //arr is 2d array name
arr = new char[3][3];
}
//this is a way to inialize a 2d array in java....
First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:
public function win_os(){
ob_start();
system('ipconfig-a');
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
$pmac = strpos($mycom, $findme); // Find the position of Physical text
$mac=substr($mycom,($pmac+36),17); // Get Physical Address
return $mac;
}
And your OS Linux Ubuntu or Linux then this code use:
public function unix_os(){
ob_start();
system('ifconfig -a');
$mycom = ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
//Find the position of Physical text
$pmac = strpos($mycom, $findme);
$mac = substr($mycom, ($pmac + 37), 18);
return $mac;
}
This code may be work OS X.
It was suggested by Mark Mishyn to use slice but there is no reason to create array with make
and use in for
returned slice of it when array created via literal can be used and it's shorter
for i := range [5]int{} {
fmt.Println(i)
}
your fadeIn()
function calls the fadeOut()
function, which calls the fadeIn()
function again. the recursion is in the JS.
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal
one to accept traffic from anywhere since creating new rules didn't make any difference.
To add on to the answers above, here is a code sample
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
This would give a compilation error:
Error 12 Cannot convert null to 'Test' because it is a non-nullable value type
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
<<~TEXT
Hi #{user.name},
Thanks for raising the flag, we're always happy to help you.
Your issue will be resolved within 2 hours.
Please be patient!
Thanks again,
Team #{user.organization.name}
TEXT
Theres a difference in <<-TEXT
and <<~TEXT
, former retains the spacing inside block and latter doesn't.
There are other options as well. Like concatenation etc. but this one makes more sense in general.
If I am wrong here, let me know how...
ng-model
and ng-checked
directives should not be used togetherFrom the Docs:
ngChecked
Sets the checked attribute on the element, if the expression inside
ngChecked
is truthy.Note that this directive should not be used together with
ngModel
, as this can lead to unexpected behavior.
Instead set the desired initial value from the controller:
<input type="checkbox" name="test" ng-model="testModel['item1']" ?n?g?-?c?h?e?c?k?e?d?=?"?t?r?u?e?"? />
Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };
There are 3 things you need.
You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)
You need the access token (which you get returned in the URL box after the oAuth is done.)
When those are complete you can then access the photos like so https://graph.facebook.com/me?access_token=ACCESS_TOKEN
You can find all of the information in more detail here: http://developers.facebook.com/docs/authentication
forever module has a concept of multiple node.js servers, and can start, restart, stop and list currently running servers. It can also watch for changing files and restart node as needed.
Install it if you don't have it already:
npm install forever -g
After installing it, call the forever
command: use the -w
flag to watch file for changes:
forever -w ./my-script.js
In addition, you can watch directory and ignore patterns:
forever --watch --watchDirectory ./path/to/dir --watchIgnore *.log ./start/file
Have you had a look at $routeProvider.when('/path',{ resolve:{...}
? It can make the promise approach a bit cleaner:
Expose a promise in your service:
app.service('MyService', function($http) {
var myData = null;
var promise = $http.get('data.json').success(function (data) {
myData = data;
});
return {
promise:promise,
setData: function (data) {
myData = data;
},
doStuff: function () {
return myData;//.getSomeData();
}
};
});
Add resolve
to your route config:
app.config(function($routeProvider){
$routeProvider
.when('/',{controller:'MainCtrl',
template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
resolve:{
'MyServiceData':function(MyService){
// MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
return MyService.promise;
}
}})
}):
Your controller won't get instantiated before all dependencies are resolved:
app.controller('MainCtrl', function($scope,MyService) {
console.log('Promise is now resolved: '+MyService.doStuff().data)
$scope.data = MyService.doStuff();
});
I've made an example at plnkr: http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
Simple solution
{{ orderTotal | number : '1.2-2'}}
//output like this
// public orderTotal = 220.45892221
// {{ orderTotal | number : '1.2-2'}}
// final Output
// 220.45
In Eclipse 3.3:
It's installed under your Eclipse workspace. Something like:
.metadata\.plugins\org.eclipse.core.resources\.projects\
within your workspace folder.
Under that folder is one folder per project. There's a file in there called .location, but it's binary.
So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.
Just change the routeReuseStrategy from the angular Router:
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
Set the routerproperty "navigated" to false:
this._router.navigated = false;
Then navigate to your component:
this._router.navigate(['routeToYourComponent'])
After that reinstate the old/default routeReuseStrategy:
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
You can also make a service out of this:
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
print '\033[1m Your Name \033[0m'
\033[1m is the unicode for bold in the terminal \033[0m is the unicode for end the edited text and back default text formate!!!!!
if you do not use \033[0m than all upcoming text of the terminal will become bold!!!!!!!!!
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
float percent = (n / (v * 1.0f)) *100
If your <input>
or <textarea>
has attribute id=mytext
then use
mytext.focus();
function setFocusToTextBox() {_x000D_
mytext.focus();_x000D_
}
_x000D_
<body onload='setFocusToTextBox()'>_x000D_
<form>_x000D_
<input type="text" id="mytext"/>_x000D_
</form>_x000D_
</body>
_x000D_
First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the while loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...
You may also use goto in the following way (using an April Fools module from here):
#import the stuff
from goto import goto, label
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": goto .breakall
if ok == "n" or ok == "N": break
#do more processing with menus and stuff
label .breakall
I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.
Solution using 32 bit display mask,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110
If you are working in ROOT, you do not even have to write #include<iostream>
and using namespace std;
simply start from int filename()
.
This will solve the issue.
Try:
if haystackstr.lower().find(needlestr.lower()) != -1:
# True
well looking for a simpler variation I found this:
it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.
demo and credit => http://codepen.io/Ahrengot/pen/bKdLC
@keyframes fadeIn { _x000D_
from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
So this is the way I had to do it because i still wanted a JavaScript date object to manipulate as a date and unfortunantly alot of these answers require you to go to a string.
//First i had a string called stringDateVar that i needed to convert to Date
var newDate = new Date(stringDateVar)
//output: 2019-01-07T04:00:00.000Z
//I needed it 2019-01-07T00:00:00.000Z because i had other logic that was dependent on that
var correctDate = new Date(newDate.setUTCHours(0))
//This will output 2019-01-07T00:00:00.000Z on everything which allows scalability
I tend to prefer passing a URL to psql:
psql "postgresql://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"
This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.
This requires libpq
. The documentation can be found here.
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
With argc
(argument count) and argv
(argument vector) you can get the number and the values of passed arguments when your application has been launched.
This way you can use parameters (such as -version
) when your application is started to act a different way.
But you can also use int main(void)
as a prototype in C.
There is a third (less known and nonstandard) prototype with a third argument which is envp
. It contains environment variables.
Resources:
String[] parts = text.split(".");
int occurances = parts.length - 1;
" It's a great day at O.S.G. Dallas! "
-- Famous Last Words
Well, it's a case of knowing your Java, especially your basic foundational understanding of the collection classes already available in Java. If you look throughout the entire posting here, there is just about everything short of Stephen Hawking's explanation of the Origin of the Universe, Darwin's paperback on Evolution and Gene Roddenberry's Star Trek cast selection as to why they went with William Shatner short of how to do this quickly and easily...
... need I say anymore?
To make your formula more readable, you could assign a Name to cell A0, and then use that name in the formula.
The easiest way to define a Name is to highlight the cell or range, then click on the Name box in the formula bar.
Then, if you named A0 "Rate" you can use that name like this:
=(B0+4)/(Rate)
See, much easier to read.
If you want to find Rate, click F5 and it appears in the GoTo list.
Using jsonpickle
import jsonpickle
object = YourClass()
json_object = jsonpickle.encode(object)
Try this: sudo systemctl start mongod
and to check whether its running use sudo systemctl status mongod
Emp class needs to implement Comaparable interface so we need to Override its compateTo method.
import java.util.ArrayList;
import java.util.Collections;
class Emp implements Comparable< Emp >{
int empid;
String name;
Emp(int empid,String name){
this.empid = empid;
this.name = name;
}
@Override
public String toString(){
return empid+" "+name;
}
@Override
public int compareTo(Emp o) {
if(this.empid==o.empid){
return 0;
}
else if(this.empid < o.empid){
return 1;
}
else{
return -1;
}
}
}
public class JavaApplication1 {
public static void main(String[] args) {
ArrayList<Emp> a= new ArrayList<Emp>();
a.add(new Emp(10,"Mahadev"));
a.add(new Emp(50,"Ashish"));
a.add(new Emp(40,"Amit"));
Collections.sort(a);
for(Emp id:a){
System.out.println(id);
}
}
}
//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
You can check the total number of arguments which are passed in command line with "$#
"
Say for Example my shell script name is hello.sh
sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument
if [ $# -eq 1 ]
then
echo $1
else
echo "invalid argument please pass only one argument "
fi
Output will be hello-world
Using angular, You can do this to restrict to enter e,+,-,E
<input type="number" (keypress)="numericOnly($event)"/>
numericOnly(event): boolean { // restrict e,+,-,E characters in input type number
debugger
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode == 101 || charCode == 69 || charCode == 45 || charCode == 43) {
return false;
}
return true;
}
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
Mozila Firefox says that onreadystatechange
is an alternative to DOMContentLoaded
.
// alternative to DOMContentLoaded
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
In DOMContentLoaded
the Mozila's doc says:
The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).
I think load
event should be used for a full document+resources loading.
you can retrieve value like this
string str = (string)(range.Cells[row, col] as Excel.Range).Value2 ;
select entire used range
Excel.Range range = xlWorkSheet.UsedRange;
source :
http://csharp.net-informations.com/excel/csharp-read-excel.htm
flaming
You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/
(very rough example)
#!/usr/bin/expect
set pass "mysecret"
spawn /usr/bin/passwd
expect "password: "
send "$pass"
expect "password: "
send "$pass"
There is a php library (pdfparser) that does exactly what you want.
project website
github
https://github.com/smalot/pdfparser
Demo page/api
After including pdfparser in your project you can get all text from mypdf.pdf
like so:
<?php
$parser = new \installpath\PdfParser\Parser();
$pdf = $parser->parseFile('mypdf.pdf');
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf
?>
Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).
To check input type
<!DOCTYPE html>
<html>
<body>
<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>
<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>
</body>
</html>
Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:
if ("A C Viking G M Ocelot".contains(mAnswer)) {...}
for numbers it's a tad more involved but still works:
if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...}
To get more information about tensorflow and its options you can use below command:
>> import tensorflow as tf
>> help(tf)