You need to edit the Tomcat/conf/server.xml
and change the connector port. The connector setting should look something like this:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
Just change the connector port from default 8080 to another valid port number.
this should work, haven't tried though. this will exclude zero. NULL is excluded by default
AVG (CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)
I got this from EDX use it! its called recursion
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
I know this is an old question, but I came across a main thread one-liner that I use in both Kotlin and Java. This may not be the best solution for a service, but for calling something that will change the UI inside of a fragment this is extremely simple and obvious.
Java (8):
getActivity().runOnUiThread(()->{
//your main thread code
});
Kotlin:
this.runOnUiThread {
//your main thread code
}
version 4.7.1 was slightly different : for import:
import org.antlr.v4.runtime.*;
for the main segment - note the CharStreams:
CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
private int _my_int;
public int myInt;? _my_int? )
-as much as I like the _style of this and think it's readable I find it's arguably more trouble than it's worth, as it's uncommon and it's likely not to match anything else in the codebase you're using.
-automated code generation (e.g. eclipse's generate getters, setters) aren't likely to understand this so you'll have to fix it by hand or muck with eclipse enough to get it to recognize.
Ultimately, you're going against the rest of the (java) world's prefs and are likely to have some annoyances from that. And as previous posters have mentioned, consistency in the codebase trumps all of the above issues.
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
I know this question was specifically for jQuery, but for anyone using AngularJS that has this problem you can create a directive that handles this:
angular.module('app').directive('dropdownPreventClose', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function(e) {
e.stopPropagation(); //prevent the default behavior of closing the dropdown-menu
});
}
};
});
Then just add the attribute dropdown-prevent-close
to your element that is triggering the menu to close, and it should prevent it. For me, it was a select
element that automatically closed the menu:
<div class="dropdown-menu">
<select dropdown-prevent-close name="myInput" id="myInput" ng-model="myModel">
<option value="">Select Me</option>
</select>
</div>
If you don't care about legacy browsers:
if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )
if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:
if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )
C# compiler have only lambda
arg => arg.MyProperty
for infer type of arg(TModel) an type of arg.MyProperty(TProperty). It's impossible.
It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example:
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add _CRT_SECURE_NO_DEPRECATE to Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.
You can follow these tutorials to get started
Tutorials
Hello World Web Server (paid)
Node JS Processing Model – Single Threaded Model with Event Loop Architecture
Developer Sites
Videos
Screencasts
Books
Courses
Blogs
Podcasts
JavaScript resources
Node.js Modules
Other
First of all - you do not really want to try find literally all cycles because if there is 1 then there is an infinite number of those. For example A-B-A, A-B-A-B-A etc. Or it may be possible to join together 2 cycles into an 8-like cycle etc., etc... The meaningful approach is to look for all so called simple cycles - those that do not cross themselves except in the start/end point. Then if you wish you can generate combinations of simple cycles.
One of the baseline algorithms for finding all simple cycles in a directed graph is this: Do a depth-first traversal of all simple paths (those that do not cross themselves) in the graph. Every time when the current node has a successor on the stack a simple cycle is discovered. It consists of the elements on the stack starting with the identified successor and ending with the top of the stack. Depth first traversal of all simple paths is similar to depth first search but you do not mark/record visited nodes other than those currently on the stack as stop points.
The brute force algorithm above is terribly inefficient and in addition to that generates multiple copies of the cycles. It is however the starting point of multiple practical algorithms which apply various enhancements in order to improve performance and avoid cycle duplication. I was surprised to find out some time ago that these algorithms are not readily available in textbooks and on the web. So I did some research and implemented 4 such algorithms and 1 algorithm for cycles in undirected graphs in an open source Java library here : http://code.google.com/p/niographs/ .
BTW, since I mentioned undirected graphs : The algorithm for those is different. Build a spanning tree and then every edge which is not part of the tree forms a simple cycle together with some edges in the tree. The cycles found this way form a so called cycle base. All simple cycles can then be found by combining 2 or more distinct base cycles. For more details see e.g. this : http://dspace.mit.edu/bitstream/handle/1721.1/68106/FTL_R_1982_07.pdf .
If only the column names are available like :
cnms <- c("Nam1","Nam2","Nam3")
To create an empty data frame with the above variable names, first create a data.frame
object:
emptydf <- data.frame()
Now call zeroth element of every column, thus creating an empty data frame with the given variable names:
for( i in 1:length(cnms)){
emptydf[0,eval(cnms[i])]
}
If you know the list of ids try this query:
SELECT * FROM `Buses` WHERE BusId IN (`list of busIds`)
or if you pull them from another table list of busIds
could be another subquery:
SELECT * FROM `Buses` WHERE BusId IN (SELECT SomeId from OtherTable WHERE something = somethingElse)
If you need to compare to another table you need a join:
SELECT * FROM `Buses` JOIN OtheTable on Buses.BusesId = OtehrTable.BusesId
Full sync has few tasks:
git reset HEAD --hard
git clean -f
git pull origin master
Or else, what I prefer is that, I may create a new branch with the latest from the remote using:
git checkout origin/master -b <new branch name>
origin is my remote repository reference, and master is my considered branch name. These may different from yours.
You have everything right, but the problem is with getLine1Number()
function.
getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.
this method works only for few cell phone but not all phones.
So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber()
. It is always unique, valid and it always exists.
This one $("#yourDiv").load(" #yourDiv > *");
is the best if you are planning to just reload a <div>
Make sure to use an id
and not a class
. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
in the <head>
section of the html file, if you haven't already. In opposite case it won't work.
While there is still some truth to most of the answers above, I think they deserve an update:
Over the years the performance of SVG has improved a lot and now there is hardware-accelerated CSS transitions and animations for SVG that do not depend on JavaScript performance at all. Of course JavaScript performance has improved, too and with it the performance of Canvas, but not as much as SVG got improved. Also there is a "new kid" on the block that is available in almost all browsers today and that is WebGL. To use the same words that Simon used above: It beats both Canvas and SVG hands down. This doesn't mean it should be the go-to technology, though, since it's a beast to work with and it is only faster in very specific use-cases.
IMHO for most use-cases today, SVG gives the best performance/usability ratio. Visualizations need to be really complex (with respect to number of elements) and really simple at the same time (per element) so that Canvas and even more so WebGL really shine.
In this answer to a similar question I am providing more details, why I think that the combination of all three technologies sometimes is the best option you have.
You can use RSYNC to DELETE the large number of files
rsync -a --delete blanktest/ test/
Create blanktest folder with 0 files in it and command will sync your test folders with large number of files(I have deleted nearly 5M files using this method).
Thanks to http://www.slashroot.in/which-is-the-fastest-method-to-delete-files-in-linux
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
for example:
- for (var i = 0; i < 10; ++i) {
li= array[i]
- }
you may see https://github.com/visionmedia/jade for detailed document.
hope this might help someone else out there
SELECT
.... FROM XXX XX
WHERE
....
AND(
param1 IS NULL
OR XX.param1 = param1
)
SELECT CASE WHEN EXISTS (SELECT TOP 1 *
FROM dbo.[YourTable]
WHERE [YourColumn] = [YourValue])
THEN CAST (1 AS BIT)
ELSE CAST (0 AS BIT) END
This approach returns a boolean for you.
Value of string::npos is 18446744073709551615. Its a value returned if there is no string found.
Use where_in()
$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
I use PyCharm which has great capabilities to compare between folders and files.
Just open the parent folder for both repos and wait until it indexes. Then you can use right click on a folder or file and Compare to...
and pick the corresponding folder / file on the other side.
It shows not only what files are different but also their content. Much easier than command line.
The easiest solution I found to this problem was to downgrade the MySql from MySQL Workbench to MySQL Version 1.2.17. I had browsed some MySQL Forums, where it was said that the timeout time in MySQL Workbech has been hard coded to 600 and some suggested methods to change it didn't work for me. If someone is facing the same problem with workbench you could try downgrading too.
I had a very similar error message as you, although listing a particular file:
$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127
$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127
In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:
${LINEDETECTOR_OBJECTS}:\
../HoughLineAccumulator/houghlineaccumulator.hh # <-- missing slash!!
../HoughLineExtractor/houghlineextractor.hh
Hope that helps someone else who lands here from a search engine.
You can easily mock an extension method with JustMock. The API is the same as mocking normal method. Consider the following
public static string Echo(this Foo foo, string strValue)
{
return strValue;
}
To arrange and verify this method use the following:
string expected = "World";
var foo = new Foo();
Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);
string result = foo.Echo("Hello");
Assert.AreEqual(expected, result);
Here is also a link to the documentation: Extension Methods Mocking
Disclaimer. I am one of the developers responsible for JustMock.
The simplest way to handle multiple listagg's is to use 1 WITH (subquery factor) per column containing a listagg of that column from a select distinct:
WITH tab AS
(
SELECT 1 as col1, 2 as col2, 3 as col3, 'Smith' as created_by FROM dual
UNION ALL SELECT 1 as col1, 2 as col2, 3 as col3,'John' as created_by FROM dual
UNION ALL SELECT 1 as col1, 3 as col2, 4 as col3,'Ajay' as created_by FROM dual
UNION ALL SELECT 1 as col1, 4 as col2, 4 as col3,'Ram' as created_by FROM dual
UNION ALL SELECT 1 as col1, 5 as col2, 6 as col3,'Jack' as created_by FROM dual
)
, getCol2 AS
(
SELECT DISTINCT col1, listagg(col2,',') within group (order by col2) over (partition by col1) AS col2List
FROM ( SELECT DISTINCT col1,col2 FROM tab)
)
, getCol3 AS
(
SELECT DISTINCT col1, listagg(col3,',') within group (order by col3) over (partition by col1) AS col3List
FROM ( SELECT DISTINCT col1,col3 FROM tab)
)
select col1,col2List,col3List
FROM getCol2
JOIN getCol3
using (col1)
Which gives:
col1 col2List col3List
1 2,3,4,5 3,4,6
SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'
EDIT Adding additional info:
SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'
The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)
Another difference is that you may not have access to dba_source.
ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr
or per process
ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr |grep mysql
define MOD(a, b) ((((a)%(b))+(b))%(b))
As of V8 v7.0 / Chrome 70, V8 uses TimSort, Python's sorting algorithm. Chrome 70 was released on September 13, 2018.
See the the post on the V8 dev blog for details about this change. You can also read the source code or patch 1186801.
@roens is correct. This affects all Anaconda users, with below error
curl: (77) error setting certificate verify locations:
CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
The workaround is to use the default system curl and avoid messing with the prepended Anaconda PATH
variable. You can either
Rename the Anaconda curl binary :)
mv /path/to/anaconda/bin/curl /path/to/anaconda/bin/curl_anaconda
OR remove Anaconda curl
conda remove curl
$ which curl
/usr/bin/curl
[0] Anaconda Ubuntu curl Github issue https://github.com/conda/conda-recipes/issues/352
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
I can't answer all questions, but I will do my best.
As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.
Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.
WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).
In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.
Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.
About the protocol, as Wikipedia shows, it looks like this:
Client sends:
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
Server replies:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.
As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support
Upgrade: websocket
Connection: Upgrade
will reply with an error or with a page content.
The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.
function display(a){
var hours = Math.trunc(a/60);
var minutes = a % 60;
console.log(hours +":"+ minutes);
}
display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"
android:background="#64B5F6"
You can change the value after '#' according to your own specification or need depending on how you want to use them.
Here is a sample code:
<TextView_x000D_
android:text="Abir"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textSize="24sp"_x000D_
android:background="#D4E157" />
_x000D_
Thank you :)
Try below Alphanumeric regex
"^[a-zA-Z0-9]*$"
^ - Start of string
[a-zA-Z0-9]* - multiple characters to include
$ - End of string
See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Create two tables one after other, put second table in a div of fixed height and set the overflow property to auto. Also keep all the td's inside thead in second table empty.
<div>
<table>
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
<th>Head 4</th>
<th>Head 5</th>
</tr>
</thead>
</table>
</div>
<div style="max-height:500px;overflow:auto;">
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
</tbody>
</table>
</div>
caller
is forbidden in strict mode. Here is an alternative using the (non-standard) Error
stack.
The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.
'use strict';_x000D_
const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/;_x000D_
_x000D_
function fnName(str) {_x000D_
const regexResult = fnNameMatcher.exec(str);_x000D_
return regexResult[1] || regexResult[2];_x000D_
}_x000D_
_x000D_
function log(...messages) {_x000D_
const logLines = (new Error().stack).split('\n');_x000D_
const callerName = fnName(logLines[1]);_x000D_
_x000D_
if (callerName !== null) {_x000D_
if (callerName !== 'log') {_x000D_
console.log(callerName, 'called log with:', ...messages);_x000D_
} else {_x000D_
console.log(fnName(logLines[2]), 'called log with:', ...messages);_x000D_
}_x000D_
} else {_x000D_
console.log(...messages);_x000D_
}_x000D_
}_x000D_
_x000D_
function foo() {_x000D_
log('hi', 'there');_x000D_
}_x000D_
_x000D_
(function main() {_x000D_
foo();_x000D_
}());
_x000D_
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
mysqli_fetch_array()
returns NULL
if there is no row.
In procedural style:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}
I tried lashrah's answer and it worked after changing syntax a little bit. this is what worked for me:
@(
((HomeController)this.ViewContext.Controller).Method1();
)
Here is the working code for Swift 3 or above, to have a two-columns layout :
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let nbCol = 2
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(nbCol - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(nbCol))
return CGSize(width: size, height: size)
}
Feel free to change "nbCol" to your desired number of columns.
Use a comma to specify two (or more) different rules:
@media screen and (max-width: 995px),
screen and (max-height: 700px) {
...
}
From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Create a C# class that maps to your Json and use Newsoft JsonConvert
to Deserialise it.
For example:
public Class MyResponse
{
public Meta Meta { get; set; }
public Response Response { get; set; }
}
The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:
PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current
Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.
It is a list of the names of all installed printers on the system.
If you are using HTML Form element instead Laravel Form Builder, you must place method_field
between your
form opening tag and closing end. By doing this you may explicitly define form method type.
<form>
{{ method_field('PUT') }}
</form>
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
This answer is only for Linux Beginners.
Assuming initially the DB user didn't have file/folder(directory) permission on the client side.
Let's constrain ourselves to the following:
User: postgres
Purpose: You wanted to (write to / read from) a specific folder
Tool: psql
Connected to a specific database: YES
FILE_PATH: /home/user/training/sql/csv_example.csv
Query: \copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Actual Results: After running the query you got an error : Permission Denied
Expected Results: COPY COUNT_OF_ROWS_COPIED
Inside a terminal to view the permissions for a file/folder you need to long list them by entering the command ls -l
.
The output has a section that shows sth like this -> drwxrwxr-x
Which is interpreted in the following way:
TYPE | OWNER RIGHTS | GROUP RIGHTS | USER RIGHTS
rwx
(r: Read, W: Write, X: Execute)
TYPE (1 Char) = d: directory, -: file
OWNER RIGHTS (3 Chars after TYPE)
GROUP RIGHTS (3 Chars after OWNER)
USER RIGHTS (3 Chars after GROUP)
x
.This means for FILE_PATH, All the directories (home , user, training, sql) should have at least an x
in the USER RIGHTS.
x
. You can use chmod rights_you_want parent_folder
Assuming /training/
didn't have an execute permission.
I'd go the user folder and enter chmod a+x training
w
if you want to write to it. or at least a r
if you want to read from itAssuming /sql
didn't have a write permission.
I would now chmod a+w sql
sudo systemctl restart postgresql
This would most probably help you now get a successful expected result.
There is a plugin for Android Studio called “Mock Location Plugin”. You can emulate multiple points with this plugin. You can find a detailed manual of use in this link: Android Studio. Simulate multiple GPS points with Mock Location Plugin
$(function(){
$("input[type='submit']").click(function () {
$(this).attr("disabled", true);
});
});
thant's it.
If you do not want variables to be replaced, you need to surround EOL with single quotes.
cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
Previous example:
$ cat /tmp/myconfig.conf
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
A simple change in Num2 class like this:
super().__init__(num)
It works in python3.
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def __init__(self,num):
super().__init__(num)
self.n2 = num*2
def show(self):
print (self.n1,self.n2)
mynumber = Num2(8)
mynumber.show()
Of course! jQuery is just a library that utilizes javascript after all.
You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.
elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';
Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.
Note: As pointed out in the comments by @nevf, this solution may no longer work (at least in Chrome) due to performance changes. The recommendation is to use
touch-action
which is also suggested by @JohnWeisz's answer.
Similar to the answer given by @Llepwryd, I used a combination of ontouchstart
and ontouchmove
to prevent scrolling when it is on a certain element.
Taken as-is from a project of mine:
window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e)
{
if ($(e.target).closest('#mobileMenuHeader').length == 1)
{
blockMenuHeaderScroll = true;
}
});
$(window).on('touchend', function()
{
blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e)
{
if (blockMenuHeaderScroll)
{
e.preventDefault();
}
});
Essentially, what I am doing is listening on the touch start to see whether it begins on an element that is a child of another using jQuery .closest
and allowing that to turn on/off the touch movement doing scrolling. The e.target
refers to the element that the touch start begins with.
You want to prevent the default on the touch move event however you also need to clear your flag for this at the end of the touch event otherwise no touch scroll events will work.
This can be accomplished without jQuery however for my usage, I already had jQuery and didn't need to code something up to find whether the element has a particular parent.
Tested in Chrome on Android and an iPod Touch as of 2013-06-18
I made a really cool jQuery plugin for handling all varieties of ellipsis of text is one called ThreeDots @ http://tpgblog.com/threedots
It's much more flexible than the CSS approaches, and supports much more advanced, customizable behaviors and interactions.
Enjoy.
I'm using Rails 5 and the above answers work great; here's another way that also worked for me (the table name is :people
and the column name is :email_address
)
class AddIndexToEmailAddress < ActiveRecord::Migration[5.0]
def change
change_table :people do |t|
t.index :email_address, unique: true
end
end
end
This explains the whole thing:
The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.
The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.
This prints 10 lines of trailing context after matching lines
grep -i "my_regex" -A 10
If you need to print 10 lines of leading context before matching lines,
grep -i "my_regex" -B 10
And if you need to print 10 lines of leading and trailing output context.
grep -i "my_regex" -C 10
Example
user@box:~$ cat out
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$
Normal grep
user@box:~$ grep my_regex out
line 5 my_regex
user@box:~$
Grep exact matching lines and 2 lines after
user@box:~$ grep -A 2 my_regex out
line 5 my_regex
line 6
line 7
user@box:~$
Grep exact matching lines and 2 lines before
user@box:~$ grep -B 2 my_regex out
line 3
line 4
line 5 my_regex
user@box:~$
Grep exact matching lines and 2 lines before and after
user@box:~$ grep -C 2 my_regex out
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$
Reference: manpage grep
-A num
--after-context=num
Print num lines of trailing context after matching lines.
-B num
--before-context=num
Print num lines of leading context before matching lines.
-C num
-num
--context=num
Print num lines of leading and trailing output context.
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
SELECT TOP 2 [Id] FROM table
The best way to do this is to set display: inline;
. Note, however, that in inline display, you lose access to some layout properties, such as manual height and vertical margins, but this doesn't appear to be a problem for your page.
$(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
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
Actually if you need to test background fetch you need to enable one option in scheme:
Another way how you can test it:
Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, {'foo': 'bar'})
foo => bar
bar => default value
For some odd reason this DID NOT work (using Pandas: '0.25.1')
df[['col1', 'col2']].fillna(value=0, inplace=True)
Another solution:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Example:
df = pd.DataFrame(data={'col1':[1,2,np.nan,], 'col2':[1,np.nan,3], 'col3':[np.nan,2,3]})
output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 nan 2.00
2 nan 3.00 3.00
Apply list comp. to fillna values:
subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]
Output:
col1 col2 col3
0 1.00 1.00 nan
1 2.00 0.00 2.00
2 0.00 3.00 3.00
I think your basic requirement is to have a C/C++-like syntax in Python with the least headache possible. Although I liked Alexander Poluektov's answer it doesn't work for classes.
The following should work for classes. It works by distinguishing by the number of non-keyword arguments (but it doesn't support distinguishing by type):
class TestOverloading(object):
def overloaded_function(self, *args, **kwargs):
# Call the function that has the same number of non-keyword arguments.
getattr(self, "_overloaded_function_impl_" + str(len(args)))(*args, **kwargs)
def _overloaded_function_impl_3(self, sprite, start, direction, **kwargs):
print "This is overload 3"
print "Sprite: %s" % str(sprite)
print "Start: %s" % str(start)
print "Direction: %s" % str(direction)
def _overloaded_function_impl_2(self, sprite, script):
print "This is overload 2"
print "Sprite: %s" % str(sprite)
print "Script: "
print script
And it can be used simply like this:
test = TestOverloading()
test.overloaded_function("I'm a Sprite", 0, "Right")
print
test.overloaded_function("I'm another Sprite", "while x == True: print 'hi'")
Output:
This is overload 3
Sprite: I'm a Sprite
Start: 0
Direction: RightThis is overload 2
Sprite: I'm another Sprite
Script:
while x == True: print 'hi'
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.
PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.
When the browser sends p
in the querystring, it is received as a string, not an int. is_int()
will therefore always return false.
Instead try is_numeric()
or ctype_digit()
For what it's worth, here's a Sass mixin:
Usage:
@include gradientAnimation(red, blue, .6s);
Mixin:
@mixin gradientAnimation( $start, $end, $transTime ){
background-size: 100%;
background-image: linear-gradient($start, $end);
position: relative;
z-index: 100;
&:before {
background-image: linear-gradient($end, $start);
content: "";
display: block;
height: 100%;
position: absolute;
top: 0; left: 0;
opacity: 0;
width: 100%;
z-index: -100;
transition: opacity $transTime;
}
&:hover {
&:before {
opacity: 1;
}
}
}
Taken from this awesome post on Medium from Dave Lunny: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759
Needs installed excel as it uses the Excel.Application
com object.Save this as .bat
file:
@if (@X)==(@Y) @end /* JScript comment
@echo off
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%
@if (@X)==(@Y) @end JScript comment */
var ARGS = WScript.Arguments;
var xlCSV = 6;
var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;
var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);
objExcel.Quit();
It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:
call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"
First of all check the declaration of both the methods.
1) OrElse: Execute logic and pass result as argument.
public T orElse(T other) {
return value != null ? value : other;
}
2) OrElseGet: Execute logic if value inside the optional is null
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.
Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.
Optional.of(getModel())
.map(x -> {
//some logic
})
.orElse(getDefaultAndLogError());
getDefaultAndLogError() {
log.error("No Data found, Returning default");
return defaultValue;
}
Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.
Optional.of(getModel())
.map(x -> //some logic)
.orElse(getDefaultFromDb());
getDefaultFromDb() {
return dataBaseServe.getDefaultValue(); //api call, db call.
}
Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.
List<Model> list = new ArrayList<>();
Optional.of(getModel())
.map(x -> {
})
.orElse(get(list));
get(List < String > list) {
log.error("No Data found, Returning default");
list.add(defaultValue);
return defaultValue;
}
Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.
Key takeaways from this:
I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder
I was having this issue on my Mac. When you create the device if you change "Graphics" from "Automatic" to "Software" it fixes the issue, or it least it did for me.
In case you have both python 2 and 3 in your path, you can move up the Python27 folder in your path, so it search and executes python 2 first.
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);
The problem is that you are calling GetGridData
from a background thread. This method accesses several WPF controls which are bound to the main thread. Any attempt to access them from a background thread will lead to this error.
In order to get back to the correct thread you should use SynchronizationContext.Current.Post
. However in this particular case it seems like the majority of the work you are doing is UI based. Hence you would be creating a background thread just to go immediately back to the UI thread and do some work. You need to refactor your code a bit so that it can do the expensive work on the background thread and then post the new data to the UI thread afterwards
You can use Memurai for Windows, a Redis-compatible cache and datastore for Windows, currently compatible with Redis 5. Memurai aims to fulfill the need for a supported Redis-compatible datastore on the Windows platform. At its core, it’s based on Redis source code, ported to run natively on Windows, and it’s designed to provide the level of reliability and performance required for production environments. Memurai is free for development and testing. You can learn more and download Memurai at https://www.memurai.com.
Alexis Campailla
CEO, Memurai
To count all occurrences, use -o
. Try this:
echo afoobarfoobar | grep -o foo | wc -l
And man grep
of course (:
Some suggest to use just grep -co foo
instead of grep -o foo | wc -l
.
Don't.
This shortcut won't work in all cases. Man page says:
-c print a count of matching lines
Difference in these approaches is illustrated below:
1.
$ echo afoobarfoobar | grep -oc foo
1
As soon as the match is found in the line (a{foo}barfoobar
) the searching stops. Only one line was checked and it matched, so the output is 1
. Actually -o
is ignored here and you could just use grep -c
instead.
2.
$ echo afoobarfoobar | grep -o foo
foo
foo
$ echo afoobarfoobar | grep -o foo | wc -l
2
Two matches are found in the line (a{foo}bar{foo}bar
) because we explicitly asked to find every occurrence (-o
). Every occurence is printed on a separate line, and wc -l
just counts the number of lines in the output.
I had the same problem, and came up with a template that uses lockfile, a pid file that holds the process id number, and a kill -0 $(cat $pid_file)
check to make aborted scripts not stop the next run.
This creates a foobar-$USERID folder in /tmp where the lockfile and pid file lives.
You can still call the script and do other things, as long as you keep those actions in alertRunningPS
.
#!/bin/bash
user_id_num=$(id -u)
pid_file="/tmp/foobar-$user_id_num/foobar-$user_id_num.pid"
lock_file="/tmp/foobar-$user_id_num/running.lock"
ps_id=$$
function alertRunningPS () {
local PID=$(cat "$pid_file" 2> /dev/null)
echo "Lockfile present. ps id file: $PID"
echo "Checking if process is actually running or something left over from crash..."
if kill -0 $PID 2> /dev/null; then
echo "Already running, exiting"
exit 1
else
echo "Not running, removing lock and continuing"
rm -f "$lock_file"
lockfile -r 0 "$lock_file"
fi
}
echo "Hello, checking some stuff before locking stuff"
# Lock further operations to one process
mkdir -p /tmp/foobar-$user_id_num
lockfile -r 0 "$lock_file" || alertRunningPS
# Do stuff here
echo -n $ps_id > "$pid_file"
echo "Running stuff in ONE ps"
sleep 30s
rm -f "$lock_file"
rm -f "$pid_file"
exit 0
There's nothing wrong with your redirection of standard out to a file. Move and mkdir commands do not output anything. If you really need to have a log trail of those commands, then you'll need to explicitly echo to standard out indicating what you just executed.
The batch file, example:
@ECHO OFF
cd bob
ECHO I just did this: cd bob
Run from command line:
myfile.bat >> out.txt
or
myfile.bat > out.txt
Alternative solution if all above solutions are not working for you
By default, Volley set timeout equally for both setConnectionTimeout()
and setReadTimeout()
with the value from RetryPolicy
. In my case, Volley
throws timeout exception for large data chunk see:
com.android.volley.toolbox.HurlStack.openConnection().
My solution is create a class which extends HttpStack
with my own setReadTimeout()
policy. Then use it when creates RequestQueue
as follow:
Volley.newRequestQueue(mContext.getApplicationContext(), new MyHurlStack())
hooks can be executed when some condition is encountered. e.g. some variable changes or some action is called or some event happens. hooks can enter in the process and change things or react upon changes.
SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.*
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS')
ORDER BY emp_login_date
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value. 1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
Another option is to create a link in the button:
<button type="button"><a href="yourlink.com">Link link</a></button>
Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):
button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}
I have created a demo here.
try this,
$(".head h3").html("New header");
or
$(".head h3").text("New header");
remember class selectors returns all the matching elements.
I encountered the same error while using SpringBoot 2.1.4, along with Spring Security 5 (I believe). After one day of trying everything that Google had to offer, I discovered the cause of error in my case. I had a setup of micro-services, with the Auth server being different from the Resource Server. I had the following lines in my application.yml which prevented 'auto-configuration' despite of having included dependencies spring-boot-starter-security
, spring-security-oauth2
and spring-security-jwt
. I had included the following in the properties (during development) which caused the error.
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Commenting it out solved it for me.
#spring:
# autoconfigure:
# exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Hope, it helps someone.
I suggest you to create a scalar user defined function. This is an example (sorry in advance, because the variable names are in spanish):
CREATE FUNCTION [dbo].[Udf_ReplaceChars] (
@cadena VARCHAR(500), -- String to manipulate
@caracteresElim VARCHAR(100), -- String of characters to be replaced
@caracteresReem VARCHAR(100) -- String of characters for replacement
)
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE @cadenaFinal VARCHAR(500), @longCad INT, @pos INT, @caracter CHAR(1), @posCarER INT;
SELECT
@cadenaFinal = '',
@longCad = LEN(@cadena),
@pos = 1;
IF LEN(@caracteresElim)<>LEN(@caracteresReem)
BEGIN
RETURN NULL;
END
WHILE @pos <= @longCad
BEGIN
SELECT
@caracter = SUBSTRING(@cadena,@pos,1),
@pos = @pos + 1,
@posCarER = CHARINDEX(@caracter,@caracteresElim);
IF @posCarER <= 0
BEGIN
SET @cadenaFinal = @cadenaFinal + @caracter;
END
ELSE
BEGIN
SET @cadenaFinal = @cadenaFinal + SUBSTRING(@caracteresReem,@posCarER,1)
END
END
RETURN @cadenaFinal;
END
Here is an example using this function:
SELECT dbo.Udf_ReplaceChars('This is a test.','sat','Z47');
And the result is: 7hiZ iZ 4 7eZ7.
As you can see, each character of the @caracteresElim
parameter is replaced by the character in the same position from the @caracteresReem
parameter.
If you're using Anaconda to manage Python on your system, you can install it with:
$ conda install pyqt=4
Omit the =4
to install the most current version.
Answer from How to install PyQt4 in anaconda?
I just went through this myself and chose to set the default value at the reducer INIT function.
If you bind your select with redux then best not 'de-bind' it with a select default value that doesn't represent the actual value, instead set the value when you initialize the object.
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
This will stop the viewport jumping to the top by saving the scroll position and restoring it on enabling scrolling.
CSS
.no-scroll{
position: fixed;
width:100%;
min-height:100vh;
top:0;
left:0;
overflow-y:scroll!important;
}
JS
var scrollTopPostion = 0;
function scroll_pause(){
scrollTopPostion = $(window).scrollTop();
$("body").addClass("no-scroll").css({"top":-1*scrollTopPostion+"px"});
}
function scroll_resume(){
$("body").removeClass("no-scroll").removeAttr("style");
$(window).scrollTop(scrollTopPostion);
}
Now all you need to do is to call the functions
$(document).on("click","#DISABLEelementID",function(){
scroll_pause();
});
$(document).on("click","#ENABLEelementID",function(){
scroll_resume();
});
jQuery .height
will return you the height of the element. It doesn't need CSS definition as it determines the computed height.
You can use .height()
, .innerHeight()
or outerHeight()
based on what you need.
.height()
- returns the height of element excludes padding, border and margin.
.innerHeight()
- returns the height of element includes padding but excludes border and margin.
.outerHeight()
- returns the height of the div including border but excludes margin.
.outerHeight(true)
- returns the height of the div including margin.
Check below code snippet for live demo. :)
$(function() {_x000D_
var $heightTest = $('#heightTest');_x000D_
$heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
.append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
.append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
.append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
.append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE
which "shows the CREATE TABLE
statement that creates a given table, or the CREATE VIEW
statement that creates a given view."
Usage:
SHOW CREATE TABLE myTable;
2014 March: Truncating long strings with CSS: a new answer with focus on browser support
Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).
<style type="text/css">
span {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
-o-text-overflow: ellipsis; /** Opera 9 & 10 **/
width: 370px; /* note that this width will have to be smaller to see the effect */
}
</style>
<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>
The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.
Successfully tested (on Browserstack.com) on Windows OS, for web browsers:
Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).
I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).
Some further testing on a Mac OS web browsers would be needed.
Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated
Resources:
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.
Here is new path for changing iOS simulator you just need to change
default: 'iPhone 6' or something else
Path:
<project_root>/node_modules/@react-native-community/cli/build/commands/runIOS/runIOS.js
$('#id option').remove();
This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();
You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to * will accept cross-domain AJAX requests from any domain.
Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:
header("Access-Control-Allow-Origin: *");
Don't forget to enable mod_headers module in httpd.conf.
You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?
<link rel="stylesheet" href="CSS/main.css" type="text/css">
Just came across the same issue today...
In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:
list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)
If your XML goes quite deep, you might want to consider using XPath, which comes with your JRE, so you can access the contents far more easily using:
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
Full example:
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XPathTest {
private Document document;
@Before
public void setup() throws Exception {
String xml = "<add job=\"351\"><tag>foobar</tag><tag>foobar2</tag></add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(new InputSource(new StringReader(xml)));
}
@Test
public void testXPath() throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
assertEquals("foobar", text);
}
}
To change comma to semicolon as the default Excel separator for CSV - go to Region -> Additional Settings -> Numbers tab -> List separator and type ; instead of the default ,
I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.
The SQL*Plus® User's Guide and Reference gives an example:
sqlplus hr@\"sales-server:1521/sales.us.acme.com\"
Pay attention to two important points:
I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:
SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'
if you get this error "Value does not fall within the expected range" in this line:
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
use instead this to fix the error:
SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;
Use always URl to get Lists or others because they are unique, names are not the best way ;)
Your json isn't an array, it hasn't length property. You must change your data return or the way you get your data count.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
This was the only solution what worked for me:
Install Vagrant plugin: vagrant-vbguest, which can keep your VirtualBox Guest Additions up to date.
vagrant plugin install vagrant-vbguest
Source: https://github.com/aidanns/vagrant-reload/issues/4#issuecomment-230134083
You can try sed
if you like -
[jaypal:~/Temp] TESTSTRINGONE="MOTEST"
[jaypal:~/Temp] sed 's/\(.\{5\}\).*/\1/' <<< "$TESTSTRINGONE"
MOTES
If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;
hidePrefs(){
this.prefs = true;
}
This function from this answer is the best way to handle this as $.ready
explicitly fails for iframes. Here's the decision not to support this.
The load
event also doesn't fire if the iframe has already loaded. Very frustrating that this remains a problem in 2020!
function onIframeReady($i, successFn, errorFn) {
try {
const iCon = $i.first()[0].contentWindow,
bl = "about:blank",
compl = "complete";
const callCallback = () => {
try {
const $con = $i.contents();
if($con.length === 0) { // https://git.io/vV8yU
throw new Error("iframe inaccessible");
}
successFn($con);
} catch(e) { // accessing contents failed
errorFn();
}
};
const observeOnload = () => {
$i.on("load.jqueryMark", () => {
try {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href !== bl || src === bl || src === "") {
$i.off("load.jqueryMark");
callCallback();
}
} catch(e) {
errorFn();
}
});
};
if(iCon.document.readyState === compl) {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href === bl && src !== bl && src !== "") {
observeOnload();
} else {
callCallback();
}
} else {
observeOnload();
}
} catch(e) {
errorFn();
}
}
The proposed solution is just to much work for something that can be done like this:
Get-Alias -Definition Write*
If you really should use Double instead of double you even can get the int Value of Double by calling:
Double d = new Double(1.23);
int i = d.intValue();
Else its already described by Peter Lawreys answer.
Because without the PDB files, it would be impossible to debug a "Release" build by anything other than address-level debugging. Optimizations really do a number on your code, making it very difficult to find the culprit if something goes wrong (say, an exception is thrown). Even setting breakpoints is extremely difficult, because lines of source code cannot be matched up one-to-one with (or even in the same order as) the generated assembly code. PDB files help you and the debugger out, making post-mortem debugging significantly easier.
You make the point that if your software is ready for release, you should have done all your debugging by then. While that's certainly true, there are a couple of important points to keep in mind:
You should also test and debug your application (before you release it) using the "Release" build. That's because turning optimizations on (they are disabled by default under the "Debug" configuration) can sometimes cause subtle bugs to appear that you wouldn't otherwise catch. When you're doing this debugging, you'll want the PDB symbols.
Customers frequently report edge cases and bugs that only crop up under "ideal" conditions. These are things that are almost impossible to reproduce in the lab because they rely on some whacky configuration of that user's machine. If they're particularly helpful customers, they'll report the exception that was thrown and provide you with a stack trace. Or they'll even let you borrow their machine to debug your software remotely. In either of those cases, you'll want the PDB files to assist you.
Profiling should always be done on "Release" builds with optimizations enabled. And once again, the PDB files come in handy, because they allow the assembly instructions being profiled to be mapped back to the source code that you actually wrote.
You can't go back and generate the PDB files after the compile.* If you don't create them during the build, you've lost your opportunity. It doesn't hurt anything to create them. If you don't want to distribute them, you can simply omit them from your binaries. But if you later decide you want them, you're out of luck. Better to always generate them and archive a copy, just in case you ever need them.
If you really want to turn them off, that's always an option. In your project's Properties window, set the "Debug Info" option to "none" for any configuration you want to change.
Do note, however, that the "Debug" and "Release" configurations do by default use different settings for emitting debug information. You will want to keep this setting. The "Debug Info" option is set to "full" for a Debug build, which means that in addition to a PDB file, debugging symbol information is embedded into the assembly. You also get symbols that support cool features like edit-and-continue. In Release mode, the "pdb-only" option is selected, which, like it sounds, includes only the PDB file, without affecting the content of the assembly. So it's not quite as simple as the mere presence or absence of PDB files in your /bin
directory. But assuming you use the "pdb-only" option, the PDB file's presence will in no way affect the run-time performance of your code.
* As Marc Sherman points out in a comment, as long as your source code has not changed (or you can retrieve the original code from a version-control system), you can rebuild it and generate a matching PDB file. At least, usually. This works well most of the time, but the compiler is not guaranteed to generate identical binaries each time you compile the same code, so there may be subtle differences. Worse, if you have made any upgrades to your toolchain in the meantime (like applying a service pack for Visual Studio), the PDBs are even less likely to match. To guarantee the reliable generation of ex postfacto PDB files, you would need to archive not only the source code in your version-control system, but also the binaries for your entire build toolchain to ensure that you could precisely recreate the configuration of your build environment. It goes without saying that it is much easier to simply create and archive the PDB files.
CSS:
.auto { cursor: auto; }
.default { cursor: default; }
.none { cursor: none; }
.context-menu { cursor: context-menu; }
.help { cursor: help; }
.pointer { cursor: pointer; }
.progress { cursor: progress; }
.wait { cursor: wait; }
.cell { cursor: cell; }
.crosshair { cursor: crosshair; }
.text { cursor: text; }
.vertical-text { cursor: vertical-text; }
.alias { cursor: alias; }
.copy { cursor: copy; }
.move { cursor: move; }
.no-drop { cursor: no-drop; }
.not-allowed { cursor: not-allowed; }
.all-scroll { cursor: all-scroll; }
.col-resize { cursor: col-resize; }
.row-resize { cursor: row-resize; }
.n-resize { cursor: n-resize; }
.e-resize { cursor: e-resize; }
.s-resize { cursor: s-resize; }
.w-resize { cursor: w-resize; }
.ns-resize { cursor: ns-resize; }
.ew-resize { cursor: ew-resize; }
.ne-resize { cursor: ne-resize; }
.nw-resize { cursor: nw-resize; }
.se-resize { cursor: se-resize; }
.sw-resize { cursor: sw-resize; }
.nesw-resize { cursor: nesw-resize; }
.nwse-resize { cursor: nwse-resize; }
You can also have the cursor be an image:
.img-cur {
cursor: url(images/cursor.png), auto;
}
javac doesn't actively prohibit this, but it does have a limitation that pretty much means that you'd never want to refer to a top-level class from another file unless it has the same name as the file it's in.
Suppose you have two files, Foo.java and Bar.java.
Foo.java contains:
Bar.java contains:
Let's also say that all of the classes are in the same package (and the files are in the same directory).
What happens if Foo.java refers to Baz but not Bar and we try to compile Foo.java? The compilation fails with an error like this:
Foo.java:2: cannot find symbol
symbol : class Baz
location: class Foo
private Baz baz;
^
1 error
This makes sense if you think about it. If Foo.java refers to Baz, but there is no Baz.java (or Baz.class), how can javac know what source file to look in?
If you instead tell javac to compile Foo.java and Bar.java at the same time, or even if you had previously compiled Bar.java (leaving the Baz.class where javac can find it) then this error goes away. This makes your build process feel very unreliable and flaky, however.
Because the actual limitation, which is more like "don't refer to a top-level class from another file unless it has the same name as the file it's in or you're also referring to a class that's in that same file that's named the same thing as the file" is kind of hard to follow, people usually go with the much more straightforward (though stricter) convention of just putting one top-level class in each file. This is also better if you ever change your mind about whether a class should be public or not.
Sometimes there really is a good reason why everybody does something in a particular way.
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
For both / and \:
window.location.pathname.replace(/[^\\\/]*$/, '');
To return without the trailing slash, do:
window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
Instead of Activity use context.It works for me.
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
Just use
filter_input(INPUT_METHOD_NAME, 'var_name')
instead of $_INPUT_METHOD_NAME['var_name']
filter_input_array(INPUT_METHOD_NAME)
instead of $_INPUT_METHOD_NAME
e.g
$host= filter_input(INPUT_SERVER, 'HTTP_HOST');
echo $host;
instead of
$host= $_SERVER['HTTP_HOST'];
echo $host;
And use
var_dump(filter_input_array(INPUT_SERVER));
instead of
var_dump($_SERVER);
N.B: Apply to all other Super Global variable
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
The formal difference -
The difference in usage:
object
. You can use it with or without related class. In 1st case it's called a companion object. You have to:
To create a program you should use main method in object
, not in class
.
object Hello {
def main(args: Array[String]) {
println("Hello, World!")
}
}
You also may use it as you use singleton object in java.
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.
Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp
.
You could also use http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();
You need to use document.write()
<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write()
will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.
you can start with this tool, https://themestr.app/theme , seeing how it overwrites the scss variables, you would get an idea what variable impacts what. its the simplest way I think.
example scss genearation:
@import url(https://fonts.googleapis.com/css?family=Montserrat:200,300,400,700);
$font-family-base:Montserrat;
@import url(https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,700);
$headings-font-family:Open Sans;
$enable-grid-classes:false;
$primary:#222222;
$secondary:#666666;
$success:#333333;
$danger:#434343;
$info:#515151;
$warning:#5f5f5f;
$light:#eceeec;
$dark:#111111;
@import "bootstrap";
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
I would echo what Wyzard wrote but add that:
URLEncoder
should not be usedI wrote a blog post a while back about this subject: Java: safe character handling and URL building
I guess you had an error in the inline code of your image. Try this :
var image = document.createElement('img');_x000D_
_x000D_
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";_x000D_
_x000D_
image.width=100;_x000D_
image.height=100;_x000D_
image.alt="here should be some image";_x000D_
_x000D_
document.body.appendChild(image);
_x000D_
Helpful link :http://dean.edwards.name/my/base64-ie.html
if not exists (select * from sysobjects where name='cars' and xtype='U')
create table cars (
Name varchar(64) not null
)
go
The above will create a table called cars
if the table does not already exist.
Reinstalling Compass worked for me.. It's a magic!
sudo gem install -n /usr/local/bin compass
Yet another possibility to check, it was my problem this time.
I had added the function to the library, and included the library's output folder in the search path.
But I also had a folder with an older version of the library listed before, so VS was using the old library, and of course not finding the new function.
I had to add my current IP address (again) to the Atlas MongoDB whitelist and so got rid of the XMLHttpRequest status 0 error
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
You can try this it'll convert the date format to DD-MM-YYYY:
df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)
There is also the DateTime
object if you want to go that way: http://www.php.net/manual/en/datetime.construct.php
The loc
parameter specifies in which corner of the bounding box the legend is placed. The default for loc
is loc="best"
which gives unpredictable results when the bbox_to_anchor
argument is used.
Therefore, when specifying bbox_to_anchor
, always specify loc
as well.
The default for bbox_to_anchor
is (0,0,1,1)
, which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.
Below is an example where the bounding box is set to position (0.6,0.5)
(green dot) and different loc
parameters are tested. Because the legend extents outside the bounding box, the loc
parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
ax.set_title(l)
ax.plot([1,2,3],[2,3,1], "b-", label="blue")
ax.plot([1,2,3],[1,2,1], "r-", label="red")
ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)
plt.tight_layout()
plt.show()
See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .
bbox_transform
argument. If may make sense to use figure coordinates
ax.legend(bbox_to_anchor=(1,0), loc="lower right", bbox_transform=fig.transFigure)
It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData
.
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
I got asked a similar question in a test.
Find a number's length without converting to string
const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0]
const numberLength = number => {
let length = 0
let n = Math.abs(number)
do {
n /= 10
length++
} while (n >= 1)
return length
}
console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ]
Negative numbers were added to complicate it a little more, hence the Math.abs().
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.
for(int i = 0; i < list.Count; i++){
if(i == 5)
i = list.Count; //it will make "i<list.Count" false and loop will exit
}
Expanding on Jakub’s answer and Joe’s tip, the following will strip out the "refs/heads/" so the output only displays the branch names:
git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'
You can use a combination of UCASE()
, MID()
and CONCAT()
:
SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
use: docker container stop $(docker container ls -q --filter ancestor=mongo)
(base) :~ user$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d394144acf3a mongo "docker-entrypoint.s…" 15 seconds ago Up 14 seconds 0.0.0.0:27017->27017/tcp magical_nobel
(base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
d394144acf3a
(base) :~ user$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
(base) :~ user$
unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
Note that the variables @fname
or @ext
can be simply concatenated. This:
forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"
renames all PDF files to "filename_old.pdf"
Edit two - This code is an ugly, ugly kluge from olden days. You do not want it.
This compresses the contents of .\in
to .\out.zip
with System.IO.Packaging.ZipPackage following the example here
$zipArchive = $pwd.path + "\out.zip"
[System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
$ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipArchive,
[System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
$in = gci .\in | select -expand fullName
[array]$files = $in -replace "C:","" -replace "\\","/"
ForEach ($file In $files)
{
$partName=New-Object System.Uri($file, [System.UriKind]"Relative")
$part=$ZipPackage.CreatePart($partName, "application/zip",
[System.IO.Packaging.CompressionOption]"Maximum")
$bytes=[System.IO.File]::ReadAllBytes($file)
$stream=$part.GetStream()
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
}
$ZipPackage.Close()
Edit: Unreliable for larger files, maybe >10mb, YMMV. Something to do with appdomain evidence and isolated storage. The friendlier .NET 4.5 approach works nicely from PS v3, but wanted more memory in my case. To use .NET 4 from PS v2, config files need an unsupported tweak.
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Try this (the negative in front of the x is valid since it is a unary operator, find more here):
int answer = -x;
With this, you can turn a positive to a negative and a negative to a positive.
However, if you want to only make a negative number positive then try this:
int answer = Math.abs(x);
A little cool math trick! Squaring the number will guarantee a positive value of x^2, and then, taking the square root will get you to the absolute value of x:
int answer = Math.sqrt(Math.pow(x, 2));
Hope it helps! Good Luck!
I don't know if my answer would make sense to many, but I too faced the same issue and the solution was outrageously simple. All I had to do was to open the program which I used to run the code as an administrator. (right-click --> Run as Administrator).
That was all.
Instead of QString::number()
i would use QLocale::toString()
, so i can get locale aware group seperatores like german "1.234.567,89".
I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.
However, it does not cover the addHitRegion
API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla
Simple solution if you need to ignore everything except few files and few root folders:
/*
!.gitignore
!showMe.txt
!my_visible_dir
The magic is in /*
(as described above) it ignores everything in the (root) folder BUT NOT recursively.
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.
<select defaultValue={'DEFAULT'} >
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
Here the user is forced to pick an option!
EDIT
If this is a controlled component
In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.
function TheSelectComponent(props){
let currentValue = props.curentValue || "DEFAULT";
return(
<select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
)
}
I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?
This is how you could do that:
while True: # repeat until the try statement succeeds
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need
break # exit the loop
except IOError:
input("Could not open file! Please close Excel. Press Enter to retry.")
# restart the loop
with myfile:
do_stuff()
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
This is a common code adapted from another examples:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
# ... take the code from the options below
# Load a page
driver.get('http://bings.com')
# Make the tests...
# close the tab
driver.quit()
the possible ways were:
Sending <CTRL> + <T>
to one element
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
Sending <CTRL> + <T>
via Action chains
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Execute a javascript snippet
driver.execute_script('''window.open("http://bings.com","_blank");''')
In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 3)
fp.set_preference("browser.link.open_newwindow.restriction", 2)
driver = webdriver.Firefox(browser_profile=fp)
the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.
In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:
FirefoxOptions options = new FirefoxOptions().setProfile(fp);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 2);
FirefoxDriver driver = new FirefoxDriver(options);
The third option did stop working for python in selenium 3.4.0.
The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)
driver = webdriver.Firefox(browser_profile=fp)
... and then you can use successfully the first way.
Just an improved version to nkron responce.
const httpGet = url => {
return new Promise((resolve, reject) => {
http.get(url, res => {
res.setEncoding('utf8');
const body = [];
res.on('data', chunk => body.push(chunk));
res.on('end', () => resolve(body.join('')));
}).on('error', reject);
});
};
Appending chunks in an string[] is better for memory usage, the join(''), will allocate new memory only once.
None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.
the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind
/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
EmpID int,
Activity varchar(20),
DoneBy varchar(50),
Date_Time datetime NOT NULL DEFAULT GETDATE()
);
select * from Emp_Audit*/
create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
SET @activity = 'UPDATE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end
If exists (Select * from inserted) and not exists(Select * from deleted)
begin
SET @activity = 'INSERT';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
If exists(select * from deleted) and not exists(Select * from inserted)
begin
SET @activity = 'DELETE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from deleted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
save the file on your disk and then use the following as URL:
file://your_path/your_file.wsdl
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
using (html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
include angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
add ngSanitize
in root angular app
var app = angular.module("app", ["ngSanitize"]);
using (html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
As of version 0.8.6 of Android Studio generating an APK file (signed and I believe unsigned, too) will be placed inside ProjectName/device/build/outputs/apk
For example, I am making something for Google Glass and my signed APK gets dropped in /Users/MyName/AndroidStudioProjects/HelloGlass/glass/build/outputs/apk
You can just use the -R (recursive) flag.
chmod -R 777 /Users/Test/Desktop/PATH
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..
Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
If you're running Python 3.4+, you can use the pathlib
module. The Path.glob()
method supports the **
pattern, which means “this directory and all subdirectories, recursively”. It returns a generator yielding Path
objects for all matching files.
from pathlib import Path
configfiles = Path("C:/Users/sam/Desktop/file1/").glob("**/*.txt")
You can create an in-memory temporary table and store them in hive table using sqlContext.
Lets say your data frame is myDf. You can create one temporary table using,
myDf.createOrReplaceTempView("mytempTable")
Then you can use a simple hive statement to create table and dump the data from your temp table.
sqlContext.sql("create table mytable as select * from mytempTable");
So the issue is actually that you are not waiting for the init to complete. This will cause random results. Here is what I use.
window.fbAsyncInit = function () {
FB.init({ appId: 'your-app-id', cookie: true, xfbml: true, oauth: true });
// *** here is my code ***
if (typeof facebookInit == 'function') {
facebookInit();
}
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
This will ensure that once everything is loaded, the function facebookInit is available and executed. That way you don't have to duplicate the init code every time you want to use it.
function facebookInit() {
// do what you would like here
}
In fact, you can't change the time once it's created. But you can create it easily with many constructors: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2
For example, if you want to create a DateTime changing Seconds, you can just do this:
DateTime now = DateTime.Now;
DateTime secondschanged = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, yourseconds);
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Using react hooks, you can do following way
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
GridView
is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count
. However, you should note that a GridView
is scrollable, and if that isn't what you want, you may be better off with just rows and columns.
import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.orange,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
title: new Text('Grid Demo'),
),
body: new GridView.count(
crossAxisCount: 4,
children: new List<Widget>.generate(16, (index) {
return new GridTile(
child: new Card(
color: Colors.blue.shade200,
child: new Center(
child: new Text('tile $index'),
)
),
);
}),
),
);
}
}
See this example, initializes the map to "San Diego, CA".
Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address ="San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%">
</body>
</html>
working code snippet:
var geocoder;
var map;
var address = "San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
_x000D_
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
_x000D_
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
_x000D_
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
I'd recommend this if you use native Javascript.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
You need to get the PropertyInfo
associated with the property (e.g. via typeof(Class1).GetProperty("Name")
) and then call GetCustomAttributes
.
It's a bit messy due to returning multiple values - you may well want to write a helper method to do this if you need it from a few places. (There may already be a helper method in the framework somewhere, but if there is I'm unaware of it.)
EDIT: As leppie pointed out, there is such a method: Attribute.GetCustomAttribute(MemberInfo, Type)
Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
More on wordpress.org:
const special = ':;"<>?/!`~@#$%^&*()+=-_ '.split("");
const trim = (input) => {
const inTrim = (str) => {
const spStr = str.split("");
let deleteTill = 0;
let startChar = spStr[deleteTill];
while (special.some((s) => s === startChar)) {
deleteTill++;
if (deleteTill <= spStr.length) {
startChar = spStr[deleteTill];
} else {
deleteTill--;
break;
}
}
spStr.splice(0, deleteTill);
return spStr.join("");
};
input = inTrim(input);
input = inTrim(input.split("").reverse().join("")).split("").reverse().join("");
return input;
};
alert(trim('@#This is what I use$%'));
_x000D_
Necromancing.
The provided answers are incomplete.
First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.
It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.
This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.
// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{
public System.Web.HttpBrowserCapabilities Browser { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string Platform { get; set; }
public bool IsMobileDevice { get; set; }
public string MobileBrand { get; set; }
public string MobileModel { get; set; }
public BrowserInfo(System.Web.HttpRequest request)
{
if (request.Browser != null)
{
if (request.UserAgent.Contains("Edge")
&& request.Browser.Browser != "Edge")
{
this.Name = "Edge";
}
else
{
this.Name = request.Browser.Browser;
this.Version = request.Browser.MajorVersion.ToString();
}
this.Browser = request.Browser;
this.Platform = request.Browser.Platform;
this.IsMobileDevice = request.Browser.IsMobileDevice;
if (IsMobileDevice)
{
this.Name = request.Browser.Browser;
}
}
}
}
void context_EndRequest(object sender, System.EventArgs e)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
try
{
// response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
// response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AppendHeader("X-Frame-Options", "DENY");
// response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
// response.AppendHeader("X-Frame-Options", "AllowAll");
if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
{
// "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome
string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
+ System.Web.HttpContext.Current.Request.UrlReferrer.Authority
;
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
// SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);
if (IsHostAllowed(refAuth))
{
BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);
// bi.Name = Firefox
// bi.Name = InternetExplorer
// bi.Name = Chrome
// Chrome wants entire path...
if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
// unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
// unsafe-inline: styles
// data: url(data:image/png:...)
// https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
// https://www.ietf.org/rfc/rfc7034.txt
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
// https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
// https://content-security-policy.com/
// http://rehansaeed.com/content-security-policy-for-asp-net-mvc/
// This is for Chrome:
// response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
ls.Add("default-src");
ls.Add("'self'");
ls.Add("'unsafe-inline'");
ls.Add("'unsafe-eval'");
ls.Add("data:");
// http://az416426.vo.msecnd.net/scripts/a/ai.0.js
// ls.Add("*.msecnd.net");
// ls.Add("vortex.data.microsoft.com");
ls.Add(selfAuth);
ls.Add(refAuth);
string contentSecurityPolicy = string.Join(" ", ls.ToArray());
response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
}
else
{
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
}
else
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
catch (System.Exception ex)
{
// WTF ?
System.Console.WriteLine(ex.Message); // Suppress warning
}
} // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
} // End Using context_EndRequest
private static string[] s_allowedHosts = new string[]
{
"localhost:49533"
,"localhost:52257"
,"vmcompany1"
,"vmcompany2"
,"vmpostalservices"
,"example.com"
};
public static bool IsHostAllowed(string host)
{
return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed
public static bool Contains(string[] allowed, string current)
{
for (int i = 0; i < allowed.Length; ++i)
{
if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
return true;
} // Next i
return false;
} // End Function Contains
You need to register the context_EndRequest function in the HTTP-module Init function.
public class RequestLanguageChanger : System.Web.IHttpModule
{
void System.Web.IHttpModule.Dispose()
{
// throw new NotImplementedException();
}
void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
{
// https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
context.EndRequest += new System.EventHandler(context_EndRequest);
}
// context_EndRequest Code from above comes here
}
Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:
namespace ChangeRequestLanguage
{
public class Global : System.Web.HttpApplication
{
System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();
public override void Init()
{
mod.Init(this);
base.Init();
}
protected void Application_Start(object sender, System.EventArgs e)
{
}
protected void Session_Start(object sender, System.EventArgs e)
{
}
protected void Application_BeginRequest(object sender, System.EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
{
}
protected void Application_Error(object sender, System.EventArgs e)
{
}
protected void Session_End(object sender, System.EventArgs e)
{
}
protected void Application_End(object sender, System.EventArgs e)
{
}
}
}
or you can add entries to Web.config if you don't own the application source-code:
<httpModules>
<add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</modules>
</system.webServer>
</configuration>
The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.
The string in type is in the format "Namespace.Class, Assembly"
.
Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like
"[DefaultNameSpace.Namespace].Class, Assembly"
If you want to avoid this problem, write the DLL in C#.