Only few steps. We can download or generate PDF from our HTML page or we can generate PDF of specific div from a HTML page.
Steps : HTML -> Image (PNG or JPEG) -> PDF
Please Follow the below steps,
Step 1 :-
npm install --save html-to-image
npm install jspdf --save
Step 2 :-
/* ES6 */
import * as htmlToImage from 'html-to-image';
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
/* ES5 */
var htmlToImage = require('html-to-image');
-------------------------
import { jsPDF } from "jspdf";
Step 3 :-
****** With out PDF properties given below ******
htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.jpeg';
const pdf = new jsPDF();
pdf.addImage(dataUrl, 'PNG', 0, 0);
pdf.save("download.pdf");
});
****** With PDF properties given below ******
htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.jpeg';
const pdf = new jsPDF();
const imgProps= pdf.getImageProperties(dataUrl);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(dataUrl, 'PNG', 0, 0,pdfWidth, pdfHeight);
pdf.save("download.pdf");
});
I think this is helpful. Please try
If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.
To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK
From there on you can simply build/debug your solution. Hope it helps
Do what the compiler tells you to do, i.e. recompile with -fPIC
. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.
In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.
Finally, you can read about it on Wikipedia too.
I suspect GCC (mingw) has custom code to disable the checks for the wide printf
functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s
and %ls
backwards for the wide printf
functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.
To install the GPL version of PyQt5, run (see PyQt5 Project):
pip3 install pyqt5
This will install the Python wheel for your platform and your version of Python (assuming both are supported).
(The wheel will be automatically downloaded from the Python Package Index.)
The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.
(The required sip
is packaged as a separate wheel and will be downloaded and installed automatically.)
Note:
If you get an error message saying something as
No downloads could be found that satisfy the requirement
then you are probably using an unsupported version of Python.
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
Ultimately, this is completely platform-dependent. Unicode-support is, unfortunately, very poor in Standard C++. For GCC, you will have to make it a narrow string, as they use UTF-8, and Windows wants a wide string, and you must output to wcout
.
// GCC
std::cout << "?";
// Windoze
wcout << L"?";
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");
Use the global(g
) flag
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you. If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.
const char* text_char = "example of mbstowcs";
size_t length = strlen(text_char );
Example of usage "mbstowcs"
std::wstring text_wchar(length, L'#');
//#pragma warning (disable : 4996)
// Or add to the preprocessor: _CRT_SECURE_NO_WARNINGS
mbstowcs(&text_wchar[0], text_char , length);
Example of usage "mbstowcs_s"
Microsoft suggest to use "mbstowcs_s" instead of "mbstowcs".
Links:
wchar_t text_wchar[30];
mbstowcs_s(&length, text_wchar, text_char, length);
It always bothered me that I can't use the String.Remove
method to get rid of instances of a string or character in a string so I usually add theses extension methods to my code base:
public static class StringExtensions
{
public static string Remove(this string str, string toBeRemoved)
{
return str.Replace(toBeRemoved, "");
}
public static string RemoveChar(this string str, char toBeRemoved)
{
return str.Replace(toBeRemoved.ToString(), "");
}
}
The one taking char
can't use overload semantics unfortunately since it will resolve to string.Remove(int startIndex)
since it is "closer"
This is of course purely esthetics, but I like it...
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
wxWidgets has a very rich string API wxString
it can be done with (using the case conversion way)
int Contains(const wxString& SpecProgramName, const wxString& str)
{
wxString SpecProgramName_ = SpecProgramName.Upper();
wxString str_ = str.Upper();
int found = SpecProgramName.Find(str_);
if (wxNOT_FOUND == found)
{
return 0;
}
return 1;
}
Here's another way of doing it, remember to use free() on the result.
char* wchar_to_char(const wchar_t* pwchar)
{
// get the number of characters in the string.
int currentCharIndex = 0;
char currentChar = pwchar[currentCharIndex];
while (currentChar != '\0')
{
currentCharIndex++;
currentChar = pwchar[currentCharIndex];
}
const int charCount = currentCharIndex + 1;
// allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
char* filePathC = (char*)malloc(sizeof(char) * charCount);
for (int i = 0; i < charCount; i++)
{
// convert to char (1 byte)
char character = pwchar[i];
*filePathC = character;
filePathC += sizeof(char);
}
filePathC += '\0';
filePathC -= (sizeof(char) * charCount);
return filePathC;
}
int StringToWString(std::wstring &ws, const std::string &s)
{
std::wstring wsTmp(s.begin(), s.end());
ws = wsTmp;
return 0;
}
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
If you have a std::wstring object, you can call c_str()
on it to get a wchar_t*
:
std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar
routine. That will give you an LPWSTR
, which is equivalent to wchar_t*
.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("file.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("staff")) {
String name = el.getElementsByTagName("name").item(0).getTextContent();
String phone = el.getElementsByTagName("phone").item(0).getTextContent();
String email = el.getElementsByTagName("email").item(0).getTextContent();
String area = el.getElementsByTagName("area").item(0).getTextContent();
String city = el.getElementsByTagName("city").item(0).getTextContent();
}
}
}
Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE
is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.
For each node under stuff (name, phone, email, area, city)
el.getElementsByTagName("name").item(0).getTextContent();
el.getElementsByTagName("name")
will extract the "name" nodes under stuff,
.item(0)
will get you the first node
and .getTextContent()
will get the text content inside.
Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:
public class Staff {
private String name;
private String phone;
private String email;
private String area;
private String city;
...getters setters
}
Then using jackson:
JsonNode root = new XmlMapper().readTree(xml.getBytes());
ObjectMapper mapper = new ObjectMapper();
root.forEach(node -> consume(node, mapper));
private void consume(JsonNode node, ObjectMapper mapper) {
try {
Staff staff = mapper.treeToValue(node, Staff.class);
//TODO your job with staff
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Apart from the <h:panelGroup>
component (which comes as a bit of a surprise to me), you could use a <f:verbatim>
tag with the escape parameter set to false
to generate any mark-up you want. For example:
<f:verbatim escape="true">
<div id="blah"></div>
</f:verbatim>
Bear in mind it's a little less elegant than the panelGroup
solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div
tag.
Alternatively, all the major UI Frameworks have a div
component tag, or you could write your own.
For displaying short, formatted text that doesn't need to be editable, Core Text is the way to go. There are several open-source projects for labels that use NSAttributedString
and Core Text for rendering. See CoreTextAttributedLabel or OHAttributedLabel for example.
What about performance?
scope.applyAsync
to reduce overall digest cycles countfunction debounce(func, wait) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
func.apply(context, args);
};
if (!timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
angular.module('app.layout')
.directive('classScroll', function ($window) {
return {
restrict: 'A',
link: function (scope, element) {
function toggle() {
angular.element(element)
.toggleClass('class-scroll--scrolled',
window.pageYOffset > 0);
scope.$applyAsync();
}
angular.element($window)
.on('scroll', debounce(toggle, 50));
toggle();
}
};
});
3. If you don't need to trigger watchers/digests at all then use compile
.directive('classScroll', function ($window, utils) {
return {
restrict: 'A',
compile: function (element, attributes) {
function toggle() {
angular.element(element)
.toggleClass(attributes.classScroll,
window.pageYOffset > 0);
}
angular.element($window)
.on('scroll', utils.debounce(toggle, 50));
toggle();
}
};
});
And you can use it like <header class-scroll="header--scrolled">
I just encountered a case where changing from
</div>
<script src="addressofjavascriptfile.js"></script>
</body>
</html>
to
<script src="addressofjavascriptfile.js"></script>
</div>
</body>
</html>
fixed this problem.
Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
Bootstrap is the world’s most popular and widely used open-source framework for developing with HTML, CSS, and JS. It is a front end framework of HTML. Bootstrap helps in building responsive websites or web applications and a 12-column grid system that helps dynamically adjust the website to a suitable screen resolution. The current version of bootstrap is 4.3.1 and the bootstrap team has also officially announced Bootstrap 5 version and changes like removing jquery from bootstrap. Some of the crucial reasons why bootstrap framework is most preferable are
It is easy to use
Bootstrap has a big community support
Customizations can be done easily
It increases development speed
Responsiveness
For more details, you can check the official website: https://getbootstrap.com/
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
There are 2 techniques which can come in handy for this common scenario. Each have their drawbacks but can both be useful at times.
box-sizing: border-box includes padding and border width in the width of an item. For example, if you set the width of a div with 20px 20px padding and 1px border to 100px, the actual width would be 142px but with border-box, both padding and margin are inside the 100px.
.bb{
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
width: 100%;
height:200px;
padding: 50px;
}
Here's an excellent article on it: http://css-tricks.com/box-sizing/ and here's a fiddle http://jsfiddle.net/L3Rvw/
And then there's position: absolute
.padded{
position: absolute;
top: 50px;
right: 50px;
left: 50px;
bottom: 50px;
background-color: #aefebc;
}
Neither are perfect of course, box-sizing doesn't exactly fit the question as the element is actually 100% width, rather than 100% - 100px (however a child div would be). And absolute positioning definitely can't be used in every situation, but is usually okay as long as the parent height is set.
I understand you intention well, I use buffers exclusively too, and occasionally do split if needed.
below is excerpt of my .vimrc
" disable macro, since not used in 90+% use cases
map q <Nop>
" q, close/hide current window, or quit vim if no other window
nnoremap q :if winnr('$') > 1 \|hide\|else\|silent! exec 'q'\|endif<CR>
" qo, close all other window -- 'o' stands for 'only'
nnoremap qo :only<CR>
set hidden
set timeout
set timeoutlen=200 " let vim wait less for your typing!
Which fits my workflow quite well
If
q
was pressed
- hide current window if multiple window open, else try to quit vim.
if
qo
was pressed,
- close all other window, no effect if only one window.
Of course, you can wrap that messy part into a function, eg
func! Hide_cur_window_or_quit_vim()
if winnr('$') > 1
hide
else
silent! exec 'q'
endif
endfunc
nnoremap q :call Hide_cur_window_or_quit_vim()<CR>
Sidenote:
I remap q
, since I do not use macro for editing, instead use :s
, :g
, :v
, and external text processing command if needed, eg, :'{,'}!awk 'some_programm'
, or use :norm! normal-command-here
.
We cannot always depend on ERRORLEVEL, because many times external programs or batch scripts do not return exit codes.
In that case we can use generic checks for failures like this:
IF EXIST %outfile% (DEL /F %outfile%)
CALL some_script.bat -o %outfile%
IF NOT EXIST %outfile% (ECHO ERROR & EXIT /b)
And if the program outputs something to console, we can check it also.
some_program.exe 2>&1 | FIND "error message here" && (ECHO ERROR & EXIT /b)
some_program.exe 2>&1 | FIND "Done processing." || (ECHO ERROR & EXIT /b)
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
Make UIAlertController+AlertController Category as:
UIAlertController+AlertController.h
typedef void (^UIAlertCompletionBlock) (UIAlertController *alertViewController, NSInteger buttonIndex);
@interface UIAlertController (AlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock;
@end
UIAlertController+AlertController.m
@implementation UIAlertController (NTAlertController)
+ (instancetype)showAlertIn:(UIViewController *)controller
WithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitle
tapBlock:(UIAlertCompletionBlock)tapBlock {
UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
if(cancelButtonTitle != nil) {
UIAlertAction *cancelButton = [UIAlertAction
actionWithTitle:cancelButtonTitle
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_CANCEL); // CANCEL BUTTON CALL BACK ACTION
}];
[alertController addAction:cancelButton];
}
if(otherButtonTitle != nil) {
UIAlertAction *otherButton = [UIAlertAction
actionWithTitle:otherButtonTitle
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
tapBlock(alertController, ALERTACTION_OTHER); // OTHER BUTTON CALL BACK ACTION
}];
[alertController addAction:otherButton];
}
[controller presentViewController:alertController animated:YES completion:nil];
return alertController;
}
@end
in your ViewController.m
[UIAlertController showAlertIn:self WithTitle:@"" message:@"" cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other" tapBlock:^(UIAlertController *alertController, NSInteger index){
if(index == ALERTACTION_CANCEL){
// CANCEL BUTTON ACTION
}else
if(index == ALERTACTION_OTHER){
// OTHER BUTTON ACTION
}
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
NOTE: If you want to add more than two buttons then add another more UIAlertAction to the UIAlertController.
The other answers don't mention that you can also set this in the XML of your Toolbar
widget:
app:navigationIcon="?attr/homeAsUpIndicator"
For example:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:navigationIcon="?attr/homeAsUpIndicator"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:title="@string/title_activity_acoustic_progress" />
It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim()
instead (http://api.jquery.com/jQuery.trim/).
I'd like to add that the array initialization syntax is very succinct and flexible. I use it a LOT to extract data from my code and place it somewhere more usable.
As an example, I've often created menus like this:
Menu menu=initMenus(menuHandler, new String[]{"File", "+Save", "+Load", "Edit", "+Copy", ...});
This would allow me to write come code to set up a menu system. The "+" is enough to tell it to place that item under the previous item.
I could bind it to the menuHandler class either by a method naming convention by naming my methods something like "menuFile, menuFileSave, menuFileLoad, ..." and binding them reflectively (there are other alternatives).
This syntax allows AMAZINGLY brief menu definition and an extremely reusable "initMenus" method. (Yet I don't bother reusing it because it's always fun to write and only takes a few minutes+a few lines of code).
any time you see a pattern in your code, see if you can replace it with something like this, and always remember how succinct the array initialization syntax is!.
Here is a CSV action result I wrote that takes a DataTable and converts it into CSV. You can return this from your view and it will prompt the user to download the file. You should be able to convert this easily into a List compatible form or even just put your list into a DataTable.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
namespace Detectent.Analyze.ActionResults
{
public class CSVResult : ActionResult
{
/// <summary>
/// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
/// </summary>
/// <param name="dataTable"></param>
/// <param name="fileName">The full file name including the extension.</param>
public CSVResult(DataTable dataTable, string fileName)
{
Table = dataTable;
FileName = fileName;
}
public string FileName { get; protected set; }
public DataTable Table { get; protected set; }
public override void ExecuteResult(ControllerContext context)
{
StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);
for (int c = 0; c < Table.Columns.Count; c++)
{
if (c > 0)
csv.Append(",");
DataColumn dc = Table.Columns[c];
string columnTitleCleaned = CleanCSVString(dc.ColumnName);
csv.Append(columnTitleCleaned);
}
csv.Append(Environment.NewLine);
foreach (DataRow dr in Table.Rows)
{
StringBuilder csvRow = new StringBuilder();
for(int c = 0; c < Table.Columns.Count; c++)
{
if(c != 0)
csvRow.Append(",");
object columnValue = dr[c];
if (columnValue == null)
csvRow.Append("");
else
{
string columnStringValue = columnValue.ToString();
string cleanedColumnValue = CleanCSVString(columnStringValue);
if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
{
cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
}
csvRow.Append(cleanedColumnValue);
}
}
csv.AppendLine(csvRow.ToString());
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
response.Write(csv.ToString());
}
protected string CleanCSVString(string input)
{
string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
return output;
}
}
}
You can use contextual selectors and move the vertical-align there. This would work with the p tag, then. Take this snippet below as an example. Any p tags within your class will respect the vertical-align control:
#header_selecttxt {
font-family: Arial;
font-size: 12px;
font-weight: bold;
}
#header_selecttxt p {
vertical-align: text-top;
}
You could also keep the vertical-align in both sections so that other, inline elements would use this.
If you're using python >= 3.8, you can use the fmean
function introduced in the statistics
module which is part of the standard library:
>>> from statistics import fmean
>>> fmean([0, 1, 2, 3])
1.5
It's faster than the statistics.mean
function, but it converts its data points to float
beforehand, so it can be less accurate in some specific cases.
You can see its implementation here
This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
SearchView searchView = (SearchView) myActionMenuItem.getActionView();
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(Color.WHITE); //You color here
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y
means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
Alternatively to the answer above, you can have a MySQL table that uses the CSV engine.
Then you will have a file on your hard disk that will always be in a CSV format which you could just copy without processing it.
Note: The snippet would only work if the iframe is with the same origin.
Other answers proposed the load
event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.
Here's a plain JavaScript solution:
function iframeURLChange(iframe, callback) {_x000D_
var unloadHandler = function () {_x000D_
// Timeout needed because the URL changes immediately after_x000D_
// the `unload` event is dispatched._x000D_
setTimeout(function () {_x000D_
callback(iframe.contentWindow.location.href);_x000D_
}, 0);_x000D_
};_x000D_
_x000D_
function attachUnload() {_x000D_
// Remove the unloadHandler in case it was already attached._x000D_
// Otherwise, the change will be dispatched twice._x000D_
iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
}_x000D_
_x000D_
iframe.addEventListener("load", attachUnload);_x000D_
attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
This will successfully track the src
attribute changes, as well as any URL changes made from within the iframe itself.
Tested in all modern browsers.
I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary) Use Method 1 if performance is not a consideration, use Method 2 if memory is not a consideration.
Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.
Is there any reason you can't reverse the key-value relationship?
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.
There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.
Examples:
Load URL into ImageView without generating a bitmap:
Picasso.with(context) // Context
.load("http://abc.imgur.com/gxsg.png") // URL or file
.into(imageView); // An ImageView object to show the loaded image
Load URL into ImageView by generating a bitmap:
Picasso.with(this)
.load(artistImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
There are many more options available in Picasso. Here is the documentation.
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!
<input type="file" multiple ng-simple-upload web-api-url="/api/post"
callback-fn="myCallback" />
ng-simple-upload more on Github with an example using Web API.
You could do it like this:
iterations = 10
variables = 2
output <- matrix(ncol=variables, nrow=iterations)
for(i in 1:iterations){
output[i,] <- runif(2)
}
output
and then turn it into a data.frame
output <- data.frame(output)
class(output)
what this does:
With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css
.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Here is a working demo.
Note that you have to use .glyphicon
classes instead of .icon
:
Example:
<span class="glyphicon glyphicon-heart"></span>
Also note that you would still need to include bootstrap.min.js
for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.
If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
Since the css
file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css
file is all there is to do to start using Glyphicons.
Here is a working demo of the Glyphicons without Bootstrap.
You can delete the file using
unlink($Your_file_path);
but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.
If it wasn't checked in as a Java Project, you can add the java nature as shown here.
Here is a happy little list to put in your .jshintrc
I will add to this list at time passes.
{
// other settings...
// ENVIRONMENTS
// "browser": true, // Is in most configs by default
"node": true,
// others (e.g. yui, mootools, rhino, worker, etc.)
"globals": {
"$":false,
"jquery":false,
"angular":false
// other explicit global names to exclude
},
}
One important thing to check that no one has mentioned so far: Check your local firewall, make sure it's turned OFF.
See my response here: https://stackoverflow.com/a/41400708/1459275
I got this error in the context of angular tree control. In my case it was the tree options. I was returning treeOptions() from a function. It was always returning the same object. But Angular magically thinks that its a new object and then cause a digest cycle to kick off. Causing a recursion of digests. The solution was to bind the treeOptions to scope. And assign it just once.
I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.
My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.
For those who use Spring framework there is a useful StreamUtils class:
StreamUtils.copy(in, out);
The above does not close the streams. If you want the streams closed after the copy, use FileCopyUtils class instead:
FileCopyUtils.copy(in, out);
JSON of unknown format to HashMap
public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
writeJson("JsonFile.json");
readgson("JsonFile.json");
}
public static void readgson(String file) {
try {
System.out.println( "Reading JSON file from Java program" );
FileReader fileReader = new FileReader( file );
com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
if ( keys.isEmpty() ) {
System.out.println( "Empty JSON Object" );
}else {
Map<String, Object> map = json_UnKnown_Format( keys );
System.out.println("Json 2 Map : "+map);
}
} catch (IOException ex) {
System.out.println("Input File Does not Exists.");
}
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
Map<String, Object> jsonMap = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : keys) {
String keyEntry = entry.getKey();
System.out.println(keyEntry + " : ");
JsonElement valuesEntry = entry.getValue();
if (valuesEntry.isJsonNull()) {
System.out.println(valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonPrimitive()) {
System.out.println("P - "+valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonArray()) {
JsonArray array = valuesEntry.getAsJsonArray();
List<Object> array2List = new ArrayList<Object>();
for (JsonElement jsonElements : array) {
System.out.println("A - "+jsonElements);
array2List.add(jsonElements);
}
jsonMap.put(keyEntry, array2List);
}else if (valuesEntry.isJsonObject()) {
com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
}
}
return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {
JSONObject json = new JSONObject();
json.put("Key1", "Value");
json.put("Key2", 777); // Converts to "777"
json.put("Key3", null);
json.put("Key4", false);
JSONArray jsonArray = new JSONArray();
jsonArray.put("Array-Value1");
jsonArray.put(10);
jsonArray.put("Array-Value2");
json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]
JSONObject jsonObj = new JSONObject();
jsonObj.put("Obj-Key1", 20);
jsonObj.put("Obj-Key2", "Value2");
jsonObj.put(4, "Value2"); // Converts to "4"
json.put("InnerObject", jsonObj);
JSONObject jsonObjArray = new JSONObject();
JSONArray objArray = new JSONArray();
objArray.put("Obj-Array1");
objArray.put(0, "Obj-Array3");
jsonObjArray.put("ObjectArray", objArray);
json.put("InnerObjectArray", jsonObjArray);
Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
sortedTree.put("Sorted1", 10);
sortedTree.put("Sorted2", 103);
sortedTree.put("Sorted3", 14);
json.put("TreeMap", sortedTree);
try {
System.out.println("Writting JSON into file ...");
System.out.println(json);
FileWriter jsonFileWriter = new FileWriter(file);
jsonFileWriter.write(json.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
It worked for me like this:
Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:
/index.php/%year%/%monthnum%/%day%/%postname%/
and click the Save button.
A bonus would be if I can detect the specific version(s) of Excel that is(/are) installed.
I know the question has been asked and answered a long time ago, but this same question has kept me busy until I made this observation:
To get the build number (e.g. 15.0.4569.1506
), probe HKLM\SOFTWARE\Microsoft\Office\[VER]\Common\ProductVersion::LastProduct
, where [VER]
is the major version number (12.0 for Office 2007, 14.0 for Office 2010, 15.0 for Office 2013).
On a 64-bit Windows, you need to insert Wow6432Node
between the SOFTWARE
and Microsoft
crumbs, irrespective of the bitness of the Office installation.
On my machines, this gives the version information of the originally installed version. For Office 2010 for instance, the numbers match the ones listed here, and they differ from the version reported in File > Help
, which reflects patches applied by hotfixes.
Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Type type = assembly.GetType("MyType");
dynamic instanceOfMyType = Activator.CreateInstance(type);
So in this way you can use functions not with getting methodinfo,and then invoking it.You will do like this instanceOfMyType.MethodName(); But you can't use Intellisense because dynamic types are typed in runtime,not in compile time.
In case of SQL Server, this should work
SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond
We use a combination of the processor id number (ProcessorID
) from Win32_processor
and the universally unique identifier (UUID
) from Win32_ComputerSystemProduct
:
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
processorId = mo["ProcessorID"] as string;
}
mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
systemId = mo["UUID"] as string;
}
var compIdStr = $"{processorId}{systemId}";
Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor"
) and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"
), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:
Therefore, it is worth considering this situation.
Also keep in mind that the ProcessorID
number may be the same on different computers.
This seems to work great :
if( response.getEntity() != null ) {
response.getEntity().consumeContent();
}//if
And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !
This error consumed my whole day so thought of writing what really worked for me
"DO NOT DELETE PODFILE"
After all this, CLEAN(OPTION + SHIFT + CMD + K) --> BUILD(CMD + B) --> RUN(CMD + R)
I hope this really works for you :)
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3</version>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.exe</exclude>
<exclude>**/*.java</exclude>
<exclude>**/*.xls</exclude>
</excludes>
</configuration>
</plugin>
Use following html
<link rel="stylesheet" href="app/components/directives/navBar/navBar.scss"/>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav">
<li><h5><a href="#/">Home</a></h5></li>
<li>|</li>
<li><h5><a href="#products">About</a></h5></li>
<li>|</li>
<li><h5><a href="#">Contacts</a></h5></li>
<li>|</li>
<li><h5><a href="#cart">Cart</a></h5></li>
</ul>
</div><!-- /.container-fluid -->
</nav>
And css
.navbar-nav {
width: 100%;
text-align: center;
}
.navbar-nav > li {
float: none;
display: inline-block;
}
.navbar-default {
background-color: white;
border-color: white;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus{
background-color:white;
}
Modify according to your needs
You can use this:
select
table_name,column_name,referenced_table_name,referenced_column_name
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
Or for better formatted output use this:
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
Use ng-switch with expression and ng-switch-when
for matching expression value:
<div ng-switch="data.id">
<div ng-switch-when="5">...</div>
<div ng-switch-default>...</div>
</div>
Usually, if the command is an external program, you can use the OS to help you here.
command > file_output.txt
So your C code would be doing something like
exec("command > file_output.txt");
Then you can use the file_output.txt file.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
Using conda install scipy instead of pip solved the problem for me!
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
I took Nico Burns's answer and made it using jQuery:
div contentEditable="true"
You'll need jQuery 1.6 or higher:
savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
var s = window.getSelection();
var t = $('div[contenteditable="true"]').index(this);
if (typeof(savedRanges[t]) === "undefined"){
savedRanges[t]= new Range();
} else if(s.rangeCount > 0) {
s.removeAllRanges();
s.addRange(savedRanges[t]);
}
}).bind("mouseup keyup",function(){
var t = $('div[contenteditable="true"]').index(this);
savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
if(!$(this).is(":focus")){
e.stopPropagation();
e.preventDefault();
$(this).focus();
}
});
savedRanges = new Object();_x000D_
$('div[contenteditable="true"]').focus(function(){_x000D_
var s = window.getSelection();_x000D_
var t = $('div[contenteditable="true"]').index(this);_x000D_
if (typeof(savedRanges[t]) === "undefined"){_x000D_
savedRanges[t]= new Range();_x000D_
} else if(s.rangeCount > 0) {_x000D_
s.removeAllRanges();_x000D_
s.addRange(savedRanges[t]);_x000D_
}_x000D_
}).bind("mouseup keyup",function(){_x000D_
var t = $('div[contenteditable="true"]').index(this);_x000D_
savedRanges[t] = window.getSelection().getRangeAt(0);_x000D_
}).on("mousedown click",function(e){_x000D_
if(!$(this).is(":focus")){_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$(this).focus();_x000D_
}_x000D_
});
_x000D_
div[contenteditable] {_x000D_
padding: 1em;_x000D_
font-family: Arial;_x000D_
outline: 1px solid rgba(0,0,0,0.5);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>
_x000D_
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
Structs can have functions just like classes. The only difference is that they are public by default:
struct A {
void f() {}
};
Additionally, structs can also have constructors and destructors.
struct A {
A() : x(5) {}
~A() {}
private: int x;
};
QFile file("bigimage.jpg");
if (file.open(QIODevice::ReadOnly))
{
QByteArray fileData = file.readAll();
QByteArray hashData = QCryptographicHash::hash(fileData,QCryptographicHash::Md5); // or QCryptographicHash::Sha1
qDebug() << hashData.toHex(); // 0e0c2180dfd784dd84423b00af86e2fc
}
It works for me by using require syntax like this:
$('.eventSlick').slick({
dots: true,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: false,
autoplaySpeed: 2000,
arrows: true,
draggable: false,
prevArrow: '<button type="button" data-role="none" class="slick-prev"><img src="' + require("@/assets/img/icon/Arrow_Left.svg")+'"></button>',
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
In the Android Studio IDE, access the "Run Anything bar" by:
CTRL+CTRL +gradle CreateFullJarRelease
+ENTER
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
Gradle has already a Task
for that, in the gradle side-menu, under the other
folder.
Then scroll down to createFullJarRelease
and click it.
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
I was able to bypass all the framework messages by making the property a string in my view model.
[Range(0, 15, ErrorMessage = "Can only be between 0 .. 15")]
[StringLength(2, ErrorMessage = "Max 2 digits")]
[Remote("PredictionOK", "Predict", ErrorMessage = "Prediction can only be a number in range 0 .. 15")]
public string HomeTeamPrediction { get; set; }
Then I need to do some conversion in my get method:
viewModel.HomeTeamPrediction = databaseModel.HomeTeamPrediction.ToString();
and post method:
databaseModel.HomeTeamPrediction = int.Parse(viewModel.HomeTeamPrediction);
This works best when using the range attribute, otherwise some additional validation would be needed to make sure the value is a number.
You can also specify the type of number by changing the numbers in the range to the correct type:
[Range(0, 10000000F, ErrorMessageResourceType = typeof(GauErrorMessages), ErrorMessageResourceName = nameof(GauErrorMessages.MoneyRange))]
If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?
In version 2, instead of
from module import attribute1
you can do
attribute1 = module.attribute1
Try using the ToDictionary
method like so:
var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );
I really recommend using some sort of library, but you asked for it, you get it:
var p = document.querySelector('p'); // element to make resizable
p.addEventListener('click', function init() {
p.removeEventListener('click', init, false);
p.className = p.className + ' resizable';
var resizer = document.createElement('div');
resizer.className = 'resizer';
p.appendChild(resizer);
resizer.addEventListener('mousedown', initDrag, false);
}, false);
var startX, startY, startWidth, startHeight;
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
p.style.width = (startWidth + e.clientX - startX) + 'px';
p.style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).
Possible options to exclude files/directories from backup using tar:
Exclude files using multiple patterns
tar -czf backup.tar.gz --exclude=PATTERN1 --exclude=PATTERN2 ... /path/to/backup
Exclude files using an exclude file filled with a list of patterns
tar -czf backup.tar.gz -X /path/to/exclude.txt /path/to/backup
Exclude files using tags by placing a tag file in any directory that should be skipped
tar -czf backup.tar.gz --exclude-tag-all=exclude.tag /path/to/backup
The proper way to login into mongo shell is
mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname
Just in case you do this for a lot of functions in your class:
class Foo {
public:
virtual void f1() {
// ...
}
virtual void f2() {
// ...
}
//...
};
class Bar : public Foo {
private:
typedef Foo super;
public:
void f1() {
super::f1();
}
};
This might save a bit of writing if you want to rename Foo.
Not knowing what you are trying to do, I'll share one more suggestion: Preallocate vectors of the type you want for each column, insert values into those vectors, and then, at the end, create your data.frame
.
Continuing with Julian's f3
(a preallocated data.frame
) as the fastest option so far, defined as:
# pre-allocate space
f3 <- function(n){
df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
for(i in 1:n){
df$x[i] <- i
df$y[i] <- toString(i)
}
df
}
Here's a similar approach, but one where the data.frame
is created as the last step.
# Use preallocated vectors
f4 <- function(n) {
x <- numeric(n)
y <- character(n)
for (i in 1:n) {
x[i] <- i
y[i] <- i
}
data.frame(x, y, stringsAsFactors=FALSE)
}
microbenchmark
from the "microbenchmark" package will give us more comprehensive insight than system.time
:
library(microbenchmark)
microbenchmark(f1(1000), f3(1000), f4(1000), times = 5)
# Unit: milliseconds
# expr min lq median uq max neval
# f1(1000) 1024.539618 1029.693877 1045.972666 1055.25931 1112.769176 5
# f3(1000) 149.417636 150.529011 150.827393 151.02230 160.637845 5
# f4(1000) 7.872647 7.892395 7.901151 7.95077 8.049581 5
f1()
(the approach below) is incredibly inefficient because of how often it calls data.frame
and because growing objects that way is generally slow in R. f3()
is much improved due to preallocation, but the data.frame
structure itself might be part of the bottleneck here. f4()
tries to bypass that bottleneck without compromising the approach you want to take.
This is really not a good idea, but if you wanted to do it this way, I guess you can try:
for (i in 1:10) {
df <- rbind(df, data.frame(x = i, y = toString(i)))
}
Note that in your code, there is one other problem:
stringsAsFactors
if you want the characters to not get converted to factors. Use: df = data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
Yes, that code does exactly that.
You can also use:
if (@value is null or @value = '')
With the added information that @value
is an int
value, you need instead:
if (@value is null)
An int
value can never contain the value ''
.
You may use @JsonIgnore
to break the cycle (reference).
You need to import org.codehaus.jackson.annotate.JsonIgnore
(legacy versions) or com.fasterxml.jackson.annotation.JsonIgnore
(current versions).
You can use DECIMAL
or NUMERIC
both are same
The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL
i.e. DECIMAL(10,2)
Another point to add.
Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.
int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)
Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.
Can overload class constructors, methods.
Can consider as Compile Time (static / Early Binding) polymorphism.
=====================================================================================================
Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.
Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.
Can Consider as Run Time (Dynamic / Late Binding) polymorphism.
Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx
=====================================================================================================
Helpful Links
http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism
If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.
xmlDoc.Load(new StreamReader(
File.Open("file.xml"),
Encoding.GetEncoding("iso-8859-15")));
I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:
<?xml version="1.0" encoding="UTF-16"?>
Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.
Link Source:
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
YES YOU CAN.
In your stored procedure, you fill the table @tbRetour
.
At the very end of your stored procedure, you write:
SELECT * FROM @tbRetour
To execute the stored procedure, you write:
USE [...]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'
GO
I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.
I didn't go through, but I got what I wanted in the query posted by the original author.
I used it (without conditions/filters) for my requirement but it gave incorrect results
The main problem was the results getting cross product without join condition on index_id
SELECT S.NAME SCHEMA_NAME,T.NAME TABLE_NAME,I.NAME INDEX_NAME,C.NAME COLUMN_NAME
FROM SYS.TABLES T
INNER JOIN SYS.SCHEMAS S
ON T.SCHEMA_ID = S.SCHEMA_ID
INNER JOIN SYS.INDEXES I
ON I.OBJECT_ID = T.OBJECT_ID
INNER JOIN SYS.INDEX_COLUMNS IC
ON IC.OBJECT_ID = T.OBJECT_ID
INNER JOIN SYS.COLUMNS C
ON C.OBJECT_ID = T.OBJECT_ID
**AND IC.INDEX_ID = I.INDEX_ID**
AND IC.COLUMN_ID = C.COLUMN_ID
WHERE 1=1
ORDER BY I.NAME,I.INDEX_ID,IC.KEY_ORDINAL
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
How about gSOAP? It is open source and freely available under the GPL license. Despite its name, the gSOAP toolkit is a generic XML data binding tool and allows you to bind your C and C++ data to XML automatically. There is no need to use an XML parser API, just let it read/write your data in XML format for you. If you really need a super-simple C++ XML parser then gSOAP may be an overkill. But for everything else it has worked well as testimonials show for many industrial applications since gSOAP was introduced in 2001.
Here is a brief list of features:
For example:
class Address
{
std::string name;
std::vector<LONG64> number;
time_t date;
};
Then run "soapcpp2" on the Address
class declaration above to generate the soap_read_Address
and soap_write_Address
XML reader and writer, for example:
Address *a = new Address();
a = ...;
soap ctx = soap_new();
soap_write_Address(ctx, a);
soap_end(ctx);
soap_free(ctx);`
This produces an XML representation of the Address a
object. By annotating the header file declarations with XML namespace details (not shown here), the tools also generate schemas. This is a simple example. The gSOAP tools can handle a very broad range of C and C++ data types, including pointer-based linked structures and even (cyclic) graphs (rather than just trees).
Hope this helps.
A SpringApplication
will attempt to create the right type of ApplicationContext
on your behalf. By default, an AnnotationConfigApplicationContext
or AnnotationConfigEmbeddedWebApplicationContext
will be used, depending on whether you are developing a web application or not.
The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use setWebEnvironment(boolean webEnvironment)
if you need to override the default.
It is also possible to take complete control of the ApplicationContext
type that will be used by calling setApplicationContextClass(…?)
.
[Tip]
It is often desirable to call setWebEnvironment(false)
when using SpringApplication
within a JUnit test.
If you are interested in parsing command line arguments to an R script try RScript which is bundled with R as of version 2.5.x
http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html
Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY
tells the OS to recreate the service after it has enough memory and call onStartCommand()
again with a null intent. START_NOT_STICKY
tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT
that tells the OS to recreate the service and redeliver the same intent to onStartCommand()
.
This article by Dianne Hackborn explained the background of this a lot better than the official documentation.
Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html
The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:
START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.
Try this one it's easy.. to Pic a Image using UIImagePickerControllerDelegate
@objc func masterAction(_ sender: UIButton)
{
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
print("hello i'm touch \(sender.tag)")
}
func imagePickerControllerDidCancel(_ picker:
UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
print("Get Image \(chosenImage)")
ImageList.insert(chosenImage, at: 0)
ArrayList.insert("", at: 0)
Collection_Vw.reloadData()
} else{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.
The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...
@ECHO OFF
SET man1=%1
SET man2=%2
SHIFT & SHIFT
:loop
IF NOT "%1"=="" (
IF "%1"=="-username" (
SET user=%2
SHIFT
)
IF "%1"=="-otheroption" (
SET other=%2
SHIFT
)
SHIFT
GOTO :loop
)
ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%
REM ...do stuff here...
:theend
The Collections.sort is a good sort implementation. If you don't have The comparable implemented for Contact, you will need to pass in a Comparator implementation
Of note:
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
The merge sort is probably better than most search algorithm you can do.
Don't use HTTP use SSH instead
change
https://github.com/WEMP/project-slideshow.git
to
[email protected]:WEMP/project-slideshow.git
you can do it in .git/config
file
Just make sure that you have one root div and put everything inside this root
<div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>
and so on
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
EDIT: Blender's updated answer is the right answer here if you're just checking a single character (namely !isNaN(parseInt(c, 10))
). My answer below is a good solution if you want to test whole strings.
Here is jQuery's isNumeric
implementation (in pure JavaScript), which works against full strings:
function isNumeric(s) {
return !isNaN(s - parseFloat(s));
}
The comment for this function reads:
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
I think we can trust that these chaps have spent quite a bit of time on this!
Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.
This problem happens because you are calling fun.cpp
instead of fun.hpp
. So c++ compiler finds func.cpp definition twice and throws this error.
Change line 3 of your main.cpp
file, from #include "fun.cpp"
to #include "fun.hpp"
.
In c# following code insert data into datatable on specified position
DataTable dt = new DataTable();
dt.Columns.Add("SL");
dt.Columns.Add("Amount");
dt.rows.add(1, 1000)
dt.rows.add(2, 2000)
dt.Rows.InsertAt(dt.NewRow(), 3);
var rowPosition = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("SL")] = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("Amount")] = 3000;
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
You can also find an element by name using FrameworkElement.FindName(string).
Given:
<UserControl ...>
<TextBlock x:Name="myTextBlock" />
</UserControl>
In the code-behind file, you could write:
var myTextBlock = (TextBlock)this.FindName("myTextBlock");
Of course, because it's defined using x:Name, you could just reference the generated field, but perhaps you want to look it up dynamically rather than statically.
This approach is also available for templates, in which the named item appears multiple times (once per usage of the template).
There is already an primary key in your table. You can't just add primary key,otherwise will cause error. Because there is one primary key for sql table.
First, you have to drop your old primary key.
MySQL:
ALTER TABLE Persion
DROP PRIMARY KEY;
SQL Server / Oracle / MS Access:
ALTER TABLE Persion
DROP CONSTRAINT 'constraint name';
You have to find the constraint name in your table. If you had given constraint name when you created table,you can easily use the constraint name(ex:PK_Persion).
Second,Add primary key.
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persion ADD PRIMARY KEY (PersionId,Pname,PMID);
or the better one below
ALTER TABLE Persion ADD CONSTRAINT PK_Persion PRIMARY KEY (PersionId,Pname,PMID);
This can set constraint name by developer. It's more easily to maintain the table.
I got a little confuse when i have looked all answers. So I research some document to find every detail. Hope this answer can help other SQL beginner.
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
Is there any solution like building a pdf file on file system in order to let the user download it?
Try setting responseType
of XMLHttpRequest
to blob
, substituting download
attribute at a
element for window.open
to allow download of response from XMLHttpRequest
as .pdf
file
var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true);
request.responseType = "blob";
request.onload = function (e) {
if (this.status === 200) {
// `blob` response
console.log(this.response);
// create `objectURL` of `this.response` : `.pdf` as `Blob`
var file = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
a.href = file;
a.download = this.response.name || "detailPDF";
document.body.appendChild(a);
a.click();
// remove `a` following `Save As` dialog,
// `window` regains `focus`
window.onfocus = function () {
document.body.removeChild(a)
}
};
};
request.send();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript"><!--
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
alert(targ.innerHTML);
}
onload = function() {
var t = document.getElementById("main").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
</script>
<body>
<table id="main"><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr><tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr><tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr></table>
</body>
</html>
Based on what I understand from the latest git documentation, the synopsis is:
git branch -u upstream-branch local-branch
git branch --set-upstream-to=upstream-branch local-branch
This usage seems to be a bit different than urschrei's answer, as in his the synopsis is:
git branch local-branch -u upstream-branch
git branch local-branch --set-upstream-to=upstream-branch
I'm guessing they changed the documentation again?
For Visual Studio 2005:
If you do have an installed Visual Studio 2005 however, and want to find out the serial number you’ve used to install it because you don’t have a clue where you put that shiny sticker, you can. It is, like most things in Windows, in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
In order to convert the value in that key to an actual serial number you have to put a dash ( – ) after evert 5 characters of the code.
From: http://www.gooli.org/blog/visual-studio-2005-serial-number/
For Visual Studio 2008 it's supposed to be:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
However I noted that the the Data field for PIDKEY is only filled in the 1000.0x000
(or 2000.0x000) sub folder of the above paths.
If this is not a performance issue for you, you can write
public String getFirstName(Person person) {
try {
return person.getName().getGivenName();
} catch (NullPointerException ignored) {
return null;
}
}
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.
The lesson learned is "always use homogeneous development and deployment databases!"
I am using iobroker and easily managed to stop the script with
stopScript();
There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.
''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task
''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task
''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource
''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
Me._ActionTask = Task.Run(taskAction)
Await Me.ActionTask ' Task.Run(streamEntitiesAction)
Try
Me.ActionTask?.Wait()
Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
Catch ex As AggregateException
Me.OnExceptionOccurred(ex)
Finally
Me.TaskCancellationSource.Dispose()
End Try
End Function
''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey"> The bucket key. </param>
''' <param name="timeout"> The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
If Me.IsTaskActive Then
Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
Else
Me._TaskCancellationSource = New Threading.CancellationTokenSource
Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
Me.TaskCancellationSource.CancelAfter(timeout)
' the action class is created withing the Async/Await function
Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
End If
End Sub
After combining a lot of snippets, I finally found a reuseable solution for Windows, that uses ATL Library, which comes with Visual Studio.
#include <atlstr.h>
void getFiles(CString directory) {
HANDLE dir;
WIN32_FIND_DATA file_data;
CString file_name, full_file_name;
if ((dir = FindFirstFile((directory + "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
// Invalid directory
}
while (FindNextFile(dir, &file_data)) {
file_name = file_data.cFileName;
full_file_name = directory + file_name;
if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
{
std::string fileName = full_file_name.GetString();
// Do stuff with fileName
}
}
}
To access the method, just call:
getFiles("i:\\Folder1");
There is an function, but it's extra: http://docs.jquery.com/Cookbook/wait
This little snippet allows you to wait:
$.fn.wait = function(time, type) {
time = time || 1000;
type = type || "fx";
return this.queue(type, function() {
var self = this;
setTimeout(function() {
$(self).dequeue();
}, time);
});
};
Number of days calculation between two dates.
$(document).ready(function () {
$('.submit').on('click', function () {
var startDate = $('.start-date').val();
var endDate = $('.end-date').val();
var start = new Date(startDate);
var end = new Date(endDate);
var diffDate = (end - start) / (1000 * 60 * 60 * 24);
var days = Math.round(diffDate);
});
});
I was just playing around with this same subject, which is the fastest way to access the pixels. I currently know of two ways for doing this:
getRGB()
method as described in @tskuzzy's answer.By accessing the pixels array directly using:
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
If you are working with large images and performance is an issue, the first method is absolutely not the way to go. The getRGB()
method combines the alpha, red, green and blue values into one int and then returns the result, which in most cases you'll do the reverse to get these values back.
The second method will return the red, green and blue values directly for each pixel, and if there is an alpha channel it will add the alpha value. Using this method is harder in terms of calculating indices, but is much faster than the first approach.
In my application I was able to reduce the time of processing the pixels by more than 90% by just switching from the first approach to the second!
Here is a comparison I've setup to compare the two approaches:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PerformanceTest {
public static void main(String[] args) throws IOException {
BufferedImage hugeImage = ImageIO.read(PerformanceTest.class.getResource("12000X12000.jpg"));
System.out.println("Testing convertTo2DUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
System.out.println("");
System.out.println("Testing convertTo2DWithoutUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DWithoutUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
}
private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel + 3 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel + 2 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
private static String toString(long nanoSecs) {
int minutes = (int) (nanoSecs / 60000000000.0);
int seconds = (int) (nanoSecs / 1000000000.0) - (minutes * 60);
int millisecs = (int) ( ((nanoSecs / 1000000000.0) - (seconds + minutes * 60)) * 1000);
if (minutes == 0 && seconds == 0)
return millisecs + "ms";
else if (minutes == 0 && millisecs == 0)
return seconds + "s";
else if (seconds == 0 && millisecs == 0)
return minutes + "min";
else if (minutes == 0)
return seconds + "s " + millisecs + "ms";
else if (seconds == 0)
return minutes + "min " + millisecs + "ms";
else if (millisecs == 0)
return minutes + "min " + seconds + "s";
return minutes + "min " + seconds + "s " + millisecs + "ms";
}
}
Can you guess the output? ;)
Testing convertTo2DUsingGetRGB:
1 : 16s 911ms
2 : 16s 730ms
3 : 16s 512ms
4 : 16s 476ms
5 : 16s 503ms
6 : 16s 683ms
7 : 16s 477ms
8 : 16s 373ms
9 : 16s 367ms
10: 16s 446ms
Testing convertTo2DWithoutUsingGetRGB:
1 : 1s 487ms
2 : 1s 940ms
3 : 1s 785ms
4 : 1s 848ms
5 : 1s 624ms
6 : 2s 13ms
7 : 1s 968ms
8 : 1s 864ms
9 : 1s 673ms
10: 2s 86ms
BUILD SUCCESSFUL (total time: 3 minutes 10 seconds)
The answer given by @HursVanBloob works only with fixed width parent container, but fails in case of fluid-width containers.
I tried a lot of properties, but nothing worked as expected. Finally I came to a conclusion that giving word-spacing
a very huge value works perfectly fine.
p { word-spacing: 9999999px; }
or, for the modern browsers you can use the CSS vw
unit (visual width in % of the screen size).
p { word-spacing: 100vw; }
It seems that the only parameter that allows you to inject custom text is the "quote".
https://www.facebook.com/sharer/sharer.php?u=THE_URL"e=THE_CUSTOM_TEXT
python compile on the fly when you run it.
Run a .py file by(linux): python abc.py
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
I found better way to do it. if you want to use something like this
Use this dependency
compile 'com.nex3z:notification-badge:0.1.0'
create one xml file in drawable and Save it as Badge.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#66000000"/>
<size android:width="30dp" android:height="40dp"/>
</shape>
</item>
<item android:bottom="1dp" android:right="0.6dp">
<shape android:shape="oval">
<solid android:color="@color/Error_color"/>
<size android:width="20dp" android:height="20dp"/>
</shape>
</item>
</layer-list>
Now wherever you want to use that badge use following code in xml. with the help of this you will be able to see that badge on top-right corner of your image or anything.
<com.nex3z.notificationbadge.NotificationBadge
android:id="@+id/badge"
android:layout_toRightOf="@id/Your_ICON/IMAGE"
android:layout_alignTop="@id/Your_ICON/IMAGE"
android:layout_marginLeft="-16dp"
android:layout_marginTop="-8dp"
android:layout_width="28dp"
android:layout_height="28dp"
app:badgeBackground="@drawable/Badge"
app:maxTextLength="2"
></com.nex3z.notificationbadge.NotificationBadge>
Now finally on yourFile.java use this 2 simple thing.. 1) Define
NotificationBadge mBadge;
2) where your loop or anything which is counting this number use this:
mBadge.setNumber(your_LoopCount);
here, mBadge.setNumber(0)
will not show anything.
Hope this help.
Reloading the configuration file (my.cnf
) cannot be done without restarting the mysqld
server.
FLUSH LOGS
only rotates a few log files.
SET @@...=...
sets it for anyone not yet logged in, but it will go away after the next restart. But that gives a clue... Do the SET
, and change my.cnf
; that way you are covered. Caveat: Not all settings can be performed via SET
.
New with MySQL 8.0...
SET PERSIST ...
will set the global setting and save it past restarts. Nearly all settings can be adjusted this way.
public static long byteArrayToLong(byte[] bytes) {
return ((long) (bytes[0]) << 56)
+ (((long) bytes[1] & 0xFF) << 48)
+ ((long) (bytes[2] & 0xFF) << 40)
+ ((long) (bytes[3] & 0xFF) << 32)
+ ((long) (bytes[4] & 0xFF) << 24)
+ ((bytes[5] & 0xFF) << 16)
+ ((bytes[6] & 0xFF) << 8)
+ (bytes[7] & 0xFF);
}
convert bytes array (long is 8 bytes) to long
It is because one of the DBs the column was created with " which makes its name case-sensitive.
Oracle Table Column Name : GoodRec Hive cannot recognize case sensitivity : ERROR thrown was - Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "GOODREC": invalid identifier
Solution : Rename Oracle column name to all caps.
There is one more way, i got the same situation in my project. i solved this way
List<Object[]> list = HQL.list();
In above hibernate query language i know at which place what are my objects so what i did is :
for(Object[] obj : list){
String val = String.valueOf(obj[1]);
int code =Integer.parseint(String.valueof(obj[0]));
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh
: ${1?"Usage: $0 ARGUMENT"}
# Script exits here if command-line parameter absent,
#+ with following error message.
# usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
An easy way that works:
private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach (var item in e.AddedCells)
{
var col = item.Column as DataGridColumn;
var fc = col.GetCellContent(item.Item);
if (fc is CheckBox)
{
Debug.WriteLine("Values" + (fc as CheckBox).IsChecked);
}
else if(fc is TextBlock)
{
Debug.WriteLine("Values" + (fc as TextBlock).Text);
}
//// Like this for all available types of cells
}
}
Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:
exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'
This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.
You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.
well for what its worth now... JsonProperty is ALSO used to specify getter and setter methods for the variable apart from usual serialization and deserialization. For example suppose you have a payload like this:
{
"check": true
}
and a Deserializer class:
public class Check {
@JsonProperty("check") // It is needed else Jackson will look got getCheck method and will fail
private Boolean check;
public Boolean isCheck() {
return check;
}
}
Then in this case JsonProperty annotation is neeeded. However if you also have a method in the class
public class Check {
//@JsonProperty("check") Not needed anymore
private Boolean check;
public Boolean getCheck() {
return check;
}
}
Have a look at this documentation too: http://fasterxml.github.io/jackson-annotations/javadoc/2.3.0/com/fasterxml/jackson/annotation/JsonProperty.html
The WPF DataGrid
has an IsReadOnly
property that you can set to True
to ensure that users cannot edit your DataGrid
's cells.
You can also set this value for individual columns in your DataGrid
as needed.
In my template driven form (Angular 6) I have the following workaround:
<div class='col-sm-2 form-group'>
<label for='amount'>Amount</label>
<input type='number'
id='amount'
name='amount'
required
[ngModel] = 1
[pattern] = "'^[1-9][0-9]*$'"
class='form-control'
#amountInput='ngModel'/>
<span class='text-danger' *ngIf="amountInput.touched && amountInput.invalid">
<p *ngIf="amountInput.errors?.required">This field is <b>required</b>!</p>
<p *ngIf="amountInput.errors?.pattern">This minimum amount is <b>1</b>!</p>
</span>
</div>
Alot of the above examples make use of directives and custom classes which do scale better in more complex forms, but if your looking for a simple numeric min, utilize pattern
as a directive and impose a regex restriction on positive numbers only.
The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.
You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.
Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/
The important parts: CSS use
.head {
overflow-x: hidden;
overflow-y: scroll;
width: 500px;
}
.lower {
overflow-x: auto;
overflow-y: scroll;
width: 500px;
height: 400px;
}
Notice overflow-y
must be the same on both head and lower.
And the Javascript...
var head = document.querySelector('.head');
var lower = document.querySelector('.lower');
lower.addEventListener('scroll', function (e) {
console.log(lower.scrollLeft);
head.scrollLeft = lower.scrollLeft;
});
This changes the focus of the EditText when the button is clicked:
public class MainActivity extends Activity {
private EditText e1,e2;
private Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText) findViewById(R.id.editText1);
e2=(EditText) findViewById(R.id.editText2);
e1.requestFocus();
b1=(Button) findViewById(R.id.one);
b2=(Button) findViewById(R.id.two);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
e1.requestFocus();
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
e2.requestFocus();
}
});
}
}
The other option to try is a straightforward
<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>
i.e. without {} but instead giving the direct image path
white-space: initial; Works for me.
If you look at the docs for bytes
, it points you to bytearray
:
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
So bytes
can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.
For encoding a string, I think that some_string.encode(encoding)
is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding)
-- there is no explicit verb when you use the constructor.
Edit: I checked the Python source. If you pass a unicode string to bytes
using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode
; so you're just skipping a level of indirection if you call encode
yourself.
Also, see Serdalis' comment -- unicode_string.encode(encoding)
is also more Pythonic because its inverse is byte_string.decode(encoding)
and symmetry is nice.
@GET
does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
With multiple return and multi parameter
string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
IEnumerable<dynamic> results = conn.Query(sql: "ProductSearch",
param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 },
commandType: CommandType.StoredProcedure);. // single result
var reader = conn.QueryMultiple("ProductSearch",
param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 },
commandType: CommandType.StoredProcedure); // multiple result
var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
var salarydetails = reader.Read<dynamic>().ToList();
}
public static string GetConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
The query you want to show as an example is:
SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';
04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.
If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.
To make things a bit clearer, try this:
SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;
That will show you the date, and its 12hr time.
A solution that works with all possible line endings including mixed ones and keeping empty lines as well can be achieved using two replaces and one split as follows
text.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/);
some code to test it
var CR = "\x0D"; // \r
var LF = "\x0A"; // \n
var mixedfile = "00" + CR + LF + // 1 x win
"01" + LF + // 1 x linux
"02" + CR + // 1 x old mac
"03" + CR + CR + // 2 x old mac
"05" + LF + LF + // 2 x linux
"07" + CR + LF + CR + LF + // 2 x win
"09";
function showarr (desc, arr)
{
console.log ("// ----- " + desc);
for (var ii in arr)
console.log (ii + ") [" + arr[ii] + "] (len = " + arr[ii].length + ")");
}
showarr ("using 2 replace + 1 split",
mixedfile.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/));
and the output
// ----- using 2 replace + 1 split
0) [00] (len = 2)
1) [01] (len = 2)
2) [02] (len = 2)
3) [03] (len = 2)
4) [] (len = 0)
5) [05] (len = 2)
6) [] (len = 0)
7) [07] (len = 2)
8) [] (len = 0)
9) [09] (len = 2)
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
Ommit
There are two ways to add references via VBA to your projects
1) Using GUID
2) Directly referencing the dll.
Let me cover both.
But first these are 3 things you need to take care of
a) Macros should be enabled
b) In Security settings, ensure that "Trust Access To Visual Basic Project" is checked
c) You have manually set a reference to `Microsoft Visual Basic for Applications Extensibility" object
Way 1 (Using GUID)
I usually avoid this way as I have to search for the GUID in the registry... which I hate LOL. More on GUID here.
Topic: Add a VBA Reference Library via code
Link: http://www.vbaexpress.com/kb/getarticle.php?kb_id=267
'Credits: Ken Puls
Sub AddReference()
'Macro purpose: To add a reference to the project using the GUID for the
'reference library
Dim strGUID As String, theRef As Variant, i As Long
'Update the GUID you need below.
strGUID = "{00020905-0000-0000-C000-000000000046}"
'Set to continue in case of error
On Error Resume Next
'Remove any missing references
For i = ThisWorkbook.VBProject.References.Count To 1 Step -1
Set theRef = ThisWorkbook.VBProject.References.Item(i)
If theRef.isbroken = True Then
ThisWorkbook.VBProject.References.Remove theRef
End If
Next i
'Clear any errors so that error trapping for GUID additions can be evaluated
Err.Clear
'Add the reference
ThisWorkbook.VBProject.References.AddFromGuid _
GUID:=strGUID, Major:=1, Minor:=0
'If an error was encountered, inform the user
Select Case Err.Number
Case Is = 32813
'Reference already in use. No action necessary
Case Is = vbNullString
'Reference added without issue
Case Else
'An unknown error was encountered, so alert the user
MsgBox "A problem was encountered trying to" & vbNewLine _
& "add or remove a reference in this file" & vbNewLine & "Please check the " _
& "references in your VBA project!", vbCritical + vbOKOnly, "Error!"
End Select
On Error GoTo 0
End Sub
Way 2 (Directly referencing the dll)
This code adds a reference to Microsoft VBScript Regular Expressions 5.5
Option Explicit
Sub AddReference()
Dim VBAEditor As VBIDE.VBE
Dim vbProj As VBIDE.VBProject
Dim chkRef As VBIDE.Reference
Dim BoolExists As Boolean
Set VBAEditor = Application.VBE
Set vbProj = ActiveWorkbook.VBProject
'~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
For Each chkRef In vbProj.References
If chkRef.Name = "VBScript_RegExp_55" Then
BoolExists = True
GoTo CleanUp
End If
Next
vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"
CleanUp:
If BoolExists = True Then
MsgBox "Reference already exists"
Else
MsgBox "Reference Added Successfully"
End If
Set vbProj = Nothing
Set VBAEditor = Nothing
End Sub
Note: I have not added Error Handling. It is recommended that in your actual code, do use it :)
EDIT Beaten by mischab1
:)
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
In the Java Control Panel, under the Security tab, uncheck "Enable Java content in the browser" and Apply it. Then re-check it and apply again. This worked for me, and I had been struggling with this issue for days.
Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/
.tinted-image {
width: 300px;
height: 200px;
background:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* bottom, image */
url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}
To print address in pointer to pointer:
printf("%p",emp1)
to dereference once and print the second address:
printf("%p",*emp1)
You can always verify with debugger, if you are on linux use ddd
and display memory, or just plain gdb
, you will see the memory address so you can compare with the values in your pointers.
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json
To change a cell value using a column name, one can use
iris$Sepal.Length[3]=999
I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync
. I tried both cygwin
and minGW
. It seems like rsync
is incompatible with git for windows
's version of ssh
.
Here is what worked for me: NFS.
Vagrant docs says:
NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.
This isn't true anymore. We can use vagrant-winnfsd
plugin nowadays. It's really simple to install:
vagrant plugin install vagrant-winnfsd
Vagrantfile
: config.vm.synced_folder ".", "/vagrant", type: "nfs"
Vagrantfile
: config.vm.network "private_network", type: "dhcp"
That's all I needed to make NFS
work. Laravel response time decreased from 500ms to 100ms for me.
This would be more performant than trimming the whole string, since you only need to check for at least a single non-space character existing
// Strempty checks whether string contains only whitespace or not
func Strempty(s string) bool {
if len(s) == 0 {
return true
}
r := []rune(s)
l := len(r)
for l > 0 {
l--
if !unicode.IsSpace(r[l]) {
return false
}
}
return true
}
Assuming you are on 10g, you can also use the MERGE statement. This allows you to insert the row if it doesn't exist and ignore the row if it does exist. People tend to think of MERGE when they want to do an "upsert" (INSERT if the row doesn't exist and UPDATE if the row does exist) but the UPDATE part is optional now so it can also be used here.
SQL> create table foo (
2 name varchar2(10) primary key,
3 age number
4 );
Table created.
SQL> ed
Wrote file afiedt.buf
1 merge into foo a
2 using (select 'johnny' name, null age from dual) b
3 on (a.name = b.name)
4 when not matched then
5 insert( name, age)
6* values( b.name, b.age)
SQL> /
1 row merged.
SQL> /
0 rows merged.
SQL> select * from foo;
NAME AGE
---------- ----------
johnny
The container
class is intentionally not 100% width. It is different fixed widths depending on the width of the viewport.
If you want to work with the full width of the screen, use .container-fluid
:
Bootstrap 3:
<body>
<div class="container-fluid">
<div class="row">
<div class="col-lg-6"></div>
<div class="col-lg-6"></div>
</div>
<div class="row">
<div class="col-lg-8"></div>
<div class="col-lg-4"></div>
</div>
<div class="row">
<div class="col-lg-12"></div>
</div>
</div>
</body>
Bootstrap 2:
<body>
<div class="row">
<div class="span6"></div>
<div class="span6"></div>
</div>
<div class="row">
<div class="span8"></div>
<div class="span4"></div>
</div>
<div class="row">
<div class="span12"></div>
</div>
</body>
Lamp stack stands for Linux Apache Mysql PHP
there is also Mean Stack MongoDB ExpressJS AngularJS NodeJS
First and Last Date of current Month In the moment.js
console.log("current month first date");
const firstdate = moment().startOf('month').format('DD-MM-YYYY');
console.log(firstdate);
console.log("current month last date");
const lastdate=moment().endOf('month').format("DD-MM-YYYY");
console.log(lastdate);
Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.
I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?
The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {...
- which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.
function parseMyXML ($xml) { //pass in an XML string
$myXML = new XMLReader();
$myXML->xml($xml);
while ($myXML->read()) { //start reading.
if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myXML->name; //make $tag contain the name of the tag
switch ($tag) {
case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
$variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
break;
case 'Tag2': //this tag contains child elements, of which we only want one.
while($myXML->read()) { //so we tell it to keep reading
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
$variable2 = $myXML->readInnerXML(); //...put it in $variable2.
break;
}
}
break;
case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
while($myXML->read()) {
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
$variable3 = $myXML->readInnerXML();
break;
} else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
$variable4 = $myXML->readInnerXML();
break;
}
}
break;
}
}
}
$myXML->close();
}
You might also be interested in C, it will also delete the end of line like D, but additionally it will put you in Insert mode at the cursor location.
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
I'm answering because the previous answers have stopped working with the latest version of jQuery. I don't know when it stopped working, but the documentation says that .prop() has been the preferred method to get/set properties since jQuery 1.6.
This is how I got it to work (with jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
I am using knockoutjs and the change bindings weren't firing with the above code, so I added .change() to the end.
Here's what I needed for my solution:
$('select option:nth-child(1)').prop("selected", true).change();
See .prop() notes in the documentation here: http://api.jquery.com/prop/
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
You are probably overrunning beyond the allocated mem somewhere. then the underlying sw doesn't pick up on it until you call malloc
There may be a guard value clobbered that is being caught by malloc.
edit...added this for bounds checking help
http://www.lrde.epita.fr/~akim/ccmp/doc/bounds-checking.html
PIPESTATUS[@] must be copied to an array immediately after the pipe command returns. Any reads of PIPESTATUS[@] will erase the contents. Copy it to another array if you plan on checking the status of all pipe commands. "$?" is the same value as the last element of "${PIPESTATUS[@]}", and reading it seems to destroy "${PIPESTATUS[@]}", but I haven't absolutely verified this.
declare -a PSA
cmd1 | cmd2 | cmd3
PSA=( "${PIPESTATUS[@]}" )
This will not work if the pipe is in a sub-shell. For a solution to that problem,
see bash pipestatus in backticked command?
_JAVA_OPTIONS="-Xmx3G" mvn clean install
You can use a temporary deletion list:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine()
) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\r\n");
It's worth noting that you aren't going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
Here is a sample code showing how to align text using UILabel:
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;
You can read more about it here UILabel
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.3D case
Modifying Mohsen's answer for 3D array:
[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
// from MongoDate object to Javascript Date object
var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
dt.setSeconds(MongoDate.sec);
Try replacing this
var query = context.Search(id, searchText);
with
var query = context.Search(id, searchText).tolist();
and everything will work well.
Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.
var obj = '{ firstName:"John", lastName:"Doe" }';_x000D_
_x000D_
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {_x000D_
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';_x000D_
});_x000D_
_x000D_
obj = JSON.parse(jsonStr); //converts to a regular object_x000D_
_x000D_
console.log(obj.firstName); // expected output: John_x000D_
console.log(obj.lastName); // expected output: Doe
_x000D_
This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"] }}';_x000D_
_x000D_
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {_x000D_
return '"' + s.substring(0, s.length-1) + '":';_x000D_
});_x000D_
_x000D_
var obj = JSON.parse(jsonStr);_x000D_
console.log(obj.favorites.movies[0]); // expected output: star wars
_x000D_
.then
function of promiseB receives what is returned from .then
function of promiseA.
here promiseA is returning is a number, which will be available as number
parameter in success function of promiseB. which will then be incremented by 1
In addition to the wrong modifier, which port of gcc to Windows? mingw uses the Microsoft C library and I seem to remember that this library has no support for 80bits long double (microsoft C compiler use 64 bits long double for various reasons).
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
Create the user with a password :
http://www.postgresql.org/docs/current/static/sql-createuser.html
CREATE USER name [ [ WITH ] option [ ... ] ]
where option can be:
SUPERUSER | NOSUPERUSER
| CREATEDB | NOCREATEDB
| CREATEROLE | NOCREATEROLE
| CREATEUSER | NOCREATEUSER
| INHERIT | NOINHERIT
| LOGIN | NOLOGIN
| REPLICATION | NOREPLICATION
| CONNECTION LIMIT connlimit
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| VALID UNTIL 'timestamp'
| IN ROLE role_name [, ...]
| IN GROUP role_name [, ...]
| ROLE role_name [, ...]
| ADMIN role_name [, ...]
| USER role_name [, ...]
| SYSID uid
Then grant the user rights on a specific database :
http://www.postgresql.org/docs/current/static/sql-grant.html
Example :
grant all privileges on database db_name to someuser;
Add a string at the end of your URL to break the cache. I usually do (with PHP):
<script src="/my/js/file.js?<?=time()?>"></script>
So that it reloads every time while I'm working on it, and then take it off when it goes into production. In reality I abstract this out a little more but the idea remains the same.
If you check out the source of this website, they append the revision number at the end of the URL in a similar fashion to force the changes upon us whenever they update the javascript files.
From Google OAuth2.0 for Client documentation,
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
nums = range(10)
for i in range(0, len(nums)-1, 2):
print nums[i]
Kinda dirty but it works.
I add the following code to /root/.bashrc to run the code only once,
Please commit the container to the image before run this script, otherwise the 'docker_services' file will be created in the images and no service will be run.
if [ ! -e /var/run/docker_services ]; then
echo "Starting services"
service mysql start
service ssh start
service nginx start
touch /var/run/docker_services
fi
There are no post/pre increment/decrement operators in python like in languages like C.
We can see ++
or --
as multiple signs getting multiplied, like we do in maths (-1) * (-1) = (+1).
E.g.
---count
Parses as
-(-(-count)))
Which translates to
-(+count)
Because, multiplication of -
sign with -
sign is +
And finally,
-count
I saw this thread when I was trying to split a file in files with 100 000 lines. A better solution than sed for that is:
split -l 100000 database.sql database-
It will give files like:
database-aaa
database-aab
database-aac
...
You will need to define "special characters", but it's likely that for some string s
you mean:
import re
if re.match(r'^\w+$', s):
# s is good-to-go
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
As @nasreddine answered or you can use /d
cd /d d:\Docs\Java
For more help on the cd
command use:
C:\Documents and Settings\kenny>help cd
Displays the name of or changes the current directory.
CHDIR [/D] [drive:][path] CHDIR [..] CD [/D] [drive:][path] CD [..]
.. Specifies that you want to change to the parent directory.
Type CD drive: to display the current directory in the specified drive. Type CD without parameters to display the current drive and directory.
Use the /D switch to change current drive in addition to changing current directory for a drive.
If Command Extensions are enabled CHDIR changes as follows:
The current directory string is converted to use the same case as the on disk names. So CD C:\TEMP would actually set the current directory to C:\Temp if that is the case on disk.
CHDIR command does not treat spaces as delimiters, so it is possible to CD into a subdirectory name that contains a space without surrounding the name with quotes. For example:
cd \winnt\profiles\username\programs\start menu
is the same as:
cd "\winnt\profiles\username\programs\start menu"
which is what you would have to type if extensions were disabled.
You can use:
Insert into Event(Description,Date) values('teste', GETDATE());
Also, you can change your table so that 'Date' has a default, "GETDATE()"
In my case opening 'Help' >> "Install New Software" had no entries for any URLs (previous url's were not there) - so I Manually added 'em. And updated ... and Voilaaaa !! Above posts have been very helpful in resolving this issue for me.
As you'll probably want to do this often, add aliases into your .bashrc file, like:
alias cdc='cd /cygdrive/c'
alias cdp='cd /cygdrive/p'
Then you can just type on the command line:
cdc
I know this is an older question but this past week I started to get a similar problem, so I leave here some notes regarding the solution that fits me.
This happened only in some Windows machines using even the last JRE to date (1.8.0_45).
The Java Web Start started to load but nothing happened and none of the previous solution attempts worked.
After some digging i've found this thread, which gives the same setup and a great explanation.
https://community.oracle.com/thread/3676876
So, in conclusion, it was a memory problem in x86 JRE and since our JNLP's max heap was defined as 1024MB, we changed to 780MB as suggested and it was fixed.
However, if you need more than 780MB, can always try launching in a x64 JRE version.
The sanctioned way of creating and using child processes is through the subprocess module.
import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl
The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.
To get the property of the object or the "array key" or "array index" depending on what your native language is..... Use the Object.keys() method.
Important, this is only compatible with "Modern browsers":
So if your object is called, myObject...
var c = 0;
for(c in myObject) {
console.log(Object.keys(myObject[c]));
}
Walla! This will definitely work in the latest firefox and ie11 and chrome...
Here is some documentation at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
select
could contain optgroup
which takes one line each:
<select id="list">
<optgroup label="Group 1">
<option value="1">1</option>
</optgroup>
<optgroup label="Group 2">
<option value="2">2</option>
<option value="3">3</option>
</optgroup>
</select>
<script>
const l = document.getElementById("list")
l.setAttribute("size", l.childElementCount + l.length)
</script>
In this example total size
is (1+1)+(1+2)=5
.
CodeIgniter Active Records do not currently support sub-queries, However I use the following approach:
#Create where clause
$this->db->select('id_cer');
$this->db->from('revokace');
$where_clause = $this->db->_compile_select();
$this->db->_reset_select();
#Create main query
$this->db->select('*');
$this->db->from('certs');
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
_compile_select() and _reset_select() are two undocumented (AFAIK) methods which compile the query and return the sql (without running it) and reset the query.
On the main query the FALSE in the where clause tells codeigniter not to escape the query (or add backticks etc) which would mess up the query. (The NULL is simply because the where clause has an optional second parameter we are not using)
However you should be aware as _compile_select() and _reset_select() are not documented methods it is possible that there functionality (or existence) could change in future releases.
Here is some production code that sends the file to an ftp (may be a good solution for you):
// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
// Connecting to website.
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "[email protected]:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://@ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);