To solve this issue you need below three steps:
Set page encoding to UTF-8 like below:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8" %>
Set filter in web.xml file as below:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
This isn't much of an answer, but how about using a Horizontal Scroll View?
There are two methods to setting and using variables within for loops and parentheses scope.
setlocal enabledelayedexpansion
see setlocal /?
for help. This only works on XP/2000 or newer versions of Windows.
then use !variable!
instead of %variable%
inside the loop...
Create a batch function using batch goto labels :Label
.
Example:
for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
goto End
:Foo
set z=%1
echo %z%
echo %1
goto :eof
:End
Batch functions are very useful mechanism.
Ideone supports Python 2.6 and Python 3
Just use the location.host property
switch (location.host) {
case "xxx.local":
settings = ...
break;
case "xxx.dev.yyy.com":
settings = ...
break;
}
In my case, I wanted to center in a parent container with position: absolute.
<div class="absolute-container">
<div class="parent-container">
<div class="centered-content">
My content
</div>
</div>
</div>
I had to add some positioning for top, bottom, left & right.
.absolute-container {
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
}
.parent-container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
.centered-content {
display: table-cell;
text-align: center;
vertical-align: middle
}
A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.
I tried pretty much every suggestion on this page, but had to delete visual studio 2017 completely off my machine. I reinstalled the latest version (2019) and it magically worked. I hope this helps someone in the future.
I had to COPY
and untar java package in my docker image.
When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz
This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!
Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.
---=== The table & its data
CREATE TABLE dbo.Rates (
PkId int,
name varchar(10),
rate decimal(10,2)
)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)
Here's the solution:
---=== The solution
CREATE PROCEDURE dbo.GetRate
@PkId int
AS
BEGIN
DECLARE @tempTable TABLE (
PkId int,
name varchar(10),
rate decimal(10,2)
)
--- [1] Insert default values into @tempTable. PkId=0 is dummy value
INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)
--- [2] Update the single row in @tempTable with the actual value.
--- This only happens if a match is found
UPDATE @tempTable
SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
FROM @tempTable t INNER JOIN dbo.Rates x
ON t.PkId = 0
WHERE x.PkId = @PkId
SELECT * FROM @tempTable
END
Test the code:
EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1
EXEC dbo.GetRate @PkId=12314 --- returns default values
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
If you just don't need anything as your type, you can use void. This can be used for implementing functions, or actions. You could then do something like this:
interface Action<T> {
public T execute();
}
abstract class VoidAction implements Action<Void> {
public Void execute() {
executeInternal();
return null;
}
abstract void executeInternal();
}
Or you could omit the abstract class, and do the return null in every action that doesn't require a return value yourself.
You could then use those actions like this:
Given a method
private static <T> T executeAction(Action<T> action) {
return action.execute();
}
you can call it like
String result = executeAction(new Action<String>() {
@Override
public String execute() {
//code here
return "Return me!";
}
});
or, for the void action (note that you're not assigning the result to anything)
executeAction(new VoidAction() {
@Override
public void executeInternal() {
//code here
}
});
What I need is a function which prints an object (obj), but only if global variable verbose is true, else it does nothing.
I want to be able to change the global parameter "verbose" at any time. Simplicity and readability to me are of paramount importance. So I would proceed as the following lines indicate:
ak@HP2000:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> verbose = True
>>> def vprint(obj):
... if verbose:
... print(obj)
... return
...
>>> vprint('Norm and I')
Norm and I
>>> verbose = False
>>> vprint('I and Norm')
>>>
Global variable "verbose" can be set from the parameter list, too.
While the above responses provide most of the answer it is useful--even this late to the question--to provide the full answer, to wit:
Array sub-expression (see about_arrays)
Forces the value to be an array, even if a singleton or a null, e.g. $a = @(ps | where name -like 'foo')
Hash initializer (see about_hash_tables)
Initializes a hash table with key-value pairs, e.g.
$HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"; WhatIf = $true }
Splatting (see about_splatting)
Let's you invoke a cmdlet with parameters from an array or a hash-table rather than the more customary individually enumerated parameters, e.g. using the hash table just above, Copy-Item @HashArguments
Here strings (see about_quoting_rules)
Let's you create strings with easily embedded quotes, typically used for multi-line strings, e.g.:
$data = @"
line one
line two
something "quoted" here
"@
Because this type of question (what does 'x' notation mean in PowerShell?) is so common here on StackOverflow as well as in many reader comments, I put together a lexicon of PowerShell punctuation, just published on Simple-Talk.com. Read all about @ as well as % and # and $_ and ? and more at The Complete Guide to PowerShell Punctuation. Attached to the article is this wallchart that gives you everything on a single sheet:
In fact I have the problem with a form on each row of a table, with javascript (actually jquery) :
like Lothre1 said, "some browsers in the process of rendering will close form tag right after the declaration leaving inputs outside of the element"
which makes my input fields OUTSIDE the form, therefore I can't access the children of my form through the DOM with JAVASCRIPT..
typically, the following JQUERY code won't work :
$('#id_form :input').each(function(){/*action*/});
// this is supposed to select all inputS
// within the form that has an id ='id_form'
BUT the above exemple doesn't work with the rendered HTML :
<table>
<form id="id_form"></form>
<tr id="tr_id">
<td><input type="text"/></td>
<td><input type="submit"/></td>
</tr>
</table>
I'm still looking for a clean solution (though using the TR 'id' parameter to walk the DOM would fix this specific problem)
dirty solution would be (for jquery):
$('#tr_id :input').each(function(){/*action*/});
// this will select all the inputS
// fields within the TR with the id='tr_id'
the above exemple will work, but it's not really "clean", because it refers to the TR instead of the FORM, AND it requires AJAX ...
EDIT : complete process with jquery/ajax would be :
//init data string
// the dummy init value (1=1)is just here
// to avoid dealing with trailing &
// and should not be implemented
// (though it works)
var data_str = '1=1';
// for each input in the TR
$('#tr_id :input').each(function(){
//retrieve field name and value from the DOM
var field = $(this).attr('name');
var value = $(this).val();
//iterate the string to pass the datas
// so in the end it will render s/g like
// "1=1&field1_name=value1&field2_name=value2"...
data_str += '&' + field + '=' + value;
});
//Sendind fields datawith ajax
// to be treated
$.ajax({
type:"POST",
url: "target_for_the_form_treatment",
data:data_string,
success:function(msg){
/*actions on success of the request*/
});
});
this way, the "target_for_the_form_treatment" should receive POST data as if a form was sent to him (appart from the post[1] = 1, but to implement this solution i would recommand dealing with the trailing '&' of the data_str instead).
still I don't like this solution, but I'm forced to use TABLE structure because of the dataTables jquery plugin...
Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.
And it also limited by my using legacy compatibility mode vs unittest
scripts, so not guaranteeing it would work with native pytest.
Here goes:
subset_tests_directory
.ln -s tests_directory/foo.py
ln -s tests_directory/bar.py
be careful about imports which implicitly assume files are in test_directory
. I had to fix several of those by running python foo.py
, from within subset_tests_directory
and correcting as needed.
Once the test scripts execute correctly, just cd subset_tests_directory
and pytest
there. Pytest will only pick up the scripts it sees.
Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py
then pytest subset*.py
. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.
this.setState creates an infinite loop when used in ComponentDidUpdate when there is no break condition in the loop. You can use redux to set a variable true in the if statement and then in the condition set the variable false then it will work.
Something like this.
if(this.props.route.params.resetFields){
this.props.route.params.resetFields = false;
this.setState({broadcastMembersCount: 0,isLinkAttached: false,attachedAffiliatedLink:false,affilatedText: 'add your affiliate link'});
this.resetSelectedContactAndGroups();
this.hideNext = false;
this.initialValue_1 = 140;
this.initialValue_2 = 140;
this.height = 20
}
I have the same problem....
I change my project name and i have this problem...my solution was the checking project refences and use /
in my web.xml (instead of /*
)
For Writing Excel
For Reading Excel
A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.
All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:
module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
}, }
Require the file in the server.
const configstrp = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;
and connect as such
if (ngrok) {
console.log('If nGronk')
ngrok.connect(
{
addr: configstrp.ngrok.port,
subdomain: configstrp.ngrok.subdomain,
authtoken: configstrp.ngrok.authtoken,
host_header:3000
},
(err, url) => {
if (err) {
} else {
}
}
);
}
Do not pass a subdomain if you do not have a custom domain
My solution below is in es6 because I made use of const
if you prefer es5 you can replace all const
with var
.
const str = " Hello World! ";_x000D_
// const str = " ";_x000D_
_x000D_
checkForWhiteSpaces(str);_x000D_
_x000D_
function checkForWhiteSpaces(args) {_x000D_
const trimmedString = args.trim().length;_x000D_
console.log(checkStringLength(trimmedString)) _x000D_
return checkStringLength(trimmedString) _x000D_
}_x000D_
_x000D_
// If the browser doesn't support the trim function_x000D_
// you can make use of the regular expression below_x000D_
_x000D_
checkForWhiteSpaces2(str);_x000D_
_x000D_
function checkForWhiteSpaces2(args) {_x000D_
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;_x000D_
console.log(checkStringLength(trimmedString)) _x000D_
return checkStringLength(trimmedString)_x000D_
}_x000D_
_x000D_
function checkStringLength(args) {_x000D_
return args > 0 ? "not empty" : "empty string";_x000D_
}
_x000D_
building on top of above answers, here is what I plagiarized and came up with. Also added memory logging.
#import <mach/mach.h>
#ifdef DEBUG
# define DebugLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DebugLog(...)
#endif
#define AlwaysLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#ifdef DEBUG
# define AlertLog(fmt, ...) { \
UIAlertView *alert = [[UIAlertView alloc] \
initWithTitle : [NSString stringWithFormat:@"%s(Line: %d) ", __PRETTY_FUNCTION__, __LINE__]\
message : [NSString stringWithFormat : fmt, ##__VA_ARGS__]\
delegate : nil\
cancelButtonTitle : @"Ok"\
otherButtonTitles : nil];\
[alert show];\
}
#else
# define AlertLog(...)
#endif
#ifdef DEBUG
# define DPFLog NSLog(@"%s(%d)", __PRETTY_FUNCTION__, __LINE__);//Debug Pretty Function Log
#else
# define DPFLog
#endif
#ifdef DEBUG
# define MemoryLog {\
struct task_basic_info info;\
mach_msg_type_number_t size = sizeof(info);\
kern_return_t e = task_info(mach_task_self(),\
TASK_BASIC_INFO,\
(task_info_t)&info,\
&size);\
if(KERN_SUCCESS == e) {\
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; \
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \
DebugLog(@"%@ bytes", [formatter stringFromNumber:[NSNumber numberWithInteger:info.resident_size]]);\
} else {\
DebugLog(@"Error with task_info(): %s", mach_error_string(e));\
}\
}
#else
# define MemoryLog
#endif
Check this one. hope it will help full for you.
.row-fix { margin-bottom:20px;}
.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}
.row-fix .two-col{ background:none;}
.two-col > [class*="col"]{ height:40px; background:#ccc;}
.two-col > .col1{margin-bottom:20px;}
I imagine a simple Replace in Files (Ctrl+Shift+H) will just about do the trick; simply replace namespace DemoApp
with namespace MyApp
. After that, build the solution and look for compile errors for unknown identifiers. Anything that fully qualified DemoApp
will need to be changed to MyApp
.
Several things here.
First off, you're defining your CSS in 3 places!
In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.
I suggest you update your code in your ASP form from
<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;"
class="style6">
to this:
<td class="style6">
And then update your css too
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
This removes the inline.
Now, to move it from the head of the webForm.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
<link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td class="style6">
<asp:Menu ID="Menu1" runat="server">
<Items>
<asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
<asp:MenuItem Text="Compliance" Value="Compliance">
<asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
<asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
<asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
</Items>
</asp:Menu>
</td>
</tr>
<tr>
<td class="style6">
<img alt="South University'" class="style7"
src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
</tr>
<tr>
<td class="style2">
<table class="style3">
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="color: #FFFFFF; background-color: #A3A3A3">
This is the footer.</td>
</tr>
</table>
</form>
</body>
</html>
Now, in a new file called master.css (in your css folder) add
ul {
list-style-type:none;
margin:0;
padding:0;
}
li {
display:inline;
padding:20px;
}
.style1
{
width: 100%;
}
.style2
{
height: 459px;
}
.style3
{
width: 100%;
height: 100%;
}
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
width: 345px;
height: 73px;
}
None of these answers work when trying to do the following:
If you insert a 'perform' command after the moveToElement, it moves to the element, and the sub-menu item shows for a brief period, but that is not a hover. The hidden element immediately disappears before it can be found resulting in a ElementNotFoundException. I tried two things:
Actions builder = new Actions(driver);
builder.moveToElement(hoverElement).perform();
builder.moveToElement(clickElement).click().perform();
This did not work for me. The following worked for me:
Actions builder = new Actions(driver);
builder.moveToElement(hoverElement).perform();
By locator = By.id("clickElementID");
driver.click(locator);
Using the Actions to hover and the standard WebDriver click, I could hover and then click.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
If someone was looking for a way to remove all instances of repeated values, see "How can I efficiently extract repeated elements in a Ruby array?".
a = [1, 2, 2, 3]
counts = Hash.new(0)
a.each { |v| counts[v] += 1 }
p counts.select { |v, count| count == 1 }.keys # [1, 3]
You can use the PHP function apc_clear_cache
.
Calling apc_clear_cache()
will clear the system cache and calling apc_clear_cache('user')
will clear the user cache.
In HTML, the selected option is represented by the presence of the selected
attribute on the <option>
element like so:
<option ... selected>...</option>
Or if you're HTML/XHTML strict:
<option ... selected="selected">...</option>
Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:
request.setAttribute("selectedDept", selectedDept);
then this should do:
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
</c:forEach>
</select>
on os x these are the same for me... could this maybe be extra "\r" in windows?
in any case you may be better of with:
contents = File.read("e.tgz")
newFile = File.open("ee.tgz", "w")
newFile.write(contents)
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
Meanwhile there is another way of how to do it with f-strings:
cursor.execute(f"INSERT INTO table VALUES {var1}, {var2}, {var3},")
I believe this is the most updated answer now and it worked for me ( Guest Additions Version: 5.0.6
, VirtualBox Version: 4.3.16
, Ubuntu 14.04 LTS
)
https://github.com/mitchellh/vagrant/issues/3341#issuecomment-144271026
Basically i says:
Simple and Quick Solution for Failed to mount folders in Linux guest issue.
Add the following line to your Homestead/Vagrantfile:
config.vbguest.auto_update = false
Your Homestead/Vagrantfile should looks like this:
/...
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# To avoid install and uninstall VBoxGuessAdditions during vagrant provisioning.
config.vbguest.auto_update = false
.../
Save it and execute
$ vagrant destroy --force
$ vagrant up
For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.
I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.
Hopefully this helps someone out in the same predicament.
It's possible with the use of Brandon Aaron's Mousewheel plugin.
Here's a demo: http://jsbin.com/jivutakama/edit?html,js,output
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});
You can use http or https.
https://ip2c.org/XXX.XXX.XXX.XXX or https://ip2c.org/?ip=XXX.XXX.XXX.XXX |
https://ip2c.org/s or https://ip2c.org/self or https://ip2c.org/?self |
Reference: https://about.ip2c.org/#inputs
set this jquery min js
script src="http://code.jquery.com/jquery-1.10.1.min.js"
in wp-admin/admin-header.php
Try to avoid formatting in your query. You should return your data in a raw format and let the receiving application (e.g. a reporting service or end user app) do the formatting, i.e. rounding and so on.
Formatting the data in the server makes it harder (or even impossible) for you to further process your data. You usually want export the table or do some aggregation as well, like sum, average etc. As the numbers arrive as strings (varchar), there is usually no easy way to further process them. Some report designers will even refuse to offer the option to aggregate these 'numbers'.
Also, the end user will see the country specific formatting of the server instead of his own PC.
Also, consider rounding problems. If you round the values in the server and then still do some calculations (supposing the client is able to revert the number-strings back to a number), you will end up getting wrong results.
This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();
I believe telnet 74.255.12.25 8089
. Why don't u try both
Here's a great reason to use objectForKey:
wherever possible instead of valueForKey:
- valueForKey:
with an unknown key will throw NSUnknownKeyException
saying "this class is not key value coding-compliant for the key ".
There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.
Crude, maybe, but it definitely should work.
Though I like Justin's response, I feel it more accurately represents a filter rather than a search. What if I want to know about cars with names that start with cam?
The way I see it, you could build it into the way you handle specific resources:
/cars/cam*
Or, you could simply add it into the filter:
/cars/doors/4/name/cam*/colors/red,blue,green
Personally, I prefer the latter, however I am by no means an expert on REST (having first heard of it only 2 or so weeks ago...)
for md5 vARCHAR(32) is appropriate. For those using AES better to use varbinary.
You can also try:
create table new_table as
select * from table1
union
select * from table2
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Being aware of the two(?) different types of windows available in SQL Server Management Studio.
If you right-click a table and select Open
it will use an editable grid that you can modify the cells in. If you right-click the database and select New Query
it will create a slightly different type of window that you can't modify the grid in but it gives you a few other nice features, such as allowing different code snippets and letting you execute them separately by selection.
Can you output that data in the cells as you are creating the table?
so your table would look like this:
<table>
<thead>...</thead>
<tbody>
<tr><td data-row='1' data-column='1'>value</td>
<td data-row='1' data-column='2'>value</td>
<td data-row='1' data-column='3'>value</td></tr>
<tbody>
</table>
then it would be a simple matter
$("td").click(function(event) {
var row = $(this).attr("data-row");
var col = $(this).attr("data-col");
}
Try this
$('#add_here').text('new-dynamic-text');
git diff
can show you the difference between two commits:
git diff mybranch master -- myfile.cs
Or, equivalently:
git diff mybranch..master -- myfile.cs
Note you must specify the relative path to the file. So if the file were in the src directory, you'd say src/myfile.cs
instead of myfile.cs
.
Using the latter syntax, if either side is HEAD
it may be omitted (e.g. master..
compares master
to HEAD
).
You may also be interested in mybranch...master
(from git diff
docs):
This form is to view the changes on the branch containing and up to the second
<commit>
, starting at a common ancestor of both<commit>
.git diff A...B
is equivalent togit diff $(git-merge-base A B) B
.
In other words, this will give a diff of changes in master
since it diverged from mybranch
(but without new changes since then in mybranch
).
In all cases, the --
separator before the file name indicates the end of command line flags. This is optional unless Git will get confused if the argument refers to a commit or a file, but including it is not a bad habit to get into. See https://stackoverflow.com/a/13321491/54249 for a few examples.
The same arguments can be passed to git difftool
if you have one configured.
I solved it through googling:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.
Apparently, Chrome addresses a key in Windows registry when it looks for a Java Environment. Since the plugin installs the JRE, this key is set to a JRE path and therefore needs to be edited if you want Chrome to work with the JDK.
regedit
to edit the registry.Edit "Path" so that it matches the corresponding dll inside your JDK installation:
REGEDIT 4
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"Path"="C:\Program Files (x86)\Java\jdk1.6.0_29\jre\bin\new_plugin\npjp2.dll"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="160_29"
Save file.
The REGEDIT 4
prefix at the top of the file might only be required for Windows 7 64-bit.
Just in case anyone are using FragmentStatePagerAdapter based adapter(which will let ViewPager create minimum pages needed for display purpose, at most 2 for my case), @rui.araujo's answer of overwriting getItemPosition in your adapter will not cause significant waste, but it still can be improved.
In pseudo code:
public int getItemPosition(Object object) {
YourFragment f = (YourFragment) object;
YourData d = f.data;
logger.info("validate item position on page index: " + d.pageNo);
int dataObjIdx = this.dataPages.indexOf(d);
if (dataObjIdx < 0 || dataObjIdx != d.pageNo) {
logger.info("data changed, discard this fragment.");
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
For swift 3.0 You can also change gesture long press time duration
label.isUserInteractionEnabled = true
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:)))
longPress.minimumPressDuration = 0.2
label.addGestureRecognizer(longPress)
Ok, it is apocalyptical 2020 now, and you can find these methods in NuGet package System.Net.Http.Json
. But beware that it uses System.Text.Json
internally.
And if you really need to find out which API resides where, just use https://apisof.net/
Example of using a function() in bash:
#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
echo "Usage: $0 filename"
exit 1
}
# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
local f="$1"
[[ -f "$f" ]] && return 0 || return 1
}
# invoke usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage
# Invoke is_file_exits
if ( is_file_exists "$1" )
then
echo "File found: $1"
else
echo "File not found: $1"
fi
You must specify that the friend is a template function:
MyClass<T>& operator+=<>(const MyClass<T>& classObj);
See this C++ FAQ Lite answer for details.
I would like to add something to brilliant @AmiNadimi answer for everyone who going implement his solution in .NET Core 3:
First of all, you should change signature of SignIn
method in UserManager
class from:
public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
to:
public async Task SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
It's because you should never use async void
, especially if you work with HttpContext
. Source: Microsoft Docs
The last, but not least, your Configure()
method in Startup.cs
should contains app.UseAuthorization
and app.UseAuthentication
in proper order:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
onunload
(or onbeforeunload
) cannot redirect the user to another page. This is for security reasons.
If you want to show a prompt before the user leaves the page, use onbeforeunload
:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
You can use onunload
to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload
):
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
$(window).unload(function(){
alert('Bye.');
});
You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.
Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx
See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx
Example script for 'TestUser' to use the profile named 'General Admin Mail'.
USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'General Admin Mail',
@principal_name = 'TestUser',
@is_default = 1 ;
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})
This is an old post, but for video you might want to consider using MPEG-DASH to obfuscate your files. Plus, it will provide a better streaming experience for your users without the need for a separate streaming server. More info in this post: How to disable video/audio downloading in web pages?
For example: com.paresh.mainpackage
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
HEAD is just a special pointer that points to the local branch you’re currently on.
From the Pro Git book, chapter 3.1 Git Branching - Branches in a Nutshell, in the section Creating a New Branch:
What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the git branch command:
$ git branch testing
This creates a new pointer at the same commit you’re currently on
How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch.
old question but just to mention the solution for MVC5 developers, you can use the Model
property same as in view.
The Model
property in both view and layout is assosiated with the same ViewDataDictionary
object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName
in the layout.
But notice that when you use @Model.XXX
in the layout the intelliSense context menu will not appear because the Model
here is a dynamic object just like ViewBag
.
You may add a div with position:absolute
within a table/div with position:relative
. For example, if you want your overlay div to be shown at the bottom right of the main text div (width and height can be removed):
<div style="position:relative;width:300px;height:300px;background-color:#eef">
<div style="position:absolute;bottom:0;right:0;width:100px;height:100px;background-color:#fee">
I'm over you!
</div>
Your main text
</div>
See it here: http://jsfiddle.net/bptvt5kb/
If your OS is Unix base use this code:
import os
def check_process(name):
output = []
cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
os.system(cmd % name)
with open('/tmp/out', 'r') as f:
line = f.readline()
while line:
output.append(line.strip())
line = f.readline()
if line.strip():
output.append(line.strip())
return output
Then call it and pass it a process name to get all PIDs.
>>> check_process('firefox')
['499', '621', '623', '630', '11733']
If you're developing some kind of your own array abstraction, you can get O(1) if you store smallest added value in additional attribute and compare it every time a new item is put into array.
It should look something like this:
class MyArray
{
public:
MyArray() : m_minValue(INT_MAX) {}
void add(int newValue)
{
if (newValue < m_minValue) m_minValue = newValue;
list.push_back( newValue );
}
int min()
{
return m_minValue;
}
private:
int m_minValue;
std::list m_list;
}
extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(vc: rootViewController)
}
return nil
}
static func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
if let navigationController = vc as? UINavigationController,
let visibleController = navigationController.visibleViewController {
return UIWindow.getVisibleViewControllerFrom( vc: visibleController )
} else if let tabBarController = vc as? UITabBarController,
let selectedTabController = tabBarController.selectedViewController {
return UIWindow.getVisibleViewControllerFrom(vc: selectedTabController )
} else {
if let presentedViewController = vc.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController)
} else {
return vc
}
}
}
}
Usage:
if let topController = window.visibleViewController() {
println(topController)
}
You may be able to do it on-the-fly
crontab -l | { cat; echo "0 0 0 0 0 some entry"; } | crontab -
crontab -l
lists the current crontab jobs, cat
prints it, echo
prints the new command and crontab -
adds all the printed stuff into the crontab file. You can see the effect by doing a new crontab -l
.
In case of your python being an pyenv
installed one, where pyenv is installed with homebrew on macOS, there might me a newer version available which fixes this:
$ brew update && brew upgrade pyenv
Then reinstalling the python version:
$ pyenv install 3.7.2
pyenv: /Users/luckydonald/.pyenv/versions/3.7.2 already exists
continue with installation? (y/N)
Note, it is a bit dirty to overwrite the existing python install like that, but in my case it did work out.
I recently had to find out why this didn't work too.
The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="parent.abc();" href="#">Click Me</a>
</iframe>
</body>
Hope this helps anyone that stumbles upon this issue again.
Check out std::stringstream
.
.NET has an easy function to do that in the String
class.
Just use:
.ToString().PadLeft(4, '0') // that will fill your number with 0 on the left, up to 4 length
int i = 1;
i.toString().PadLeft(4,'0') // will return "0001"
<div style="margin: 0 auto; text-align: center; overflow: hidden;">
<div style="float: left;">
<a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
caption 1
</div>
<div style="float: left;">
<a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
caption 2
</div>
</div>
Here's some simple code to add a time out to your recv
function using poll
in C:
struct pollfd fd;
int ret;
fd.fd = mySocket; // your socket handler
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
case -1:
// Error
break;
case 0:
// Timeout
break;
default:
recv(mySocket,buf,sizeof(buf), 0); // get your data
break;
}
Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:
for %%f in (*.in) do call process.cmd %%~nf
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt
There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...
well it depends if all you want is to position a div and then nothing else, you don't need to use java script for that. You can achieve this by CSS only. What matters is relative to what container you want to position your div, if you want to position it relative to document body then your div must be positioned absolute and its container must not be positioned relatively or absolutely, in that case your div will be positioned relative to the container.
Otherwise with Jquery if you want to position an element relative to document you can use offset() method.
$(".mydiv").offset({ top: 10, left: 30 });
if relative to offset parent position the parent relative or absolute. then use following...
var pos = $('.parent').offset();
var top = pos.top + 'no of pixel you want to give the mydiv from top relative to parent';
var left = pos.left + 'no of pixel you want to give the mydiv from left relative to parent';
$('.mydiv').css({
position:'absolute',
top:top,
left:left
});
import time
import sys
def update_pct(w_str):
w_str = str(w_str)
sys.stdout.write("\b" * len(w_str))
sys.stdout.write(" " * len(w_str))
sys.stdout.write("\b" * len(w_str))
sys.stdout.write(w_str)
sys.stdout.flush()
for pct in range(0, 101):
update_pct("{n}%".format(n=str(pct)))
time.sleep(0.1)
\b
will move the location of the cursor back one space
So we move it back all the way to the beginning of the line
We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one
So then we have to move the cursor back at the beginning of the line before we write our new data
Tested on Windows cmd using Python 2.7
You can use the output value from stat_summary()
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
Difference between 'true XHTML', 'faux XHTML' and HTML as well as importance of the server-sent MIME type had been already described here well. If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag for capable browsers:
div { display: flex; }_x000D_
div + div {flex-direction: column; }
_x000D_
<div>Mime type: <label><input type="radio" onchange="t.onkeyup()" id="x" checked name="mime"> application/xhtml+xml</label>_x000D_
<label><input type="radio" onchange="t.onkeyup()" name="mime"> text/html</label></div>_x000D_
<div><textarea id="t" rows="4" _x000D_
onkeyup="i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)"_x000D_
><?xml version="1.0"?>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"_x000D_
[<!ENTITY x "true XHTML">]>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<body>_x000D_
<p>_x000D_
<span id="greet" swapto="Hello">Hell, NO :(</span> &x;._x000D_
<script src="data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')" />_x000D_
Nice to meet you!_x000D_
<!-- _x000D_
Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html_x000D_
-->_x000D_
</p>_x000D_
</body>_x000D_
</html></textarea>_x000D_
_x000D_
<iframe id="i" height="80"></iframe>_x000D_
_x000D_
<script>t.onkeyup()</script>_x000D_
</div>
_x000D_
You should see Hello, true XHTML. Nice to meet you!
below textarea.
For incapable browsers you can copy content of the textarea and save it as a file with .xhtml
(or .xht
) extension (thanks Alek for this hint).
all these answers work fine BUT add a rect to an image. Suppose You have a shape (in my case a butterfly) and You want to add a border (a red border):
we need two steps: 1) take the image, convert to CGImage, pass to a function to draw offscreen in a context using CoreGraphics, and give back a new CGImage
2) convert to uiimage back and draw:
// remember to release object!
+ (CGImageRef)createResizedCGImage:(CGImageRef)image toWidth:(int)width
andHeight:(int)height
{
// create context, keeping original image properties
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width,
height,
8
4 * width,
colorspace,
kCGImageAlphaPremultipliedFirst
);
CGColorSpaceRelease(colorspace);
if(context == NULL)
return nil;
// draw image to context (resizing it)
CGContextSetInterpolationQuality(context, kCGInterpolationDefault);
CGSize offset = CGSizeMake(2,2);
CGFloat blur = 4;
CGColorRef color = [UIColor redColor].CGColor;
CGContextSetShadowWithColor ( context, offset, blur, color);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
// extract resulting image from context
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imgRef;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect frame = CGRectMake(0,0,160, 122);
UIImage * img = [UIImage imageNamed:@"butterfly"]; // take low res OR high res, but frame should be the low-res one.
imgV = [[UIImageView alloc]initWithFrame:frame];
[imgV setImage: img];
imgV.center = self.view.center;
[self.view addSubview: imgV];
frame.size.width = frame.size.width * 1.3;
frame.size.height = frame.size.height* 1.3;
CGImageRef cgImage =[ViewController createResizedCGImage:[img CGImage] toWidth:frame.size.width andHeight: frame.size.height ];
imgV2 = [[UIImageView alloc]initWithFrame:frame];
[imgV2 setImage: [UIImage imageWithCGImage:cgImage] ];
// release:
if (cgImage) CGImageRelease(cgImage);
[self.view addSubview: imgV2];
}
I added a normal butterfly and a red-bordered bigger butterfly.
This does the job without any library. Used recursion and it is Indian style. -- Ravi.
def spellNumber(no):
# str(no) will result in 56.9 for 56.90 so we used the method which is given below.
strNo = "%.2f" %no
n = strNo.split(".")
rs = numberToText(int(n[0])).strip()
ps =""
if(len(n)>=2):
ps = numberToText(int(n[1])).strip()
rs = "" + ps+ " paise" if(rs.strip()=="") else (rs + " and " + ps+ " paise").strip()
return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))
def numberToText(no):
ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
text = ""
if len(str(no))<=2:
if(no<20):
text = ones[no]
else:
text = tens[no//10-1] +" " + ones[(no %10)]
elif len(str(no))==3:
text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
elif len(str(no))<=5:
text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
elif len(str(no))<=7:
text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
else:
text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
return text
def function(a):
if a == '1':
print ('1a')
else if a == '2'
print ('2a')
else print ('3a')
Should be corrected to:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:
id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()
Hope everything works for you.
One can also bind a function with ng-change
event listener, if they need to run a bit more complex logic.
<div ng-app="myApp" ng-controller="myCtrl">
<input type='text' ng-model='name' ng-change='change()'>
<br/> <span>changed {{counter}} times </span>
</div>
...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = 'Australia';
$scope.counter = 0;
$scope.change = function() {
$scope.counter++;
};
});
../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
you can't force refresh but you can forward all old ip requests to new one. for a website:
replace [OLD_IP] with old server's ip
replace [NEW_IP] with new server's ip
run & win.
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
The importance of locales is that your environment/os can provide formatting functionality for all installed locales even if you don't know about them when you write your application. My Windows 7 system has 211 locales installed (listed below), so you wouldn't likely write any custom code or translation specific to this many locales.
The most important thing for various versions of English is in formatting numbers and dates. Other differences are significant to the extent that you want and able to cater to specific variations.
af-ZA
am-ET
ar-AE
ar-BH
ar-DZ
ar-EG
ar-IQ
ar-JO
ar-KW
ar-LB
ar-LY
ar-MA
arn-CL
ar-OM
ar-QA
ar-SA
ar-SY
ar-TN
ar-YE
as-IN
az-Cyrl-AZ
az-Latn-AZ
ba-RU
be-BY
bg-BG
bn-BD
bn-IN
bo-CN
br-FR
bs-Cyrl-BA
bs-Latn-BA
ca-ES
co-FR
cs-CZ
cy-GB
da-DK
de-AT
de-CH
de-DE
de-LI
de-LU
dsb-DE
dv-MV
el-GR
en-029
en-AU
en-BZ
en-CA
en-GB
en-IE
en-IN
en-JM
en-MY
en-NZ
en-PH
en-SG
en-TT
en-US
en-ZA
en-ZW
es-AR
es-BO
es-CL
es-CO
es-CR
es-DO
es-EC
es-ES
es-GT
es-HN
es-MX
es-NI
es-PA
es-PE
es-PR
es-PY
es-SV
es-US
es-UY
es-VE
et-EE
eu-ES
fa-IR
fi-FI
fil-PH
fo-FO
fr-BE
fr-CA
fr-CH
fr-FR
fr-LU
fr-MC
fy-NL
ga-IE
gd-GB
gl-ES
gsw-FR
gu-IN
ha-Latn-NG
he-IL
hi-IN
hr-BA
hr-HR
hsb-DE
hu-HU
hy-AM
id-ID
ig-NG
ii-CN
is-IS
it-CH
it-IT
iu-Cans-CA
iu-Latn-CA
ja-JP
ka-GE
kk-KZ
kl-GL
km-KH
kn-IN
kok-IN
ko-KR
ky-KG
lb-LU
lo-LA
lt-LT
lv-LV
mi-NZ
mk-MK
ml-IN
mn-MN
mn-Mong-CN
moh-CA
mr-IN
ms-BN
ms-MY
mt-MT
nb-NO
ne-NP
nl-BE
nl-NL
nn-NO
nso-ZA
oc-FR
or-IN
pa-IN
pl-PL
prs-AF
ps-AF
pt-BR
pt-PT
qut-GT
quz-BO
quz-EC
quz-PE
rm-CH
ro-RO
ru-RU
rw-RW
sah-RU
sa-IN
se-FI
se-NO
se-SE
si-LK
sk-SK
sl-SI
sma-NO
sma-SE
smj-NO
smj-SE
smn-FI
sms-FI
sq-AL
sr-Cyrl-BA
sr-Cyrl-CS
sr-Cyrl-ME
sr-Cyrl-RS
sr-Latn-BA
sr-Latn-CS
sr-Latn-ME
sr-Latn-RS
sv-FI
sv-SE
sw-KE
syr-SY
ta-IN
te-IN
tg-Cyrl-TJ
th-TH
tk-TM
tn-ZA
tr-TR
tt-RU
tzm-Latn-DZ
ug-CN
uk-UA
ur-PK
uz-Cyrl-UZ
uz-Latn-UZ
vi-VN
wo-SN
xh-ZA
yo-NG
zh-CN
zh-HK
zh-MO
zh-SG
zh-TW
zu-ZA
In 2017, the solution is:
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
I'm no Java expert, but I would presume that the .hasNext
, .hasNextLine
and .hasNextByte
all use and increment the same file position indicator. You'll need to reset that, either by creating a new Scanner as Aashray mentioned, or using a RandomAccessFile and calling file.seek(0);
after each loop.
jQuery will encode and decode for you. However, you need to use a textarea tag, not a div.
var str1 = 'One & two & three';_x000D_
var str2 = "One & two & three";_x000D_
_x000D_
$(document).ready(function() {_x000D_
$("#encoded").text(htmlEncode(str1)); _x000D_
$("#decoded").text(htmlDecode(str2));_x000D_
});_x000D_
_x000D_
function htmlDecode(value) {_x000D_
return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="encoded"></div>_x000D_
<div id="decoded"></div>
_x000D_
Use the error callback.
For example:
jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
alert(xhr.status); }
});
Will alert 404
In Python 3.
GPA = 2.5
print(" %6.1f " % GPA)
6.1f
means after the dots 1 digits show if you print 2 digits after the dots you should only %6.2f
such that %6.3f
3 digits print after the point.
$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->getStartColor()
->getRGB();
insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
ts.tax_status_id,
( select r.recipient_id
from recipient r
where r.recipient_code = ?
)
from tax_status ts
where ts.tax_status_code = ?
according to http://www.maketecheasier.com/combine-multiple-pdf-files-with-pdftk/ the command should be
pdftk file1.pdf file2.pdf file3.pdf cat output newfile.pdf
note that you should download windows version of pdftk
Yes,u can overload main method but the interpreter will always search for the correct main method syntax to begin the execution.. And yes u have to call the overloaded main method with the help of object.
class Sample{
public void main(int a,int b){
System.out.println("The value of a is " +a);
}
public static void main(String args[]){
System.out.println("We r in main method");
Sample obj=new Sample();
obj.main(5,4);
main(3);
}
public static void main(int c){
System.out.println("The value of c is" +c);
}
}
The output of the program is:
We r in main method
The value of a is 5
The value of c is 3
Alternatively, just select 'Other Users' one of the element shows on the left hand side bottom of the current schema.
Select what ever the schema you want from the available list.
I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.
Unfortunately that approach is not portable C++ (so far).
All standard names are in namespace std
and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string
directly or indirectly when using #include <vector>
).
Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map>
but use std::map
it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.
In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).
The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.
However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).
There is a new way to solve this and it's by using async/await.
async function myFunction() {
while(/* my condition */) {
const res = await db.getUser(email);
logger.log(res);
}
}
myFunction().then(() => {
/* do other stuff */
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://ponyfoo.com/articles/understanding-javascript-async-await
I just found this extension called beautify in the Market Place and yes, it's another config\settings file. :)
Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.
VS Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. This extension enables running js-beautify in VS Code, AND honouring any .jsbeautifyrc file in the open file's path tree to load your code styling. Run with F1 Beautify (to beautify a selection) or F1 Beautify file.
For help on the settings in the .jsbeautifyrc see Settings.md
Here is the GitHub repository: https://github.com/HookyQR/VSCodeBeautify
Simple struct to access plist file (Swift 2.0)
struct Configuration {
static let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
static let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
static let someValue = dict["someKey"] as! String
}
Usage:
print("someValue = \(Configuration.someValue)")
For this particular query, why make expensive function calls for each row when you could just ask for values starting at the next higher second:
select *
from table
where date >= '2010-07-20 03:21:53'
I tried the following ways in first jQuery, then JavaScript:
jQuery:
window.location.href = $(".contact").attr('href');
$('.contactformone').trigger('click');
This is the best way in JavaScript:
document.getElementById("id").click();
TL;DR Use absolute paths to your assets (including your complete hostname) by setting your output.publicPath
to e.g. "http://example.com/assets/".
The problem is the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob.
When you load the page, the browser loads your Webpack bundle entry JavaScript file, which (when you're using the style-loader
) also contains a Base64 encoded copy of your CSS, which gets loaded into the page.
That's fine for all the images or fonts which are encoded into the CSS as data URIs (i.e. the content of the file is embedded in the CSS), but for assets referenced by URL, the browser has to find and fetch the file.
Now by default the file-loader
(which url-loader
delegates to for large files) will use relative URLs to reference assets - and that's the problem!
These are the URLs generated by
file-loader
by default - relative URLs
When you use relative URLs, Chrome will resolve them relative to the containing CSS file. Ordinarily that's fine, but in this case the containing file is at blob://...
and any relative URLs are referenced the same way. The end result is that Chrome attempts to load them from the parent HTML file, and ends up trying to parse the HTML file as the content of the font, which obviously won't work.
Force the file-loader
to use absolute paths including the protocol ("http" or "https").
Change your webpack config to include something equivalent to:
{
output: {
publicPath: "http://localhost:8080/", // Development Server
// publicPath: "http://example.com/", // Production Server
}
}
Now the URLs that it generates will look like this:
These URLs will be correctly parsed by Chrome and every other browser.
extract-text-webpack-plugin
It's worth noting that if you're extracting your CSS to a separate file, you won't have this problem because your CSS will be in a proper file and URLs will be correctly resolved.
As the other answers have described, lit
and typedLit
are how to add constant columns to DataFrames. lit
is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.
You'll commonly be using lit
to create org.apache.spark.sql.Column
objects because that's the column type required by most of the org.apache.spark.sql.functions
.
Suppose you have a DataFrame with a some_date
DateType column and would like to add a column with the days between December 31, 2020 and some_date
.
Here's your DataFrame:
+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+
Here's how to calculate the days till the year end:
val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
.withColumn("days_till_yearend", diff)
.show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23| 99|
|2020-01-05| 361|
|2020-04-12| 263|
+----------+-----------------+
You could also use lit
to create a year_end
column and compute the days_till_yearend
like so:
import java.sql.Date
df
.withColumn("yearend", lit(Date.valueOf("2020-12-31")))
.withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
.show()
+----------+----------+-----------------+
| some_date| yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31| 99|
|2020-01-05|2020-12-31| 361|
|2020-04-12|2020-12-31| 263|
+----------+----------+-----------------+
Most of the time, you don't need to use lit
to append a constant column to a DataFrame. You just need to use lit
to convert a Scala type to a org.apache.spark.sql.Column
object because that's what's required by the function.
See the datediff
function signature:
As you can see, datediff
requires two Column arguments.
Here's what I ended up with. This works for me if I import my script in the interpreter, and also if I execute it as a script:
import os
import sys
# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path)
May I recommend you to Beautiful Soup. Soup is a very good lib to parse all of your html document.
soup = BeatifulSoup(html_doc)
titleName = soup.title.name
Found this on Google... I would assume that in your case you would copy rc.exe
and rcdll.dll
to visual studio 2012\vc\bin
or wherever you have it installed:
Part 2: FIX LINK : fatal error LNK1158: cannot run ‘rc.exe’
Add this to your PATH environment variables:
C:\Program Files (x86)\Windows Kits\8.0\bin\x86
Copy these files:
rc.exe
rcdll.dll
From
C:\Program Files (x86)\Windows Kits\8.0\bin\x86
To
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin
Or I also found this:
Microsoft left a few things out of their MSVT package. Since no one knows whether they were left out by mistake or for license reasons, no one with MSVC is too interested in giving them out. A few Google searches turn up some tricky sources. Fortunately, Microsoft has finally wised up and solved this problem and many more.
http://msdn.microsoft.com/vstudio/express/support/faq/default.aspx#pricing
http://msdn.microsoft.com/vstudio/express/support/install/
A good amount of MSVT missing files are there but the missing SDK files aren't.
and this:
I had the same problem which I solved by doing this:
Now I can build and link resource files without errors.
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
Check your manifest,Open the file with .xml extension and then all your activities are listed your first activity should have this code enclosed in its tags
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
or there is another way u can choose from configuration which is drop down list on the left side of run button choose from App from it Hope it will help!!
The following is a jQuery function call:
$(...);
Which is the "jQuery function." $
is a function, and $(...)
is you calling that function.
The first parameter you've supplied is the following:
function() {}
The parameter is a function that you specified, and the $
function will call the supplied method when the DOM finishes loading.
After adding JTextArea into JScrollPane here:
scroll = new JScrollPane(display);
You don't need to add it again into other container like you do:
middlePanel.add(display);
Just remove that last line of code and it will work fine. Like this:
middlePanel=new JPanel();
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));
// create the middle panel components
display = new JTextArea(16, 58);
display.setEditable(false); // set textArea non-editable
scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Add Textarea in to middle panel
middlePanel.add(scroll);
JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:
new JScrollPane( myComponent )
or set view like this:
JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );
Additional:
Here is fully working example since you still did not get it working:
public static void main ( String[] args )
{
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );
// create the middle panel components
JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Textarea in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ();
frame.add ( middlePanel );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
And here is what you get:
Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Note getSelectedFile()
returns the selected folder, despite the name.
getCurrentDirectory()
returns the directory of the selected folder.
import javax.swing.*;
public class Example
{
public static void main(String[] args)
{
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
}
}
Here's another extremely detailed walkthrough that also shows you the entire process, including what values to put in the connection dialogue after the JDBC driver is installed: http://rpbouman.blogspot.com/2007/01/oracle-sql-developer-11-supports-mysql.html
There are several you can use/try:
I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.
Just set your default CSS on your images like so:
img {
width:auto;
height:auto;
max-width:100%;
max-height:100%;
}
Then use some media queries to check your orientation and that's it!
@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }
You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.
To learn more about these media queries, you can read MDN's specs.
To center your image horizontally and vertically, just use the flex box model. Use a parent div
set to 100% width and height, like so:
div.parent {
display:flex;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
justify-content:center;
align-items:center;
}
With the parent div's display
set to flex
, the element is now ready to use the flex box model. The justify-content
property sets the horizontal alignment of the flex items. The align-items
property sets the vertical alignment of the flex items.
I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.
EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.
Spring Boot 1.4 introduced testing annotation called @MockBean
. So now mocking and spying on Spring beans is natively supported by Spring Boot.
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
This approach worked for me but it is not as specific as your question:
App.Current.MainWindow
I had to do the same thing and this is what I wrote.I made it more flexible in my case as I had multiple group of check boxes to check.
// param: reqNum number of checkboxes to select
$.fn.checkboxValidate = function(reqNum){
var fields = this.serializeArray();
return (fields.length < reqNum) ? 'invalid' : 'valid';
}
then you can pass this function to check multiple group of checkboxes with multiple rules.
// helper function to create error
function err(msg){
alert("Please select a " + msg + " preference.");
}
$('#reg').submit(function(e){
//needs at lease 2 checkboxes to be selected
if($("input.region, input.music").checkboxValidate(2) == 'invalid'){
err("Region and Music");
}
});
The below worked for me
I know this reply is late, but if you are using passportjs, you might want to see this.
return (req, res, next) => {
console.log(req.originalUrl);
next();
};
I have written this middleware and applied it to express server instance, and the original URL I've got is without the "#_=_"
. Looks like it when we apply passporJS' instance as middleware to the server instance, it doesn't take those characters, but are only visible on the address bar of our browsers.
Here's a LESS mixin for transitioning two properties at once:
.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
-webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}
which
is good alternative, especially when you operate on matrices (check ?which
and notice the arr.ind
argument). But I suggest that you stick with sum
, because of na.rm
argument that can handle NA
's in logical vector.
For instance:
# create dummy variable
set.seed(100)
x <- round(runif(100, 0, 1))
x <- x == 1
# create NA's
x[seq(1, length(x), 7)] <- NA
If you type in sum(x)
you'll get NA
as a result, but if you pass na.rm = TRUE
in sum
function, you'll get the result that you want.
> sum(x)
[1] NA
> sum(x, na.rm=TRUE)
[1] 43
Is your question strictly theoretical, or you have some practical problem concerning logical vectors?
Vanilla 1-liner for IE8+:
parent !== child && parent.contains(child);
Here, how it works:
function contains(parent, child) {_x000D_
return parent !== child && parent.contains(child);_x000D_
}_x000D_
_x000D_
var parentEl = document.querySelector('#parent'),_x000D_
childEl = document.querySelector('#child')_x000D_
_x000D_
if (contains(parentEl, childEl)) {_x000D_
document.querySelector('#result').innerText = 'I confirm, that child is within parent el';_x000D_
}_x000D_
_x000D_
if (!contains(childEl, parentEl)) {_x000D_
document.querySelector('#result').innerText += ' and parent is not within child';_x000D_
}
_x000D_
<div id="parent">_x000D_
<div>_x000D_
<table>_x000D_
<tr>_x000D_
<td><span id="child"></span></td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
<div id="result"></div>
_x000D_
Check your object owner if you copy the file from another aws account.
In my case, I copy the file from another aws account without acl, so file's owner is the other aws account, it's mean the file belongs to origin account.
To fix it, copy or sync s3 files with acl, example:
aws s3 cp --acl bucket-owner-full-control s3://bucket1/key s3://bucket2/key
You have an instance method called num_words
, but you also have a variable called num_words
. They have the same name. When you run num_words()
, the function replaces itself with its own output, which probably isn't what you want to do. Consider return
ing your values.
To fix your problem, change def num_words
to something like def get_num_words
and your code should work fine. Also, change print test.sort_word_list
to print test.sorted_word_list
.
I read the comments about contacts app and how it use a theme for each contact.
Probably, contacts app has some predefine themes (for each material primary color from here: http://www.google.com/design/spec/style/color.html).
You can apply a theme before a the setContentView method inside onCreate method.
Then the contacts app can apply a theme randomly to each user.
This method is:
setTheme(R.style.MyRandomTheme);
But this method has a problem, for example it can change the toolbar color, the scroll effect color, the ripple color, etc, but it cant change the status bar color and the navigation bar color (if you want to change it too).
Then for solve this problem, you can use the method before and:
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.md_red_500));
getWindow().setStatusBarColor(getResources().getColor(R.color.md_red_700));
}
This two method change the navigation and status bar color. Remember, if you set your navigation bar translucent, you can't change its color.
This should be the final code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyRandomTheme);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.myrandomcolor1));
getWindow().setStatusBarColor(getResources().getColor(R.color.myrandomcolor2));
}
setContentView(R.layout.activity_main);
}
You can use a switch and generate random number to use random themes, or, like in contacts app, each contact probably has a predefine number associated.
A sample of theme:
<style name="MyRandomTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/myrandomcolor1</item>
<item name="colorPrimaryDark">@color/myrandomcolor2</item>
<item name="android:navigationBarColor">@color/myrandomcolor1</item>
</style>
Sorry for my english.
I have written a java example for this case:
Use json.org library to retrieve JSONObjects and JSONArrays. The example below uses blockchain.info's data which can be obtained as JSONObject.
public class main
{
public static void main(String[] args) throws MalformedURLException, IOException
{
JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
JSONArray data_array = data.getJSONArray("values");
for (int i = 0; i < data_array.length(); i++)
{
JSONObject price_point = data_array.getJSONObject(i);
// Unix time
int x = price_point.getInt("x");
// Bitcoin price at that time
double y = price_point.getDouble("y");
// Do something with x and y.
}
}
public static JSONObject getJSONfromURL(String URL)
{
try
{
URLConnection uc;
URL url = new URL(URL);
uc = url.openConnection();
uc.setConnectTimeout(10000);
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
uc.connect();
BufferedReader rd = new BufferedReader(
new InputStreamReader(uc.getInputStream(),
Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char)cp);
}
String jsonText = (sb.toString());
return new JSONObject(jsonText.toString());
} catch (IOException ex)
{
return null;
}
}
}
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object
and are what you are using, and invoke their base class through super()
, e.g.
class X(object):
def __init__(self, x):
pass
def doit(self, bar):
pass
class Y(X):
def __init__(self):
super(Y, self).__init__(123)
def doit(self, foo):
return super(Y, self).doit(foo)
Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.
For completeness sake, old-style classes call base methods explicitly using the base class, i.e.
def doit(self, foo):
return X.doit(self, foo)
But since you shouldn't be using old-style anymore, I wouldn't care about this too much.
Python 3 only knows about new-style classes (no matter if you derive from object
or not).
brew info mysql
mysql: stable 5.6.12 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.12 (9363 files, 353M) *
Poured from bottle
From: https://github.com/mxcl/homebrew/commits/master/Library/Formula/mysql.rb
==> Dependencies
Build: cmake
==> Options
--enable-debug
Build with debug support
--enable-local-infile
Build with local infile loading support
--enable-memcached
Enable innodb-memcached support
--universal
Build a universal binary
--with-archive-storage-engine
Compile with the ARCHIVE storage engine enabled
--with-blackhole-storage-engine
Compile with the BLACKHOLE storage engine enabled
--with-embedded
Build the embedded server
--with-libedit
Compile with editline wrapper instead of readline
--with-tests
Build with unit tests
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
To reload mysql after an upgrade:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
mysql.service start
. ERROR! The server quit without updating PID file (/var/run/mysqld/mysqld.pid).
or mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
I'm looking for a solution for some time but I can not solve my problem. I tried several solutions in stackoverflow.com but no this helping me.
Similarly to the RTTI, NO-RTTI discussion above, this problem can also occur if you use dynamic_cast and fail to include the object code containing the class implementation.
I ran into this problem building on Cygwin and then porting code to Linux. The make files, directory structure and even the gcc versions (4.8.2) were identical in both cases, but the code linked and operated correctly on Cygwin but failed to link on Linux. Red Hat Cygwin has apparently made compiler/linker modifications that avoid the object code linking requirement.
The Linux linker error message properly directed me to the dynamic_cast line, but earlier messages in this forum had me looking for missing function implementations rather than the actual problem: missing object code. My workaround was to substitute a virtual type function in the base and derived class, e.g. virtual int isSpecialType(), rather than use dynamic_cast. This technique avoids the requirement to link object implementation code just to get dynamic_cast to work properly.
Your controller method should be like this:
@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
int id = 2323; // Currently passing static values for testing
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
return "note";
}
Use the id
in your code, call the controller method from your JSP as:
/{your mapping}/{your id}
UPDATE:
Change your jsp code to:
<c:forEach items="${listNotes}" var="notices" varStatus="status">
<tr>
<td>${notices.noticesid}</td>
<td>${notices.notetext}</td>
<td>${notices.notetag}</td>
<td>${notices.notecolor}</td>
<td>${notices.sectionid}</td>
<td>${notices.canvasid}</td>
<td>${notices.canvasnName}</td>
<td>${notices.personid}</td>
<td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
<td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
</tr>
</c:forEach>
Why don't you take a look to this answer
Including javascript files inside javascript files
In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.
You have to modify the control template instead of ItemsPanelTemplate:
<ItemsControl >
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.
Object.values()
is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.
Solution: use es2017
or es2017.object
in your --lib
compiler option.
For example, using tsconfig.json
:
"compilerOptions": {
"lib": ["es2017", "dom"]
}
Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values
), it's up to you to polyfill your project code yourself if you want. And since Object.values
is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js
will do the job.
If its a maven project, add the below dependency in your pom file
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
Here is a code improvement based on mcandal solution.
Added exception catching for any exception generated from the client.ConnectAsync
task (e.g: SocketException when server is unreachable)
var timeOut = TimeSpan.FromSeconds(5);
var cancellationCompletionSource = new TaskCompletionSource<bool>();
try
{
using (var cts = new CancellationTokenSource(timeOut))
{
using (var client = new TcpClient())
{
var task = client.ConnectAsync(hostUri, portNumber);
using (cts.Token.Register(() => cancellationCompletionSource.TrySetResult(true)))
{
if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
{
throw new OperationCanceledException(cts.Token);
}
// throw exception inside 'task' (if any)
if (task.Exception?.InnerException != null)
{
throw task.Exception.InnerException;
}
}
...
}
}
}
catch (OperationCanceledException operationCanceledEx)
{
// connection timeout
...
}
catch (SocketException socketEx)
{
...
}
catch (Exception ex)
{
...
}
How do I select multiple columns by labels in pandas?
Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:
loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
A B C E G H I
0 -1.666330 0.321260 -1.768185 -0.034774 0.023294 0.533451 -0.241990
1 0.911498 3.408758 0.419618 -0.462590 0.739092 1.103940 0.116119
2 1.243001 -0.867370 1.058194 0.314196 0.887469 0.471137 -1.361059
3 -0.525165 0.676371 0.325831 -1.152202 0.606079 1.002880 2.032663
4 0.706609 -0.424726 0.308808 1.994626 0.626522 -0.033057 1.725315
5 0.879802 -1.961398 0.131694 -0.931951 -0.242822 -1.056038 0.550346
6 0.199072 0.969283 0.347008 -2.611489 0.282920 -0.334618 0.243583
7 1.234059 1.000687 0.863572 0.412544 0.569687 -0.684413 -0.357968
8 -0.299185 0.566009 -0.859453 -0.564557 -0.562524 0.233489 -0.039145
9 0.937637 -2.171174 -1.940916 -1.553634 0.619965 -0.664284 -0.151388
Note that the +1
is added because when using iloc
the rightmost index is exclusive.
filter
is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.
The "location-based" solution with loc
is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.
Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.
EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative
Correctly detecting the encoding all times is impossible.
(From chardet FAQ:)
However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.
There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.
You can also use UnicodeDammit. It will try the following methods:
You could add google()
to repositories block
allprojects {
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url "https://jitpack.io"
}
google()
}
}
Your code is blanking out your file:
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)
if you want to read the file in, you will need to use csv.reader and open the file for reading.
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
print line
If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).
You can make it through echo only and without the other stuff. Don't forget to add "-n" or you will get a linebreak automatically:
echo -n -e "\x5a"
For commenting out multiple lines of code in Python is to simply use a #
single-line comment on every line:
# This is comment 1
# This is comment 2
# This is comment 3
For writing “proper” multi-line comments in Python is to use multi-line strings with the """
syntax
Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.
'''
This is
multiline
comment
'''
Also, mention that you can access docstring by a class object like this
myobj.__doc__
Here's a couple of suggestions:
Use date_range
for the index:
import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
Note: we could create an empty DataFrame (with NaN
s) simply by writing:
df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs
To do these type of calculations for the data, use a numpy array:
data = np.array([np.arange(10)]*3).T
Hence we can create the DataFrame:
In [10]: df = pd.DataFrame(data, index=index, columns=columns)
In [11]: df
Out[11]:
A B C
2012-11-29 0 0 0
2012-11-30 1 1 1
2012-12-01 2 2 2
2012-12-02 3 3 3
2012-12-03 4 4 4
2012-12-04 5 5 5
2012-12-05 6 6 6
2012-12-06 7 7 7
2012-12-07 8 8 8
2012-12-08 9 9 9
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1
to %9
. There are also two other tokens that you can use:
%0
is the executable (batch file) name as specified in the command line.%*
is all parameters specified in the command line -- this is very useful if you want to forward the parameters to another program.There are also lots of important techniques to be aware of in addition to simply how to access the parameters.
This is done with constructs like IF "%~1"==""
, which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1
; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.
If you need to access more than 9 arguments you have to use the command SHIFT
. This command shifts the values of all arguments one place, so that %0
takes the value of %1
, %1
takes the value of %2
, etc. %9
takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT
(enter command SHIFT /?
for more options).
SHIFT
is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a
and -b
in any order. A good way to parse the command line in such cases is
:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!
This scheme allows you to parse pretty complex command lines without going insane.
For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~
.
For example, to get the size of the file passed in as an argument use
ECHO %~z1
To get the path of the directory where the batch file was launched from (very useful!) you can use
ECHO %~dp0
You can view the full range of these capabilities by typing CALL /?
in the command prompt.
You may use DateDiff
and compare by day.
DateDiff(dd,@date1,@date2) > 0
It means @date2 > @date1
For example :
select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00')
has the result : 1
You can see the following code to solved the problem
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->where('kg_shops.active','=', 1);
});
Or another way to solved it
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->on('kg_shops.active','=', DB::raw('1'));
});
after API >=21 there is inbuild method provided by TextView called setLetterSpacing
check this for more
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
In iOS 10 beta 4.The right code in HTML5 is
<video src="file.mp4" webkit-playsinline="true" playsinline="true">
webkit-playsinline
is for iOS < 10, and playsinline
is for iOS >= 10
See details via https://webkit.org/blog/6784/new-video-policies-for-ios/
You could try overriding the EDITOR
environment variable with something like ed
which can take a sequence of edit commands over standard input.
<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />
I've tried all the solutions from the answers but couldn't get mysql
command to work from the terminal, always getting the message
bash: command not found
The solution is to change the .bash_profile, and add the mysql path to .bash_profile
To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using
nano .bash_profile
3. Add the following command to add the mysql path
PATH="/usr/local/mysql/bin:${PATH}"
export PATH
4. Press Ctrl+X, then press y and press enter.
I believe fcntl()
is a POSIX function. Where as ioctl()
is a standard UNIX thing. Here is a list of POSIX io. ioctl()
is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl()
stuff might only work on certain OS or even certain revs of it's kernel.
I did a quick test in both node and chrome and found in both cases +=
is faster:
var profile = func => {
var start = new Date();
for (var i = 0; i < 10000000; i++) func('test');
console.log(new Date() - start);
}
profile(x => "testtesttesttesttest");
profile(x => `${x}${x}${x}${x}${x}`);
profile(x => x + x + x + x + x );
profile(x => { var s = x; s += x; s += x; s += x; s += x; return s; });
profile(x => [x, x, x, x, x].join(""));
profile(x => { var a = [x]; a.push(x); a.push(x); a.push(x); a.push(x); return a.join(""); });
results in node: 7.0.10
results from chrome 86.0.4240.198:
Depending if you have Underscore or Babel here is a Benchmark of the different way of deep cloning an array.
https://jsperf.com/object-rest-spread-vs-clone/2
Look like babel is the fastest.
var x = babel({}, obj)
As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt
The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)
Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.
1.<a href="index.jsp?p=products">Products</a>
when user clicks on Products link,you can directly call products.jsp.
I mean u can maintain name of the JSP file same as parameter Value.
<%
if(request.getParameter("p")!=null)
{
String contextPath="includes/";
String p = request.getParameter("p");
p=p+".jsp";
p=contextPath+p;
%>
<%@include file="<%=p%>" %>
<%
}
%>
or
2.you can maintain external resource file with key,value pairs. like below
products : products.jsp
customer : customers.jsp
you can programatically retrieve the name of JSP file from properies file.
this way you can easily change the name of JSP file
The above is correct but for a more general answer it is not enough. I needed to nest ng-repeat, but stay on the same html level, meaning write the elements in the same parent. The tags array contain tag(s) that also have a tags array. It is actually a tree.
[{ name:'name1', tags: [
{ name: 'name1_1', tags: []},
{ name: 'name1_2', tags: []}
]},
{ name:'name2', tags: [
{ name: 'name2_1', tags: []},
{ name: 'name2_2', tags: []}
]}
]
So here is what I eventually did.
<div ng-repeat-start="tag1 in tags" ng-if="false"></div>
{{tag1}},
<div ng-repeat-start="tag2 in tag1.tags" ng-if="false"></div>
{{tag2}},
<div ng-repeat-end ng-if="false"></div>
<div ng-repeat-end ng-if="false"></div>
Note the ng-if="false" that hides the start and end divs.
It should print
name1,name1_1,name1_2,name2,name2_1,name2_2,
PROBABLY ONLY IE:
> webBrowser1.DocumentText
for FF up from 1.0:
//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));
may work in FF. (Shows up the VERY FIRST 300 characters from the VERY beginning of source-text, mostly doctype-defs.)
BUT be aware, that the normal "Save As"-Dialog of FF MIGHT NOT save the current state of the page, rather the originallly loaded X/h/tml-source-text !! (a POST-up of ss to some temp-file and redirect to that might deliver a saveable source-text WITH the changes/edits prior made to it.)
Although FF surprises by good recovery on "back" and a NICE inclusion of states/values on "Save (as) ..." for input-like FIELDS, textarea etc. , not on elements in contenteditable/ designMode...
If NOT a xhtml- resp. xml-file (mime-type, NOT just filename-extension!), one may use document.open/write/close to SET the appr. content to the source-layer, that will be saved on user's save-dialog from the File/Save menue of FF. see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp.
https://developer.mozilla.org/en-US/docs/Web/API/document.write
Neutral to questions of X(ht)ML, try a "view-source:http://..." as the value of the src-attrib of an (script-made!?) iframe, - to access an iframes-document in FF:
<iframe-elementnode>.contentDocument
, see google "mdn contentDocument" for appr. members, like 'textContent' for instance.
'Got that years ago and no like to crawl for it. If still of urgent need, mention this, that I got to dive in ...
Add a entry, at the end of your enum, called Folders_MAX or something similar and use this value when initializing your arrays.
ContainerClass* m_containers[Folders_MAX];
I tried with many solutions but it didn't work for me so I tried flex with the table and it worked fine for me with all table functionalities like border-collapse and so on only change is display property
This was my HTML requirement
<table>
<thead>
<tr>
<th>1</th>
<th colspan="3">2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td colspan="3">2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td colspan="2">3</td>
</tr>
</tbody>
</table>
My CSS
table{
display: flex;
flex-direction: column;
}
table tr{
display: flex;
width: 100%;
}
table > thead > tr > th:first-child{
width: 20%;
}
table > thead > tr > th:last-child{
width: 80%;
}
table > tbody tr > td:first-child{
width: 10%;
}
table > tbody tr > td{
width: 30%;
}
table > tbody tr > td[colspan="2"]{
width: 60%;
}
table > tbody tr > td[colspan="3"]{
width: 90%;
}
/*This is to remove border making 1px space on right*/
table > tbody tr > td:last-child{
border-right: 0;
}
You don't need to find the file.
Only write this instruction on terminal:
git config --global --edit
just use UPDATE query without condition like this
UPDATE tablename SET online_status=0;
If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ()
.
case
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore
But it'll be better if you show your full query to get context of what you actually need.
in bootstrap v4, i center and fill the carousel img to the screen using
<img class="d-block mx-auto" max-width="100%" max-height="100%">
pretty sure this requires parent elements' height or width to be set
html,body{height:100%;}
.carousel,.carousel-item,.active{height:100%;}
.carousel-inner{height:100%;}
Use indexOf
var url = "http://mysite.com/somedir/somefile/?aa";
if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.
But make sure to unsubscribe to that on destroy of the parent component.
The problem is that an isin does not identify the exchange, only an issuer.
Let's say your isin is US4592001014
(IBM), one way to do it would be:
get the ticker (in A1):
=BDP("US4592001014 ISIN", "TICKER") => IBM
get a proper symbol (in A2)
=BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
where XX
depends on your terminal settings, which you can check on CNDF <Go>
.
get the main exchange composite ticker, or whatever suits your need (in A3):
=BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
and finally:
=BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
like this:
/\<word\>
\<
means beginning of a word, and \>
means the end of a word,
Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*'
to search forward in the file or '#'
to search backwards.
Slight variation on Mac OSX:
Eclipse ? Preferences ? General ? Editors ? Text Editors ? Show line numbers
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.
position:absolute;
top:0; bottom:0; left:0; right:0;
margin:auto;
Click on the line or element you want to copy. Copy to clipboard. Paste.
The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.
You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.
This is how Microsoft explains it:
.NET Framework is the "full" or "traditional" flavor of .NET that's distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.
.NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.
Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices.
Xamarin usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.
A common point of confusion is where ASP.NET Core fits in. ASP.NET Core can run on top of either .NET Framework (Windows) or .NET Core (cross-platform), as detailed in this answer: Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)
In a discussion, Simon clearly mentioned that:
While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.
Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2)
and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened)
as required. Here is a solution where you can open http://www.google.co.in
in the initial TAB and https://www.yahoo.com
in the adjacent TAB:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.google.co.in")
print("Initial Page Title is : %s" %driver.title)
windows_before = driver.current_window_handle
print("First Window Handle is : %s" %windows_before)
driver.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to_window(new_window)
print("Page Title after Tab Switching is : %s" %driver.title)
print("Second Window Handle is : %s" %new_window)
Console Output:
Initial Page Title is : Google
First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
Page Title after Tab Switching is : Yahoo
Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
Browser Snapshot:
You can find the java based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium
A much more accurate SQL STATEMENT
SELECT a.tablespace_name,
ROUND (((c.BYTES - NVL (b.BYTES, 0)) / c.BYTES) * 100,2) percentage_used,
c.BYTES / 1024 / 1024 space_allocated,
ROUND (c.BYTES / 1024 / 1024 - NVL (b.BYTES, 0) / 1024 / 1024,2) space_used,
ROUND (NVL (b.BYTES, 0) / 1024 / 1024, 2) space_free,
c.DATAFILES
FROM dba_tablespaces a,
( SELECT tablespace_name,
SUM (BYTES) BYTES
FROM dba_free_space
GROUP BY tablespace_name
) b,
( SELECT COUNT (1) DATAFILES,
SUM (BYTES) BYTES,
tablespace_name
FROM dba_data_files
GROUP BY tablespace_name
) c
WHERE b.tablespace_name(+) = a.tablespace_name
AND c.tablespace_name(+) = a.tablespace_name
ORDER BY NVL (((c.BYTES - NVL (b.BYTES, 0)) / c.BYTES), 0) DESC;
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
This will surely work:
UPDATE table1
SET table1.price=(SELECT table2.price
FROM table2
WHERE table2.id=table1.id AND table2.item=table1.item);
If you dont have a id or seed, like its its for a values list in insert:
REPLACE(RAND(), '.', '')