If you have a query with a lot of criteria, it can be tricky to remember what each one does. I add a text field into the original table - call it "comments" or "documentation". Then I include it in the query with a comment for each criteria.
Comments need to be written like like this so that all relevant rows are returned. Unfortunately, as I'm a new poster, I can't add a screenshot!
So here goes without
Field: | Comment |ContractStatus | ProblemDealtWith | ...... |
Table: | ElecContracts |ElecContracts | ElecContracts | ...... |
Sort:
Show:
Criteria | <> "all problems are | "objection" Or |
| picked up with this | "rejected" Or |
| criteria" OR Is Null | "rolled" |
| OR ""
<>
tells the query to choose rows that are not equal to the text you entered, otherwise it will only pick up fields that have text equal to your comment i.e. none!
" " enclose your comment in quotes
OR Is Null OR "" tells your query to include any rows that have no data in the comments field , otherwise it won't return anything!
// here is how you can detect dragging in all four directions
var isDragging = false;
$("some DOM element").mousedown(function(e) {
var previous_x_position = e.pageX;
var previous_y_position = e.pageY;
$(window).mousemove(function(event) {
isDragging = true;
var x_position = event.pageX;
var y_position = event.pageY;
if (previous_x_position < x_position) {
alert('moving right');
} else {
alert('moving left');
}
if (previous_y_position < y_position) {
alert('moving down');
} else {
alert('moving up');
}
$(window).unbind("mousemove");
});
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
});
StringEscapeUtils.escapeXml()
does not escape control characters (< 0x20). XML 1.1 allows control characters; XML 1.0 does not. For example, XStream.toXML()
will happily serialize a Java object's control characters into XML, which an XML 1.0 parser will reject.
To escape control characters with Apache commons-lang, use
NumericEntityEscaper.below(0x20).translate(StringEscapeUtils.escapeXml(str))
Here's a little cmd script you can copy-n-paste into a file named something like where.cmd
:
@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem The main ideas for this script were taken from Raymond Chen's blog:
rem
rem http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem help diagnose situations with a conflict of some sort.
rem
setlocal
rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%
if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok
rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
I hope this is what you may want to find in the classical CLRS(page 66):
There is no maximum since Ruby 2.4, as Bignum and Fixnum got unified into Integer. see Feature #12005
> (2 << 1000).is_a? Fixnum
(irb):322: warning: constant ::Fixnum is deprecated
=> true
> 1.is_a? Bignum
(irb):314: warning: constant ::Bignum is deprecated
=> true
> (2 << 1000).class
=> Integer
There won't be any overflow, what would happen is an out of memory.
To find menu items in content page base on roles
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AdminSuccess"] != null)
{
Menu mainMenu = (Menu)Page.Master.FindControl("NavigationMenu");
//you must know the index of items to be removed first
mainMenu.Items.RemoveAt(1);
//or you try to hide menu and list items inside menu with css
// cssclass must be defined in style tag in .aspx page
mainMenu.CssClass = ".hide";
}
}
<style type="text/css">
.hide
{
visibility: hidden;
}
</style>
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm()
method returns false
.
On an AWS Ubuntu 16.04 Server I put the Docker images on a separate EBS, mounted on /home/ubuntu/kaggle/, under the docker dir
This snippet of my initialization script worked correctly
# where are the images initially stored?
sudo docker info | grep "Root Dir"
# ... not where I want them
# modify the configuration files to change to image location
# NOTE this generates an error
# WARNING: Usage of loopback devices is strongly discouraged for production use.
# Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
# see https://stackoverflow.com/questions/31620825/
# warning-of-usage-of-loopback-devices-is-strongly-discouraged-for-production-use
sudo sed -i ' s@#DOCKER_OPTS=.*@DOCKER_OPTS="-g /home/ubuntu/kaggle/docker"@ ' /etc/default/docker
sudo chmod -R ugo+rw /lib/systemd/system/docker.service
sudo cp /lib/systemd/system/docker.service /etc/systemd/system/
sudo chmod -R ugo+rw /etc/systemd/system/
sudo sed -i ' s@ExecStart.*@ExecStart=/usr/bin/dockerd $DOCKER_OPTS -H fd://@ ' /etc/systemd/system/docker.service
sudo sed -i '/ExecStart/a EnvironmentFile=-/etc/default/docker' /etc/systemd/system/docker.service
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo docker info | grep "Root Dir"
# now they're where I want them
I tried both .empty()
as well as .remove()
for my dropdown and both were slow. Since I had almost 4,000 options there.
I used .html("")
which is much faster in my condition.
Which is below
$(dropdown).html("");
Any click event before for update /edit/delete records message box alerts the user and if "Ok" proceed for the action else "cancel" remain unchanged. For this code no need to right separate java script code. it works for me
<a asp-action="Delete" asp-route-ID="@Item.ArtistID" onclick = "return confirm('Are you sure you wish to remove this Artist?');">Delete</a>
Invoke-WebRequest can download HTTP, HTTPS, and FTP links.
$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password
# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing
Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.
iPad Media Queries (All generations - including iPad mini)
Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.
iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) { /* STYLES GO HERE */}
iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) { /* STYLES GO HERE */}
iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) { /* STYLES GO HERE */ }
iPad 3 & 4 Media Queries
If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.
Retina iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }
iPad 1 & 2 Media Queries
If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!
iPad 1 & 2 in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}
iPad 1 & 2 in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */}
iPad 1 & 2 in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }
Source: http://stephen.io/mediaqueries/
sudo apt-get remove --purge mysql*
Remove the MySQL packages fully from the target system.
sudo apt-get purge mysql*
Remove all mysql related configuration files.
sudo apt-get autoremove
Clean up unused dependencies using autoremove command.
sudo apt-get autoclean
To clear all local repository in the target system.
sudo apt-get remove dbconfig-mysql
If you also want to delete your local/config files for dbconfig-mysql then this will work.
Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host')
is deprecated, that's why giving Undefined
.
Use,
req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
static final PcapLinkType[] values = { DLT_NULL, DLT_EN10MB, DLT_EN3MB, null ...}
...
public static PcapLinkType getPcapLinkTypeForInt(int num){
try{
return values[int];
}catch(ArrayIndexOutOfBoundsException e){
return DLT_UKNOWN;
}
}
The question is with JQuery, it's just FYI.
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
yourBtnID.style.display = 'none';
if (textareaID.value.length) {
yourBtnID.style.display = 'inline-block';
}
});
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>
I see that we have (beside others) basically two options:
a.sort_by { |h| -h[:bar] }
and
a.sort_by { |h| h[:bar] }.reverse
While both ways give you the same result when your sorting key is unique, keep in mind that the reverse
way will reverse the order of keys that are equal.
Example:
a = [{foo: 1, bar: 1},{foo: 2,bar: 1}]
a.sort_by {|h| -h[:bar]}
=> [{:foo=>1, :bar=>1}, {:foo=>2, :bar=>1}]
a.sort_by {|h| h[:bar]}.reverse
=> [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]
While you often don't need to care about this, sometimes you do. To avoid such behavior you could introduce a second sorting key (that for sure needs to be unique at least for all items that have the same sorting key):
a.sort_by {|h| [-h[:bar],-h[:foo]]}
=> [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]
a.sort_by {|h| [h[:bar],h[:foo]]}.reverse
=> [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
I recently faced this same situation and found an easier inbuilt solution. I am sharing it here so that it might help other people looking for solution.
With OS X Yosemite, Apple has integrated the batch renaming capabilities directly into Finder. Details information is available here. I have copied the steps below as well,
Rename multiple items
Select the items, then Control-click one of them.
In the shortcut menu, select Rename Items.
In the pop-up menu below Rename Folder Items, choose to replace text in the names, add text to the names, or change the name format.
Replace text: Enter the text you want to remove in the Find field, then enter the text you want to add in the “Replace with” field.
Add text: Enter the text to you want to add in the field, then choose to add the text before or after the current name.
Format: Choose a name format for the files, then choose to put the index, counter, or date before or after the name. Enter a name in the Custom Format field, then enter the number you want to start with.
Click Rename.
If you have a common pattern in your files than you can use Replace text otherwise Add text would also do the job.
It looks like the machine you're trying to run this on has only 256 MB memory.
Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.
Try starting your Java program with a smaller heap size, for example:
java -Xms16m ...
You can use this:
fig = plt.figure()
ax = fig.add_subplot(221)
plt.plot(x,y)
ax = fig.add_subplot(222)
plt.plot(x,z)
...
plt.show()
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
const target = event.target_x000D_
if (target.files && target.files[0]) {_x000D_
_x000D_
/*Maximum allowed size in bytes_x000D_
5MB Example_x000D_
Change first operand(multiplier) for your needs*/_x000D_
const maxAllowedSize = 5 * 1024 * 1024;_x000D_
if (target.files[0].size > maxAllowedSize) {_x000D_
// Here you can ask your users to load correct file_x000D_
target.value = ''_x000D_
}_x000D_
}_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".
I created a project to easily initiate a project skeleton from scratch. https://github.com/MacHu-GWU/pygitrepo-project.
And you can create a test project, let's say, learn_creating_py_package
.
You can learn what component you should have for different purpose like:
The advantage of using pygitrepo
is that those tedious are automatically created itself and adapt your package_name
, project_name
, github_account
, document host service
, windows or macos or linux
.
It is a good place to learn develop a python project like a pro.
Hope this could help.
Thank you.
To brute force all CSV files on your server to download, add in your .htaccess file:
AddType application/octet-stream csv
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
Another possibility is
var res = /!id-[^!]*/.exec("!"+windowArray.join("!"));
return res && res[0].substr(1);
that IMO may make sense if you can have a special char delimiter (here i used "!"), the array is constant or mostly constant (so the join can be computed once or rarely) and the full string isn't much longer than the prefix searched for.
OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:
openapi: 3.0.0
...
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT # optional, for documentation purposes only
security:
- bearerAuth: []
This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).
UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx
header.
Authorization
header programmatically (Swagger UI 3.x)If you use Swagger UI and, for some reason, need to add the Authorization
header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor
. This solution is for Swagger UI 3.x; UI 2.x used a different technique.
// index.html
const ui = SwaggerUIBundle({
url: "http://your.server.com/swagger.json",
...
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer xxxxxxx"
return req
}
})
For this particular case, if using re
module is overkill, how about using split
(or rsplit
) method as
se='</html>'
z.write(article.split(se)[0]+se)
For example,
#!/usr/bin/python
article='''<html>Larala
Ponta Monta
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')
se='</html>'
z.write(article.split(se)[0]+se)
outputs out.txt
as
<html>Larala
Ponta Monta
</html>
I used the answer by @Spenhouet and added more "replacements"-possibilities than "*". For example "?". Just add your needs to the dict in replaceHelper
.
/**
* @param {string} str
* @param {string} rule
* checks match a string to a rule
* Rule allows * as zero to unlimited numbers and ? as zero to one character
* @returns {boolean}
*/
function matchRule(str, rule) {
const escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + replaceHelper(rule, {"*": "\\d*", "?": ".?"}, escapeRegex) + "$").test(str);
}
function replaceHelper(input, replace_dict, last_map) {
if (Object.keys(replace_dict).length === 0) {
return last_map(input);
}
const split_by = Object.keys(replace_dict)[0];
const replace_with = replace_dict[split_by];
delete replace_dict[split_by];
return input.split(split_by).map((next_input) => replaceHelper(next_input, replace_dict, last_map)).join(replace_with);
}
Its already been said a few times but http://www.proggyfonts.com/ is just awesome. Im a big fan of the Proggy Clean Slashed Zero Bold Punctuation. I do most my work in c# so the bold punctuation is very nice for it.
Well, there are two types of wait: explicit and implicit wait. The idea of explicit wait is
WebDriverWait.until(condition-that-finds-the-element);
The concept of implicit wait is
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
You can get difference in details here.
In such situations I'd prefer using explicit wait (fluentWait
in particular):
public WebElement fluentWait(final By locator) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
});
return foo;
};
fluentWait
function returns your found web element.
From the documentation on fluentWait
:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
Details you can get here
Usage of fluentWait
in your case be the following:
WebElement textbox = fluentWait(By.id("textbox"));
This approach IMHO better as you do not know exactly how much time to wait and in polling interval you can set arbitrary timevalue which element presence will be verified through . Regards.
I feel that this solution is dirty, but here we go:
componentDidMount() {
this.componentDidUpdate()
}
componentDidUpdate() {
// A whole lotta functions here, fired after every render.
}
Now I am just going to sit here and wait for the down votes.
I got same error. Because i used v4 alpha class names like carousel-control-next
When i changed with v3, problem solved.
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
The controller
function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model
changes coming from View
the Controller
is the right person to do that job.
The story about link
function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view
(template).
Let' start with the parameters which are passed into the link
function:
function link(scope, element, attrs) {
To put the link
into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:
Compile phase (a sister of link, let's mention it here to get a clear picture):
In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,
Link phase:
To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.
A nice example how to use the link
could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.
Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks
.directive('myCurrentTime', function($timeout, dateFilter) {
function link(scope, element, attrs) {
...
// the not MVC job must be done
function updateTime() {
element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
}
function scheduleUpdate() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
scheduleUpdate(); // schedule the next update
}, 1000);
}
element.on('$destroy', function() {
$timeout.cancel(timeoutId);
});
...
You can do this way:
scp hostname@serverNameOrServerIp:/path/to/files/\\{file1,file2,file3\\}.fileExtension ./
This will download all the listed filenames to whatever local directory you're on.
Make sure not to put spaces between each filename only use a comma ,
.
INSERTED
and DELETED
are virtual tables. They need to be used in a FROM
clause.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
IF EXISTS (SELECT foo
FROM database2.dbo.table2
WHERE id IN (SELECT deleted.id FROM deleted)
AND bar = 4)
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I had a similar problem, but I was using initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
explicitly using the name of the class as the string passed (yes bad form!).
I ended up deleting and re-creating the view controller using a slightly different name but neglected to change the string specified in the method, thus my old version was still used - even though it was in the trash!
I will likely use this structure going forward as suggested in: Is passing two nil paramters to initWithNibName:bundle: method bad practice (i.e. unsafe or slower)?
- (id)init
{
[super initWithNibName:@"MyNib" bundle:nil];
... typical initialization ...
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self init];
}
Hopefully this helps someone!
the string in your question is not a valid json string. From json.org website:
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Basically a json string will always start with either { or [.
Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.
IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.
Sample here:
<Style TargetType="Window" x:Key="DialogWindow">
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}" Background="Gray">
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Height="35" Grid.ColumnSpan="2"
x:Name="PART_WindowHeader"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
<Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
</Grid>
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="LightBlue" CornerRadius="0,0,10,10"
Grid.ColumnSpan="2"
Grid.RowSpan="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>
</Grid>
</Border>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You have asked two questions, one in the title about the difference between PNG8 and PNG24, which has received a few answers, namely that PNG24 has 8-bit red, green, and blue channels, and PNG-8 has a single 8-bit index into a palette. Naturally, PNG24 usually has a larger filesize than PNG8. Furthermore, PNG8 usually means that it is opaque or has only binary transparency (like GIF); it's defined that way in ImageMagick/GraphicsMagick.
This is an answer to the other one, "I would like to know that if I use either type in my html page, will there be any error? Or is this only quality matter?"
You can put either type on an HTML page and no, this won't cause an error; the files should all be named with the ".png" extension and referred to that way in your HTML. Years ago, early versions of Internet Explorer would not handle PNG with an alpha channel (PNG32) or indexed-color PNG with translucent pixels properly, so it was useful to convert such images to PNG8 (indexed-color with binary transparency conveyed via a PNG tRNS chunk) -- but still use the .png extension, to be sure they would display properly on IE. I think PNG24 was always OK on Internet Explorer because PNG24 is either opaque or has GIF-like single-color transparency conveyed via a PNG tRNS chunk.
The names PNG8 and PNG24 aren't mentioned in the PNG specification, which simply calls them all "PNG". Other names, invented by others, include
There are many more possible combinations including grayscale with 1, 2, 4, 8, or 16-bit samples and indexed PNG with 1, 2, or 4-bit samples (and any of those with transparent or translucent pixels), but those don't have special names.
It may also be usefull to understand the difference in term of Session Bean Identity when using @EJB and @Inject.
According to the specifications the following code will always be true
:
@EJB Cart cart1;
@EJB Cart cart2;
… if (cart1.equals(cart2)) { // this test must return true ...}
Using @Inject instead of @EJB there is not the same.
see also stateless session beans identity for further info
I did different tests on the typescript playground:
http://www.typescriptlang.org/play/
let a;
let b = null;
let c = "";
var output = "";
if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";
console.log(output);
gives:
a is null or undefined
b is null or undefined
c is defined
so:
A dirty trick I somtimes use, is hiding variables in the 'name' attribute (that I normally don't use for other purposes):
select onFocus=(this.name=this.value) onChange=someFunction(this.name,this.value)><option...
Somewhat unexpectedly, both the old and the new value is then submitted to someFunction(oldValue,newValue)
This would work too
git branch --set-upstream-to=/< remote>/< branch> < localbranch>
$time = '10:09';
$timestamp = strtotime($time);
$timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour
// Formats the timestamp to HH:MM => outputs 11:09.
echo strftime('%H:%M', $timestamp_one_hour_later);
// As crolpa suggested, you can also do
// echo date('H:i', $timestamp_one_hour_later);
Check PHP manual for strtotime(), strftime() and date() for details.
BTW, in your initial code, you need to add some quotes otherwise you will get PHP syntax errors:
$time = 10:09; // wrong syntax
$time = '10:09'; // syntax OK
$time = date(H:i, strtotime('+1 hour')); // wrong syntax
$time = date('H:i', strtotime('+1 hour')); // syntax OK
I had the same problem but with Chrome.
Solved it using the following steps
Here's the code and it worked fine
from selenium import webdriver
class InstaBot(object):
def __init__(self):
self.driver=webdriver.Chrome("C:\Program
Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure
#it is chrome driver
self.driver.get("https://www.wikipedia.com")
InstaBot()
$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });
Another cause of this can be duplicate keys in your KeyChain. I've seen this problem on two macs where there were duplicate "DigiCert High Assurance EV Root CA". One was in the login keychain, the other in the system one. Removing the certificate from the login keychain solved the problem.
This affected Safari browser as well as git on the command line.
The cleaner solution without NullPointerException is:
map.replace(key, map.get(key) + 1);
LIMIT 1
is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order
clause in an outer query).
If you haven't yet pushed your changes, you can also do a soft reset:
git reset --soft HEAD^
This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:
git checkout branch
git commit
The disadvantage is that you need to re-enter your commit message.
Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.
document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true; if (evt.stopPropagation) evt.stopPropagation},false);
Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.
Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)
well, there was 2 issues: 1.instead of pip, pip3 should be used. 2.its better to use virtual env. because i have had multiple python version installed
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];
NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter
NSString *URLString =@"your url string";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
// [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Response DICT:%@",response);
if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
{
[yourNsmutableArray addObject:[dicAll mutableCopy]];
}
//yourNsmutableArray Nsmutablearray alloction in view didload
NSLog(@"yourNsmutableArray %@",yourNsmutableArray);
}
else
{
NSLog(@"False");
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
NSLog(@"RESPONSE STRING:%@",task.response);
NSLog(@"error userInfo:%@",error.userInfo);
NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"URLString :--->> %@ Error********* %@",URLString,errResponse);
[SVProgressHUD dismiss];
}];
You can use plt.subplots_adjust to change the spacing between the subplots Link
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
UPDATED: assuming C# 6, the chances are that your case can be expressed as an exception filter. This is the ideal approach from a performance perspective assuming your requirement can be expressed in terms of it, e.g.:
try
{
}
catch ( Web2PDFException ex ) when ( ex.Code == 52 )
{
}
Assuming C# < 6, the most efficient is to catch a specific Exception
type and do handling based on that. Any catch-all handling can be done separately
try
{
}
catch ( Web2PDFException ex )
{
}
or
try
{
}
catch ( Web2PDFException ex )
{
}
catch ( Exception ex )
{
}
or (if you need to write a general handler - which is generally a bad idea, but if you're sure it's best for you, you're sure):
if( err is Web2PDFException)
{
}
or (in certain cases if you need to do some more complex type hierarchy stuff that cant be expressed with is
)
if( err.GetType().IsAssignableFrom(typeof(Web2PDFException)))
{
}
or switch to VB.NET or F# and use is
or Type.IsAssignableFrom
in Exception Filters
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this
points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
EDITED after @ErdemKAYA comment.
To erase a variable, use the magic command:
%reset_selective <regular_expression>
The variables that are erased from the namespace are the one matching the given <regular_expression>
.
Therefore
%reset_selective -f a
will erase all the variables containing an a
.
Instead, to erase only a
and not aa
:
In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a # raise NameError
In: aa # returns 2
see as well %reset_selective?
for more examples and https://regexone.com/ for a regex tutorial.
To erase all the variables in the namespace see:
%reset?
You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD
).
For example: git svn clone -s -r1450:HEAD some/svn/repo
Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n
commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.
Let us have List<Object> objectList
which we want to cast to List<T>
public <T> List<T> list(Class<T> c, List<Object> objectList){
List<T> list = new ArrayList<>();
for (Object o : objectList){
T t = c.cast(o);
list.add(t);
}
return list;
}
$(window).height()
$(window).width()
There is also a plugin to jquery to determine element location and offsets
http://plugins.jquery.com/project/dimensions
scrolling offset = offsetHeight property of an element
In the notation
u'Capit\xe1n\n'
the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write
Capit\xc3\xa1n
into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".
Edit:
As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.
If you actually have a string in this format you can use the string_escape
codec to decode it into a normal string:
In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
Capitán
The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1
in the original string. If you want to have a unicode string you have to decode again with UTF-8.
To your edit: you don't have UTF-8 in your file. To actually see how it would look like:
s = u'Capit\xe1n\n'
sutf8 = s.encode('UTF-8')
open('utf-8.out', 'w').write(sutf8)
Compare the content of the file utf-8.out
to the content of the file you saved with your editor.
& 0xFF
by itself only ensures that if bytes are longer than 8 bits (allowed by the language standard), the rest are ignored.
And that seems to work fine too?
If the result ends up greater than SHRT_MAX
, you get undefined behavior. In that respect both will work equally poorly.
As to why, no idea.
A reset will most certainly fix this:
ul { margin: 0; padding: 0; }
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
You do not need to use substring at all since your format
doesn't hold that info.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";
Date fechaNueva = format.parse(fechaStr);
System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
You need 10 ÷R 3 = 1 This will display both the reminder and the quoitent
Try it:
def showDf(df, count=None, percent=None, maxColumns=0):
if (df == None): return
import pandas
from IPython.display import display
pandas.set_option('display.encoding', 'UTF-8')
# Pandas dataframe
dfp = None
# maxColumns param
if (maxColumns >= 0):
if (maxColumns == 0): maxColumns = len(df.columns)
pandas.set_option('display.max_columns', maxColumns)
# count param
if (count == None and percent == None): count = 10 # Default count
if (count != None):
count = int(count)
if (count == 0): count = df.count()
pandas.set_option('display.max_rows', count)
dfp = pandas.DataFrame(df.head(count), columns=df.columns)
display(dfp)
# percent param
elif (percent != None):
percent = float(percent)
if (percent >=0.0 and percent <= 1.0):
import datetime
now = datetime.datetime.now()
seed = long(now.strftime("%H%M%S"))
dfs = df.sample(False, percent, seed)
count = df.count()
pandas.set_option('display.max_rows', count)
dfp = dfs.toPandas()
display(dfp)
Examples of usages are:
# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)
# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15)
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
Change from @Controller to @Service to CompteController and add @Service annotation to CompteDAOHib. Let me know if you still face this issue.
As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;
//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;
printf("conver is now %f\n",conver);
return 0;
}
I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.
I think your cron is not correct. According to what you described, you may need to change cron schedule to
*/5 * * * *
What you put in your schedule now mean it will poll the SCM at 5 past of every hour.
From Ian Bicking's own introduction to pip:
pip was originally written to improve on easy_install in the following ways
- All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
- Care is taken to present useful output on the console.
- The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
- Error messages should be useful.
- The code is relatively concise and cohesive, making it easier to use programmatically.
- Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
- Native support for other version control systems (Git, Mercurial and Bazaar)
- Uninstallation of packages.
- Simple to define fixed sets of requirements and reliably reproduce a set of packages.
The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.
SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';
Any seaborn plots suported by facetgrid won't work with (e.g. catplot)
g.set_xticklabels(rotation=30)
however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.
g.set_xticklabels(g.get_xticklabels(), rotation=30)
Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.
Let us first try to understand the root cause as to why it is happening in first place.
Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script
tags (present in head
section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head
tag are trying to access an element having id hello
even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.
How can you make it work as before?
You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello
id element is accessible/available. It is achievable in two ways:
hello
id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body
tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error. <!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="hello"></div>_x000D_
_x000D_
<script type ="text/javascript">_x000D_
what();_x000D_
function what(){_x000D_
document.getElementById('hello').innerHTML = 'hi';_x000D_
};_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
window.onload
event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with hello
id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head
tag. <!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
<title>Untitled Document</title>_x000D_
<script type ="text/javascript">_x000D_
window.onload = function() {_x000D_
what();_x000D_
function what(){_x000D_
document.getElementById('hello').innerHTML = 'hi';_x000D_
};_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="hello"></div>_x000D_
</body>_x000D_
</html>
_x000D_
I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.
for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d
pushd %curdir%
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
Write all your code below this 2 lines:-
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
It worked for me without re-installing again.
I think you have not fonts folder in your root folder like where stay css folder.
Demo
And css folder is like
And fonts folder like
I hope it will work for you.
Thanks you.
F4 doesn't always bring me to this panel. Besides, it is often said that a picture is worth a thousand words.
Use the ->pluck() method
$roles = DB::table('roles')->pluck('title');
If you would like to retrieve an array containing the values of a single column, you may use the pluck method
Use the ->lists() method
$roles = DB::table('roles')->lists('title');
This method will return an array of role titles. You may also specify a custom key column for the returned array:
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
I had to combine Maiasaura and Svun answers to get it to work: using setwd and escaping all the slashes and spaces.
setwd('C:\\Users\\firstname\ lastname\\Desktop\\folder1\\folder2\\folder3')
data = read.csv("file.csv")
data
This solved the issue for me.
This Works well
jQuery('.id_100').change(function(){
var value = jQuery('.id_100').val(); //it gets you the value of selected option
console.log(value); // you can see your sected values in console, Eg 1,2,3
});
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
If you are using the SQL Management Studio, you can right click your DB name and select
Tasks > Import/Export data and follow the wizard.
one of the steps is called "Specify Table Copy or Query" where there is an option to write a query to specify the data to transfer, so you can simply specify the following query:
select * from [Table] where Fk_CompanyId = 1
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
For example, if you have a multiple buttons that look the same, you should use class="mybutton" to have consistent styling.
In terms of performance:
CSS selectors are matched from right to left.
Therefore, .myClass should be "faster" than #myID because it misses out testing.
The performance speed is negligible for normally sized pages and you will probably never notice a difference so it's mostly just about convention.
Here is more info on why css is browsers match css selectors from right to left
try using concatenation of string
Statistics(string date)
{
this->date += date;
}
acually this was a part of a class..
Yes there is.
But OCR is very vast. I know an Android application that has an OCR feature, but that might not be the kind of OCR you are looking after.
This open-source application is called Aedict, and it does OCR on handwritten Japanese characters. It is not that slow.
If it is not what you are looking for, please precise which kind of characters, and which data input (image or X-Y touch history).
Very simply, and cobbling together some of the great comments here along with my own research into this.
First, check out the local branch you want to tie to your remote branch:
git checkout mybranch
Next:
git branch -u origin/mybranch
where:
git branch -u {remote name}/{branch name}
You should get a message:
"Branch mybranch set up to track remote branch mybranch from origin."
This answer accepts some edge cases that others don't:
1.000.000
=> 1000000
1.000e3
=> 1000e3
(1 million)Run the code snippet to see all the test suite.
const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINNING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g
export function formatNumber(number) {
// Handle exponentials
if ((number.match(/e/g) ?? []).length === 1) {
const numberParts = number.split('e')
return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
}
const sanitizedNumber = number
.replace(REGEX_UNWANTED_CHARACTERS, '')
.replace(REGEX_DASHES_EXEPT_BEGINING, '')
// Handle only thousands separator
if (
((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
) {
return sanitizedNumber.replace(/[.,]/g, '')
}
return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}
function formatNumberToNumber(number) {
return Number(formatNumber(number))
}
const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g
function formatNumber(number) {
if ((number.match(/e/g) ?? []).length === 1) {
const numberParts = number.split('e')
return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
}
const sanitizedNumber = number
.replace(REGEX_UNWANTED_CHARACTERS, '')
.replace(REGEX_DASHES_EXEPT_BEGINING, '')
if (
((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
) {
return sanitizedNumber.replace(/[.,]/g, '')
}
return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}
const testCases = [
'1',
'1.',
'1,',
'1.5',
'1,5',
'1,000.5',
'1.000,5',
'1,000,000.5',
'1.000.000,5',
'1,000,000',
'1.000.000',
'-1',
'-1.',
'-1,',
'-1.5',
'-1,5',
'-1,000.5',
'-1.000,5',
'-1,000,000.5',
'-1.000.000,5',
'-1,000,000',
'-1.000.000',
'1e3',
'1e-3',
'1e',
'-1e',
'1.000e3',
'1,000e-3',
'1.000,5e3',
'1,000.5e-3',
'1.000,5e1.000,5',
'1,000.5e-1,000.5',
'',
'a',
'a1',
'a-1',
'1a',
'-1a',
'1a1',
'1a-1',
'1-',
'-',
'1-1'
]
document.getElementById('tbody').innerHTML = testCases.reduce((total, input) => {
return `${total}<tr><td>${input}</td><td>${formatNumber(input)}</td></tr>`
}, '')
_x000D_
<table>
<thead><tr><th>Input</th><th>Output</th></tr></thead>
<tbody id="tbody"></tbody>
</table>
_x000D_
If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently
$ ssh-keygen -y -f mykey.pem > mykey.pub
This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys
and you'll be good to go
docs from SSH-KEYGEN(1)
ssh-keygen -y [-f input_keyfile]
-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
If you are using Angular 8+ and you want to reduce the size of the bundle you can use Ivy. Ivy comes as the default view engine in Angular 9 Just go to src/tsconfig.app.json and add the angularCompilerOptions parameter, for example:
{
"extends": ...,
"compilerOptions":...,
"exclude": ...,
/* add this one */
"angularCompilerOptions": {
"enableIvy": true
}
}
pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.
After an afternoon of swearing I went for putting the following in my start script:
(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
^[0-9]{1,45}$
is correct.
According to the standard, you should be safe with that assumption. The C++ bool
type has two values - true
and false
with corresponding values 1 and 0.
The thing to watch about for is mixing bool
expressions and variables with BOOL
expression and variables. The latter is defined as FALSE = 0
and TRUE != FALSE
, which quite often in practice means that any value different from 0 is considered TRUE
.
A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL
to bool
if the BOOL
value is different than 0 or 1.
Adding on to Josh's answer,
SELECT COUNT(CASE WHEN myColumn=1 THEN AD_CurrentView.PrimaryKeyColumn ELSE NULL END)
FROM AD_CurrentView
Worked well for me (in SQL Server 2012) without changing the 'count' to a 'sum' and the same logic is portable to other 'conditional aggregates'. E.g., summing based on a condition:
SELECT SUM(CASE WHEN myColumn=1 THEN AD_CurrentView.NumberColumn ELSE 0 END)
FROM AD_CurrentView
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
In the early days of gcc (2.8 etc.) and in the times of egcs, and redhat 2.96 -O3 was quite buggy sometimes. But this is over a decade ago, and -O3 is not much different than other levels of optimizations (in buggyness).
It does however tend to reveal cases where people rely on undefined behavior, due to relying more strictly on the rules, and especially corner cases, of the language(s).
As a personal note, I am running production software in the financial sector for many years now with -O3 and have not yet encountered a bug that would not have been there if I would have used -O2.
By popular demand, here an addition:
-O3 and especially additional flags like -funroll-loops (not enabled by -O3) can sometimes lead to more machine code being generated. Under certain circumstances (e.g. on a cpu with exceptionally small L1 instruction cache) this can cause a slowdown due to all the code of e.g. some inner loop now not fitting anymore into L1I. Generally gcc tries quite hard to not to generate so much code, but since it usually optimizes the generic case, this can happen. Options especially prone to this (like loop unrolling) are normally not included in -O3 and are marked accordingly in the manpage. As such it is generally a good idea to use -O3 for generating fast code, and only fall back to -O2 or -Os (which tries to optimize for code size) when appropriate (e.g. when a profiler indicates L1I misses).
If you want to take optimization into the extreme, you can tweak in gcc via --param the costs associated with certain optimizations. Additionally note that gcc now has the ability to put attributes at functions that control optimization settings just for these functions, so when you find you have a problem with -O3 in one function (or want to try out special flags for just that function), you don't need to compile the whole file or even whole project with O2.
otoh it seems that care must be taken when using -Ofast, which states:
-Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard compliant programs.
which makes me conclude that -O3 is intended to be fully standards compliant.
Long answer to short, if you install boost in custom path, all header files must in ${path}/boost/.
if you want to konw why cmake can't find the requested Boost libraries after you have set BOOST_ROOT/BOOST_INCLUDEDIR
, you can check cmake install location path_to_cmake/share/cmake-xxx/Modules/FindBoost
.
cmake which will find Boost_INCLUDE_DIR
in boost/config.hpp
in BOOST_ROOT
. That means your boost header file must in ${path}/boost/
, any other format (such as ${path}/boost-x.y.z
) will not be suitable for find_package
in CMakeLists.txt.
It points to the docker host! I followed these steps:
$ boot2docker start
Waiting for VM and Docker daemon to start...
..............................
Started.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp://192.168.59.103:2375
$ export DOCKER_HOST=tcp://192.168.59.103:2375
$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete
511136ea3c5a: Download complete
97fd97495e49: Download complete
2dcbbf65536c: Download complete
6a459d727ebb: Download complete
8f321fc43180: Download complete
03db2b23cf03: Download complete
Hello world
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.
For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.
Extrapolating from Edwin's answer:
from math import ceil, floor
def float_round(num, places = 0, direction = floor):
return direction(num * (10**places)) / float(10**places)
To use:
>>> float_round(0.21111, 3, ceil) #round up
>>> 0.212
>>> float_round(0.21111, 3) #round down
>>> 0.211
>>> float_round(0.21111, 3, round) #round naturally
>>> 0.211
I prefer to upgrade all homebrew formulae and homebrew cask formulae.
I added a Bourne shell function to my environment for this one (I load a .bashrc)
function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
set -x
for transparency: So that the terminal outputs whatever Homebrew is doing in the background.brew update
to update homebrew formulasbrew cleanup
to remove any change left over after installationsbrew cask upgrade --greedy
will install all casks; both those with versioning information and those withouttype on terminal:
nano ~/.bash_profile
then paste:
export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"
then save (press ctrl+c, press Y, press enter)
now you are ready to use "laravel" on your terminal
here is a demo
first you need to correct your syntax error its
display: table-cell;
not diaplay: table-cell;
.container {
display: table;
border-collapse:collapse
}
.column {
display:table-row;
}
.cell {
display: table-cell;
border: 1px solid red;
width: 120px;
height: 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
You can take a look to the article Design and Implementation of an In-Game Memory Profiler in the book "Game Programming Gems 8".
It shows how to implement a low overhead semi-intrusive real-time memory profiler, source code provided in the CD-ROM.
Might I suggest giving QueryStorm a try - it's a plugin for Excel that makes it quite convenient to use SQL in Excel.
Also, it's freemium. If you don't care about autocomplete, error squigglies etc, you can use it for free. Just download and install, and you have SQL support in Excel.
Disclaimer: I'm the author.
This is a tricky one. I could not find a way to select the 'no file chosen' element so I created a mask using the :after pseudo selector.
My solution also requires the use of the following pseudo selector to style the button:
::-webkit-file-upload-button
Try this: http://jsfiddle.net/J8Wfx/1/
FYI: This will only work in webkit browsers.
P.S if anyone knows how to view webkit pseudo selectors like the one above in the webkit inspector please let me know
Use Number
from the numbers
module to test isinstance(n, Number)
(available since 2.6).
isinstance(n, numbers.Number)
Here it is in action with various kinds of numbers and one non-number:
>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
... print '%15s %s' % (n.__repr__(), isinstance(n, Number))
2 True
2.0 True
Decimal('2.0') True
(2+0j) True
Fraction(2, 1) True
'2' False
This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.
From PHP 5.4
function array2xml($data, $root = null){
$xml = new SimpleXMLElement($root ? '<' . $root . '/>' : '<root/>');
array_walk_recursive($data, function($value, $key)use($xml){
$xml->addChild($key, $value);
});
return $xml->asXML();
}
You should use a callback parameter:
function Typer(callback)
{
var srcText = 'EXAMPLE ';
var i = 0;
var result = srcText[i];
var interval = setInterval(function() {
if(i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
},
100);
return true;
}
function playBGM () {
alert("Play BGM function");
$('#bgm').get(0).play();
}
Typer(function () {
playBGM();
});
// or one-liner: Typer(playBGM);
So, you pass a function as parameter (callback
) that will be called in that if
before return
.
Also, this is a good article about callbacks.
function Typer(callback)_x000D_
{_x000D_
var srcText = 'EXAMPLE ';_x000D_
var i = 0;_x000D_
var result = srcText[i];_x000D_
var interval = setInterval(function() {_x000D_
if(i == srcText.length - 1) {_x000D_
clearInterval(interval);_x000D_
callback();_x000D_
return;_x000D_
}_x000D_
i++;_x000D_
result += srcText[i].replace("\n", "<br />");_x000D_
$("#message").html(result);_x000D_
},_x000D_
100);_x000D_
return true;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
alert("Play BGM function");_x000D_
$('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
Fixed by adding Google Play Services to my Module:app gradle build file. Documentation also says to update version when you update GMS.
dependencies {
compile 'com.google.android.gms:play-services:9.6.1'
}
In the controller:
$scope.entityId = $routeParams.entityId;
In the view:
<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />
Under Excel 2016 and up (including Office 365), there is a CSV option dedicated to the UTF-8 format.
In Office 365, do Save As; where previously one might have chosen CSV (Comma Delimited), now one of the file types you can save as is CSV UTF-8 (Comma delimited) (*.csv)
In addition, you can build the binary package using the --binary option.
R CMD build --binary RJSONIO_0.2-3.tar.gz
I'd say the first, if the array is associative. If not, use a for
loop:
for ($i = 0; $i < count($array); $i++) { unset($array[$i]); }
Although if possible, using
$array = array();
To reset the array to an empty array is preferable.
Demo here
Try this one
$('html').on('click', 'a.Link', function(event){
event.preventDefault();
});
Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In public class Startup
add a property
public IConfigurationRoot Configuration { get; }
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
Then in Configure
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
add the DI Parameter IServiceProvider svp
, so the method looks like:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
Next, create a replacement class for System.Web:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
Now in Configure, where you added the IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)
and set HostingEnvironment.IsHosted to true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start
in global.asax.
I stress again, this only works if you actually added
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
And then calling HttpContext.Configure in Startup->Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
This article explains all the details http://kunststube.net/encoding/
WRITING TO BUFFER
if you write to a 4 byte buffer, symbol ?
with UTF8 encoding, your binary will look like this:
00000000 11100011 10000001 10000010
if you write to a 4 byte buffer, symbol ?
with UTF16 encoding, your binary will look like this:
00000000 00000000 00110000 01000010
As you can see, depending on what language you would use in your content this will effect your memory accordingly.
e.g. For this particular symbol: ?
UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.
READING FROM BUFFER
Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.
e.g. If you decode this :
00000000 11100011 10000001 10000010
into UTF16 encoding, you will end up with ?
not ?
Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ?
symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.
30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.
30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
This is a 100% solution. I tried it myself.
myisamchk -r -v -f --sort_buffer_size=128M --key_buffer_size=128M /var/lib/mysql/databasename/tabloname
Try os.chdir
os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.
You need this instead:
if(s.contains("+"))
contains()
method of String
class does not take regular expression as a parameter, it takes normal text.
EDIT:
String s = "ddjdjdj+kfkfkf";
if(s.contains("+"))
{
String parts[] = s.split("\\+");
System.out.print(parts[0]);
}
OUTPUT:
ddjdjdj
Starting with VB.NET 10, implicit line continuation is supported for a number of syntax elements (see Statements in Visual Basic: Continuing a Statement over Multiple Lines). The concatenation operator (&) is in the list of syntax elements, that support implicit line continuation. Interspersed comments are supported as well, so your second example could be rewritten as:
dim createArticle as string =
"Create table article " &
" (articleID int " & ' Comment for articleID
" ,articleName varchar(50) " & ' Comment for articleName
" )"
Implicit line continuation also works for query operators, with a few restrictions:
Before and after query operators (Aggregate, Distinct, From, Group By, Group Join, Join, Let, Order By, Select, Skip, Skip While, Take, Take While, Where, In, Into, On, Ascending, and Descending). You cannot break a line between the keywords of query operators that are made up of multiple keywords (Order By, Group Join, Take While, and Skip While).
Again, interspersed comments are allowed, so your first example can be rewritten as:
dim results = from a in articles
where a.articleID = 4 ' articleID - now perfectly legal
select a.articleName
One instance where using a try-catch might be appropriate is when using a forEach loop. It is synchronous but at the same time you cannot just use a return statement in the inner scope. Instead a try and catch approach can be used to return an Error object in the appropriate scope. Consider:
function processArray() {
try {
[1, 2, 3].forEach(function() { throw new Error('exception'); });
} catch (e) {
return e;
}
}
It is a combination of the approaches described by @balupton above.
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
Minimal POSIX C exit status example
To understand $?
, you must first understand the concept of process exit status which is defined by POSIX. In Linux:
when a process calls the exit
system call, the kernel stores the value passed to the system call (an int
) even after the process dies.
The exit system call is called by the exit()
ANSI C function, and indirectly when you do return
from main
.
the process that called the exiting child process (Bash), often with fork
+ exec
, can retrieve the exit status of the child with the wait
system call
Consider the Bash code:
$ false
$ echo $?
1
The C "equivalent" is:
false.c
#include <stdlib.h> /* exit */
int main(void) {
exit(1);
}
bash.c
#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */
int main(void) {
if (fork() == 0) {
/* Call false. */
execl("./false", "./false", (char *)NULL);
}
int status;
/* Wait for a child to finish. */
wait(&status);
/* Status encodes multiple fields,
* we need WEXITSTATUS to get the exit status:
* http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
**/
printf("$? = %d\n", WEXITSTATUS(status));
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash
Output:
$? = 1
In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $?
to the exit status of the forked process.
Note: for built-in commands like echo
, a process need not be spawned, and Bash just sets $?
to 0 to simulate an external process.
Standards and documentation
POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :
? Expands to the decimal exit status of the most recent pipeline (see Pipelines).
man bash
"Special Parameters":
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]
? Expands to the exit status of the most recently executed foreground pipeline.
ANSI C and POSIX then recommend that:
0
means the program was successful
other values: the program failed somehow.
The exact value could indicate the type of failure.
ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?
Bash uses exit status for if
In Bash, we often use the exit status $?
implicitly to control if
statements as in:
if true; then
:
fi
where true
is a program that just returns 0.
The above is equivalent to:
true
result=$?
if [ $result = 0 ]; then
:
fi
And in:
if [ 1 = 1 ]; then
:
fi
[
is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ]
its arguments, see also: Difference between single and double square brackets in Bash
Either there's a error in your code or you are out of memory, you can upgrade it or for for quick solution try increasing your virtual memory.
Not padding but if your goal is to simply make it larger, you can increase the font-size
. And using it with font-size-adjust
reduces the font-size back to normal on select and not on options, so it ends up making the option
larger.
Not sure if it works on all browsers, or will keep working in current.
Tested on Chrome 85 & Firefox 81.
select {
font-size: 2em;
font-size-adjust: 0.3;
}
_x000D_
<label>
Select: <select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</label>
_x000D_
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
I had the same issue and took a whole day to figure out the problem. This error message by Facebook SDK is very vague. I had this problem due to openURL: method being overwritten in MyApplication. I removed the overwritten method and facebook login worked fine.
I cannot install an apk build with "Export Unsigned Application Package" Android SDK feature, but i can install an apk browsing the bin directory of my project after the project buid. I put this apk on my sd on my HTC Wildfire phone, select it and the application install correctly. You need to allow your phone to install unsigned apk. Good Luck.
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
Use mysqladmin
to kill the runaway query:
Run the following commands:
mysqladmin -uusername -ppassword pr
Then note down the process id.
mysqladmin -uusername -ppassword kill pid
The runaway query should no longer be consuming resources.
Faster solution:
private boolean isPackageInstalled(String packagename, PackageManager packageManager) {
try {
packageManager.getPackageGids(packagename);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
getPackageGids
is less expensive from getPackageInfo
, so it work faster.
Run 10000 on API 15
Exists pkg:
getPackageInfo: nanoTime = 930000000
getPackageGids: nanoTime = 350000000
Not exists pkg:
getPackageInfo: nanoTime = 420000000
getPackageGids: nanoTime = 380000000
Run 10000 on API 17
Exists pkg:
getPackageInfo: nanoTime = 2942745517
getPackageGids: nanoTime = 2443716170
Not exists pkg:
getPackageInfo: nanoTime = 2467565849
getPackageGids: nanoTime = 2479833890
Run 10000 on API 22
Exists pkg:
getPackageInfo: nanoTime = 4596551615
getPackageGids: nanoTime = 1864970154
Not exists pkg:
getPackageInfo: nanoTime = 3830033616
getPackageGids: nanoTime = 3789230769
Run 10000 on API 25
Exists pkg:
getPackageInfo: nanoTime = 3436647394
getPackageGids: nanoTime = 2876970397
Not exists pkg:
getPackageInfo: nanoTime = 3252946114
getPackageGids: nanoTime = 3117544269
Note: This will not work in some virtual spaces. They can violate the Android API and always return an array, even if there is no application with that package name.
In this case, use getPackageInfo
.
To be a little more concrete about how RSA uses properties of prime numbers, the RSA algorithm depends critically upon Euler's Theorem, which states that for relatively prime numbers "a" and "N", a^e is congruent to 1 modulo N, where e is the Euler's totient function of N.
Where do primes come into that? To compute the Euler's totient function of N efficiently requires knowing the prime factorization of N. In the case of the RSA algorithm, where N = pq for some primes "p" and "q", then e = (p - 1)(q - 1) = N - p - q + 1. But without knowing p and q, computation of e is very difficult.
More abstractly, many crypotgraphic protocols use various trapdoor functions, functions which are easy to compute but difficult to invert. Number theory is a rich source of such trapdoor functions (such as multiplication of large prime numbers), and prime numbers are absolutely central to number theory.
Your sheet is blank because your string writer in null. Here is what may help
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Here is the full code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
To remove the ", "
part which is immediately followed by end of string, you can do:
str = str.replaceAll(", $", "");
This handles the empty list (empty string) gracefully, as opposed to lastIndexOf
/ substring
solutions which requires special treatment of such case.
Example code:
String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str); // prints "kushalhs, mayurvm, narendrabz"
NOTE: Since there has been some comments and suggested edits about the ", $"
part: The expression should match the trailing part that you want to remove.
"a,b,c,"
, use ",$"
."a, b, c, "
, use ", $"
."a , b , c , "
, use " , $"
.I think you get the point.
GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
Any binary-to-text encoding will do the trick. I use something like that
<data encoding="yEnc>
<![CDATA[ encoded binary data ]]>
</data>
for mysql 'text':
@Column(columnDefinition = "TEXT")
private String description;
for mysql 'longtext':
@Lob
private String description;
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
just a different approach
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
will represent ascii of a.. and thus the other characters in the whole array.
I personally didn't find any of these answers helpful. What worked in my case was giving the element float:none
and position:relative
. After that the element centered itself in the <td>
.
Judging by the desktop folder location you are using Windows. The command in Windows would be:
adb pull /sdcard/log.txt %USERPROFILE%\Desktop\
I think by combining .children() with $(this) will return the children of the selected item only
consider the following:
$("div li").click(function() {
$(this).children().css('background','red');
});
this will change the background of the clicked li only
Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
select * from Tran_LibraryBooksTrans LBT left join
Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN' AND
LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
ELSE 0 END`enter code here`select * from Tran_LibraryBooksTrans LBT
left join Tran_LibraryIssuedBooks LIB ON case WHEN LBT.IssuedTo='SN'
AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
1 ELSE 0 END
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.
So an extension method such as...
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
...is one way to go about it.
You have to perform your search in the domain:
http://msdn.microsoft.com/en-us/library/ms677934(VS.85).aspx So, basically your should bind to a domain in order to search inside this domain.
And here is a bigint version of the same
DECLARE @ts BIGINT
SET @ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT @ts
Windows type
command works similarly to UNIX cat
.
Example 1: Merge with file names (This will merge file1.csv & file2.csv to create concat.csv)
type file1.csv file2.csv > concat.csv
Example 2: Merge files with pattern (This will merge all files with csv extension and create concat.csv)
When using asterisk(*) to concatenate all files. Please DON'T use same extension for target file(Eg. .csv). There should be some difference in pattern else target file will also be considered in concatenation
type *.csv > concat_csv.txt
From your original code it looks like what you want is to check if the list was empty:
var getResult= keyValueList.SingleOrDefault();
if (keyValueList.Count == 0)
{
/* default */
}
else
{
}
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
The provided solutions do resolve the issue. However, they also impact all other textarea
elements with the same styling. I had to solve this and just created a more specific selector. Here is what I came up with to prevent invasive changes.
.modal-content textarea.form-control {
max-width: 100%;
}
While this selector may seem aggressive. It helps restrain the textarea
into the content area of the modal itself.
Additionally, the min-width
solution presented, above, works with basic bootstrap modals, though I had issues when using it with angular-ui-bootstrap modals.
To show the value of an environment variable you use:
echo $VARIABLE
so in your case will be:
echo $JAVA_HOME
In case you don't have it setted, you can add in your .bashrc
file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
and it will dynamically change when you update your packages.
From the comments:
import msvcrt # built-in module
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:
#include <conio.h>
int kb_inkey () {
int rc;
int key;
key = _kbhit();
if (key == 0) {
rc = 0;
} else {
rc = _getch();
}
return rc;
}
And I access it in python using the ctypes module (built into python 2.5):
import ctypes
import time
#
# first, load the DLL
#
try:
kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
raise ("Error Loading PyKeyboardAccess.dll")
#
# now, find our function
#
try:
kbfunc = kblib.kb_inkey
except:
raise ("Could not find the kb_inkey function in the dll!")
#
# Ok, now let's demo the capability
#
while 1:
x = kbfunc()
if x != 0:
print "Got key: %d" % x
else:
time.sleep(.01)
I think you need some sort of regular expression matching (the following code is in Python 3):
import string
import re
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)
Output:
['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']
Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize
.
On my machine, if I run a script directly, the default is bash
.
If I run it with sudo
, the default is sh
.
That’s why I was hitting this problem when I used sudo
.
Here I am writing some sample code hoping this may be a rather tangible example to see the behaviors of the interfaces, abstract classes and ordinary classes on a very basic level. You can also find this code in github as a project if you want to use it as a demo: https://github.com/usavas/JavaAbstractAndInterfaceDemo
public interface ExampleInterface {
// public void MethodBodyInInterfaceNotPossible(){
// }
void MethodInInterface();
}
public abstract class AbstractClass {
public abstract void AbstractMethod();
// public abstract void AbstractMethodWithBodyNotPossible(){
//
// };
//Standard Method CAN be declared in AbstractClass
public void StandardMethod(){
System.out.println("Standard Method in AbstractClass (super) runs");
}
}
public class ConcreteClass
extends AbstractClass
implements ExampleInterface{
//Abstract Method HAS TO be IMPLEMENTED in child class. Implemented by ConcreteClass
@Override
public void AbstractMethod() {
System.out.println("AbstractMethod overridden runs");
}
//Standard Method CAN be OVERRIDDEN.
@Override
public void StandardMethod() {
super.StandardMethod();
System.out.println("StandardMethod overridden in ConcreteClass runs");
}
public void ConcreteMethod(){
System.out.println("Concrete method runs");
}
//A method in interface HAS TO be IMPLEMENTED in implementer class.
@Override
public void MethodInInterface() {
System.out.println("MethodInInterface Implemented by ConcreteClass runs");
// Cannot declare abstract method in a concrete class
// public abstract void AbstractMethodDeclarationInConcreteClassNotPossible(){
//
// }
}
}
My issue was also the firewall. I'm using a Linux server with WHM/cPanel. Adding my IP to the quick allow solved my issue. I hadn't updated Filezilla and I don't think there were any changes to the server that should have caused it. However, I did move and my IP changed so maybe that was the problem. Good luck to everyone else with this insanely annoying issue.
Not really and I am talking about SQL Server. The temp table (with single #) exists and is visible within the scope it is created (scope-bound). Each time you call your stored procedure it creates a new scope and therefore that temp table exists only in that scope. I believe the temp tables are also visible to stored procedures and udfs that're called within that scope as well. If you however use double pound (##) then they become global within your session and therefore visible to other executing processes as part of the session that the temp table is created in and you will have to think if the possibility of temp table being accessed concurrently is desirable or not.
I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:
input[type=text]::-ms-clear { display: none; }
One can even get less specific by using just:
::-ms-clear { display: none; }
I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.
Warning: Both solutions given ( astype() and apply() ) do not preserve NULL values in either the nan or the None form.
import pandas as pd
import numpy as np
df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A'])
df1 = df['A'].astype(str)
df2 = df['A'].apply(str)
print df.isnull()
print df1.isnull()
print df2.isnull()
I believe this is fixed by the implementation of to_string()
All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
you can create your own custom event by using diagnostics.Event log class. Open a windows application and on a button click do the following code.
System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "MyNewLog");
"MyNewLog" means the name you want to give to your log in event viewer.
for more information check this link [ http://msdn.microsoft.com/en-in/library/49dwckkz%28v=vs.90%29.aspx]
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
In Linux every process has its own folder in /proc
. So you could use getpid()
to get the pid of the running process and then join it with the path /proc
to get the folder you hopefully need.
Here's a short example in Python:
import os
print os.path.join('/proc', str(os.getpid()))
Here's the example in ANSI C as well:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int
main(int argc, char **argv)
{
pid_t pid = getpid();
fprintf(stdout, "Path to current process: '/proc/%d/'\n", (int)pid);
return EXIT_SUCCESS;
}
Compile it with:
gcc -Wall -Werror -g -ansi -pedantic process_path.c -oprocess_path
Is $target.remove();
what you're looking for?
I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:
// make_string
class make_string {
public:
template <typename T>
make_string& operator<<( T const & val ) {
buffer_ << val;
return *this;
}
operator std::string() const {
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
And then you use it as;
string str = make_string() << 6 << 8 << "hello";
Quite nifty!
Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)
// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
std::stringstream buf;
buf << str;
RETURN_TYPE val;
buf >> val;
return val;
}
Use as:
int x = parse_string<int>("78");
You might also want versions for wstrings.
Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.
Example:
import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)
Which result might you want if this were in a function in your problem?
The best answer would be to use XOR and to use it in one line would be cool.
(x ^= y), (y ^= x), (x ^= y);
x,y are variables and the comma between them introduces the sequence points so it does not become compiler dependent. Cheers!
Well nobody answered - which is in part the fault of the question : the input string contains eleven fields (this much can be inferred) but how many tabs ? Most possibly exactly 10. Then the answer is
String s = "\t2\t\t4\t5\t6\t\t8\t\t10\t";
String[] fields = s.split("\t", -1); // in your case s.split("\t", 11) might also do
for (int i = 0; i < fields.length; ++i) {
if ("".equals(fields[i])) fields[i] = null;
}
System.out.println(Arrays.asList(fields));
// [null, 2, null, 4, 5, 6, null, 8, null, 10, null]
// with s.split("\t") : [null, 2, null, 4, 5, 6, null, 8, null, 10]
If the fields happen to contain tabs this won't work as expected, of course.
The -1
means : apply the pattern as many times as needed - so trailing fields (the 11th) will be preserved (as empty strings (""
) if absent, which need to be turned to null
explicitly).
If on the other hand there are no tabs for the missing fields - so "5\t6"
is a valid input string containing the fields 5,6 only - there is no way to get the fields[]
via split.
An easy Method, Full control over 'from type' and 'to type', and only need to remember this code for future castings
DateTime.ParseExact(InputDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));
On windows, you can print with this command in your CLI
C:\Users\dir\env | more
You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
I'm not sure why previous answers haven't suggested that the original poster set up a shell profile (bashrc, .tcshrc, etc.) that executed their commands automatically every time they log in on the server side.
The quest that brought me to this page for help was a bit different -- I wanted multiple PuTTY shortcuts for the same host that would execute different startup commands.
I came up with two solutions, both of which worked:
(background) I have a folder with a variety of PuTTY shortcuts, each with the "target" property in the shortcut tab looking something like:
"C:\Program Files (x86)\PuTTY\putty.exe" -load host01
with each load corresponding to a PuTTY profile I'd saved (with different hosts in the "Session" tab). (Mostly they only differ in color schemes -- I like to have each group of related tasks share a color scheme in the terminal window, with critical tasks, like logging in as root on a production system, performed only in distinctly colored windows.)
The folder's Windows properties are set to very clean and stripped down -- it functions as a small console with shortcut icons for each of my frequent remote PuTTY and RDP connections.
(solution 1) As mentioned in other answers the -m switch is used to configure a script on the Windows side to run, the -t switch is used to stay connected, but I found that it was order-sensitive if I wanted to get it to run without exiting
What I finally got to work after a lot of trial and error was:
(shortcut target field):
"C:\Program Files (x86)\PuTTY\putty.exe" -t -load "SSH Proxy" -m "C:\Users\[me]\Documents\hello-world-bash.txt"
where the file being executed looked like
echo "Hello, World!"
echo ""
export PUTTYVAR=PROXY
/usr/local/bin/bash
(no semicolons needed)
This runs the scripted command (in my case just printing "Hello, world" on the terminal) and sets a variable that my remote session can interact with.
Note for debugging: when you run PuTTY it loads the -m script, if you edit the script you need to re-launch PuTTY instead of just restarting the session.
(solution 2) This method feels a lot cleaner, as the brains are on the remote Unix side instead of the local Windows side:
From Putty master session (not "edit settings" from existing session) load a saved config and in the SSH tab set remote command to:
export PUTTYVAR=GREEN; bash -l
Then, in my .bashrc, I have a section that performs different actions based on that variable:
case ${PUTTYVAR} in
"")
echo ""
;;
"PROXY")
# this is the session config with all the SSH tunnels defined in it
echo "";
echo "Special window just for holding tunnels open." ;
echo "";
PROMPT_COMMAND='echo -ne "\033]0;Proxy Session @master01\$\007"'
alias temppass="ssh keyholder.example.com makeonetimepassword"
alias | grep temppass
;;
"GREEN")
echo "";
echo "It's not easy being green"
;;
"GRAY")
echo ""
echo "The gray ghost"
;;
*)
echo "";
echo "Unknown PUTTYVAR setting ${PUTTYVAR}"
;;
esac
(solution 3, untried)
It should also be possible to have bash skip my .bashrc and execute a different startup script, by putting this in the PuTTY SSH command field:
bash --rcfile .bashrc_variant -l
Since Python is a better glue language, it may be easier to call the MATLAB part of your program from Python instead of vice-versa.
Check out Mlabwrap.
Nowdays, there is a new technique suggested by google to cache and improve your image rendering process:
<script src="lazysizes.min.js" async></script>
lazyload
class to your image:
<img data-src="images/flower3.png" class="lazyload" alt="">
I believe it's most commonly called the "splat operator." Unpacking arguments is what it does.
See type assertions here:
http://golang.org/ref/spec#Type_assertions
I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
instead of below Code
BEGIN
INSERT INTO EmailsRecebidos (De, Assunto, Data)
VALUES (@_DE, @_ASSUNTO, @_DATA)
WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos
WHERE De = @_DE
AND Assunto = @_ASSUNTO
AND Data = @_DATA);
END
replace with
BEGIN
IF NOT EXISTS (SELECT * FROM EmailsRecebidos
WHERE De = @_DE
AND Assunto = @_ASSUNTO
AND Data = @_DATA)
BEGIN
INSERT INTO EmailsRecebidos (De, Assunto, Data)
VALUES (@_DE, @_ASSUNTO, @_DATA)
END
END
Updated : (thanks to @Marc Durdin for pointing)
Note that under high load, this will still sometimes fail, because a second connection can pass the IF NOT EXISTS test before the first connection executes the INSERT, i.e. a race condition. See stackoverflow.com/a/3791506/1836776 for a good answer on why even wrapping in a transaction doesn't solve this.